diff --git a/public_html/assets/api/daily.php b/public_html/assets/api/daily.php
new file mode 100644
index 0000000..7f3a0e4
--- /dev/null
+++ b/public_html/assets/api/daily.php
@@ -0,0 +1,1215 @@
+normalizeDailyPayload($data, $existing ?: null);
+ $data = $this->hydrateDailySnapshot($data, $existing ?: null);
+
+ // estquantity 자동 계산
+ if (empty($data['d_estquantity'])) {
+ $data['d_estquantity'] = $this->calculateEstQuantity($data, $existing);
+ }
+
+ // note 백업 (tbl_note 로 전달할 값)
+ $noteForUpsert = $data['d_note'] ?? '';
+ $pickupNoteForUpsert = $data['d_pickupnote'] ?? '';
+ $level = $data['d_level'] ?? 9;
+
+ // =========================
+ // 컬럼 필터링
+ // =========================
+ $allowed = $this->getDailyColumns();
+ $data = array_intersect_key($data, array_flip($allowed));
+
+ // =========================
+ // UPDATE
+ // =========================
+ if ($isUpdate) {
+
+ $setParts = [];
+
+ foreach ($data as $k => $v) {
+
+ if (in_array($k, ['d_orderdate','d_accountno','d_jobtype'], true)) continue;
+ if (!array_key_exists($k, $existing)) continue;
+
+ $setParts[] = "{$k}='" . mysqli_real_escape_string($connect, (string)$v) . "'";
+ }
+
+ $setParts[] = "d_modifydate='{$now14}'";
+
+ if (!empty($setParts)) {
+
+ // update는 무조건 d_uid 기준으로
+ $uid = (int)$existing['d_uid'];
+
+ $sql = "
+ UPDATE tbl_daily
+ SET " . implode(",", $setParts) . "
+ WHERE d_uid='{$uid}'
+ LIMIT 1
+ ";
+
+ if (!mysqli_query($connect, $sql)) {
+ throw new Exception(mysqli_error($connect));
+ }
+ }
+ }
+
+ // =========================
+ // INSERT
+ // =========================
+ else {
+
+ $cols = [];
+ $vals = [];
+
+ foreach ($data as $k => $v) {
+ $cols[] = $k;
+ $vals[] = "'" . mysqli_real_escape_string($connect, (string)$v) . "'";
+ }
+
+ if (!in_array('d_modifydate', $cols)) {
+ $cols[] = 'd_modifydate';
+ $vals[] = "'{$now14}'";
+ }
+
+ $sql = "
+ INSERT INTO tbl_daily (" . implode(",", $cols) . ")
+ VALUES (" . implode(",", $vals) . ")
+ ";
+
+ if (!mysqli_query($connect, $sql)) {
+ throw new Exception(mysqli_error($connect));
+ }
+ }
+
+ // =========================
+ // AFTER RELOAD (uid 기준)
+ // =========================
+ if ($isUpdate) {
+ $uid = (int)$existing['d_uid'];
+ $res = mysqli_query($connect, "
+ SELECT *
+ FROM tbl_daily
+ WHERE d_uid='{$uid}'
+ LIMIT 1
+ ");
+ } else {
+ $res = mysqli_query($connect, "
+ SELECT *
+ FROM tbl_daily
+ WHERE d_orderdate='{$d_orderdate}'
+ AND d_accountno='{$d_accountno}'
+ AND d_jobtype = '{$d_jobtype}'
+ ORDER BY d_uid DESC
+ LIMIT 1
+ ");
+ }
+
+ $afterData = mysqli_fetch_assoc($res);
+ // note
+ if ($noteForUpsert !== '') {
+ $afterData['d_note'] = $noteForUpsert;
+ $afterData['d_level'] = $level;
+ }
+
+ if ($pickupNoteForUpsert !== '') {
+ $afterData['d_pickupnote'] = $pickupNoteForUpsert;
+ $afterData['d_level'] = $level;
+ }
+
+ // =========================
+ // ERP OUTBOX
+ // =========================
+ $event_type = $isUpdate ? 'DAILY_UPDATED' : 'DAILY_CREATED';
+
+ $payload = mysqli_real_escape_string(
+ $connect,
+ json_encode([
+ 'key' => [
+ 'd_orderdate'=>$afterData['d_orderdate'],
+ 'd_accountno'=>$afterData['d_accountno'],
+ 'd_jobtype'=>$afterData['d_jobtype']
+ ],
+ 'before'=>$beforeData,
+ 'after'=>$afterData
+ ], JSON_UNESCAPED_UNICODE)
+ );
+
+ mysqli_query($connect, "
+ INSERT INTO tbl_erp_outbox
+ (eo_event_type, eo_key_date, eo_key_accountno, eo_key_jobtype, eo_payload, eo_status, eo_created_at)
+ VALUES
+ ('{$event_type}',
+ '{$afterData['d_orderdate']}',
+ '{$afterData['d_accountno']}',
+ '{$afterData['d_jobtype']}',
+ '{$payload}',
+ 'PENDING',
+ NOW())
+ ");
+
+ // =========================
+ // AFTER WORK
+ // =========================
+ $this->runAfterSave($beforeData, $afterData, $opt);
+
+ // =========================
+ // COMMIT
+ // =========================
+ if (!$inTx) {
+ mysqli_query($connect, "COMMIT");
+ }
+
+ return $afterData;
+
+ } catch (Exception $e) {
+
+ if (!$inTx) {
+ mysqli_query($connect, "ROLLBACK");
+ }
+
+ throw $e;
+ }
+ }
+
+ private function isDuplicate($orderdate, $accountno, $jobtype): bool
+ {
+ $connect = $GLOBALS['conn'];
+
+ $res = mysqli_query($connect, "
+ SELECT 1
+ FROM tbl_daily
+ WHERE d_orderdate='{$orderdate}'
+ AND d_accountno='{$accountno}'
+ AND d_jobtype = '{$jobtype}'
+ LIMIT 1
+ ");
+
+ return (bool)mysqli_fetch_assoc($res);
+ }
+
+ private function normalizeDailyPayload(array $data, ?array $existing = null): array
+ {
+ // 날짜 정리
+ if (isset($data['d_orderdate'])) {
+ $data['d_orderdate'] = preg_replace('/[^0-9]/', '', $data['d_orderdate']);
+ }
+
+ if (isset($data['d_visitdate'])) {
+ $data['d_visitdate'] = preg_replace('/[^0-9]/', '', $data['d_visitdate']);
+ }
+
+ // 숫자 필드 기본값
+ $intFields = [
+ 'd_quantity',
+ 'd_sludge'
+ ];
+
+ foreach ($intFields as $f) {
+ if (isset($data[$f])) {
+ $data[$f] = ($data[$f] === '' || $data[$f] === null)
+ ? 0
+ : (int)$data[$f];
+ }
+ }
+
+ // 문자열 trim
+ $strFields = [
+ 'd_pickupnote',
+ 'd_note'
+ ];
+
+ foreach ($strFields as $f) {
+ if (isset($data[$f])) {
+ $data[$f] = trim((string)$data[$f]);
+ }
+ }
+
+ return $data;
+ }
+
+ private function hydrateDailySnapshot(array $data, ?array $existing = null): array
+ {
+ $connect = $GLOBALS['conn'] ?? null;
+ if (!$connect) {
+ throw new Exception("DB connection not found");
+ }
+
+ // =========================
+ // DRIVER SNAPSHOT
+ // =========================
+ $druid = isset($data['d_druid'])
+ ? (int)$data['d_druid']
+ : (int)($existing['d_druid'] ?? 0);
+
+ // fallback: legacy member uid -> current driver uid
+ if ($druid <= 0) {
+ $driverUid = isset($data['d_driveruid'])
+ ? (int)$data['d_driveruid']
+ : (int)($existing['d_driveruid'] ?? 0);
+
+ if ($driverUid > 0) {
+ $sqMap = qry("
+ SELECT
+ m.m_currentdriver AS dr_uid,
+ d.dr_initial
+ FROM tbl_member m
+ LEFT JOIN tbl_driver d
+ ON d.dr_uid = m.m_currentdriver
+ WHERE m.m_uid = '{$driverUid}'
+ LIMIT 1
+ ");
+ $map = fetch_array($sqMap);
+
+ if ($map && (int)$map['dr_uid'] > 0) {
+ $druid = (int)$map['dr_uid'];
+ $data['d_druid'] = $druid;
+ $data['d_drinitial'] = $map['dr_initial'] ?? '';
+ }
+ }
+ }
+
+ // druid가 있으면 driver snapshot 확정
+ if ($druid > 0) {
+ $sqDriver = qry("
+ SELECT dr_initial
+ FROM tbl_driver
+ WHERE dr_uid = '{$druid}'
+ LIMIT 1
+ ");
+ $driver = fetch_array($sqDriver);
+
+ if ($driver && !empty($driver['dr_initial'])) {
+ $data['d_druid'] = $druid;
+ $data['d_drinitial'] = $driver['dr_initial'];
+ } elseif ($existing) {
+ $data['d_druid'] = $existing['d_druid'] ?? 0;
+ $data['d_drinitial'] = $existing['d_drinitial'] ?? '';
+ }
+ }
+
+ // =========================
+ // CUSTOMER SNAPSHOT (확장)
+ // =========================
+ $customerUid = isset($data['d_customeruid'])
+ ? (int)$data['d_customeruid']
+ : (int)($existing['d_customeruid'] ?? 0);
+
+ if ($customerUid > 0) {
+ $sqCustomer = qry("
+ SELECT
+ c_regionuid,
+ c_region,
+ c_fullcycle,
+ c_fullcycleforced,
+ c_fullcycleflag,
+ c_lastpickupdate,
+ c_lastpickupquantity,
+ c_lastpaiddate,
+ c_name,
+ c_paymenttype,
+ c_paymentcycle,
+ c_rate,
+ c_form_eu,
+ c_form_corsia,
+ c_maincontainer,
+ c_container,
+ c_location,
+ c_phone,
+ c_address,
+ c_city,
+ c_postal,
+ c_area
+
+ FROM tbl_customer
+ WHERE c_uid = '{$customerUid}'
+ LIMIT 1
+ ");
+ $customer = fetch_array($sqCustomer);
+
+ if ($customer) {
+ $data['d_name'] = $customer['c_name'] ?? '';
+ $data['d_form_eu'] = $customer['c_form_eu'] ?? '';
+ $data['d_form_corsia'] = $customer['c_form_corsia'] ?? '';
+ $data['d_maincontainer'] = $customer['c_maincontainer'] ?? '';
+ $data['d_container'] = $customer['c_container'] ?? '';
+ $data['d_location'] = $customer['c_location'] ?? '';
+ $data['d_phone'] = $customer['c_phone'] ?? '';
+ $data['d_address'] = $customer['c_address'] ?? '';
+ $data['d_city'] = $customer['c_city'] ?? '';
+ $data['d_postal'] = $customer['c_postal'] ?? '';
+ $data['d_area'] = $customer['c_area'] ?? '';
+ $data['d_regionuid'] = (int)($customer['c_regionuid'] ?? 0);
+ $data['d_region'] = $customer['c_region'] ?? '';
+ $data['d_fullcycle'] = $customer['c_fullcycle'] ?? 0;
+ $data['d_fullcycleforced'] = $customer['c_fullcycleforced'] ?? 0;
+ $data['d_fullcycleflag'] = $customer['c_fullcycleflag'] ?? 0;
+ $data['d_lastpickupdate'] = $customer['c_lastpickupdate'] ?? '';
+ $data['d_lastpickupquantity'] = $customer['c_lastpickupquantity'] ?? 0;
+ $data['d_lastpaiddate'] = $customer['c_lastpaiddate'] ?? '';
+ $data['d_paymenttype'] = $customer['c_paymenttype'] ?? '';
+ $data['d_cycle'] = $customer['c_paymentcycle'] ?? '';
+ $data['d_rate'] = $customer['c_rate'] ?? '';
+ if (!isset($data['d_oil_2y'])) $data['d_oil_2y'] = 0;
+ if (!isset($data['d_oil_1y'])) $data['d_oil_1y'] = 0;
+ if (!isset($data['d_oil_0y'])) $data['d_oil_0y'] = 0;
+ }
+ }
+
+ return $data;
+ }
+
+ private function getDailyColumns(): array
+ {
+ return [
+ 'd_uid',
+
+ // key
+ 'd_orderdate',
+ 'd_accountno',
+ 'd_customeruid',
+ 'd_jobtype',
+
+ // driver / region
+ 'd_driveruid',
+ 'd_druid',
+ 'd_drinitial',
+ 'd_regionuid',
+ 'd_region',
+
+ // basic status
+ 'd_ordertype',
+ 'd_visitdate',
+ 'd_visit',
+ 'd_status',
+
+ // qty / sludge / payment
+ 'd_quantity',
+ 'd_sludge',
+ 'd_paymenttype',
+ 'd_payamount',
+ 'd_payeename',
+ 'd_paystatus',
+
+ // customer snapshot
+ 'd_name',
+ 'd_form_eu',
+ 'd_form_corsia',
+ 'd_maincontainer',
+ 'd_container',
+ 'd_location',
+ 'd_phone',
+ 'd_address',
+ 'd_city',
+ 'd_postal',
+ 'd_area',
+
+ // oil / cycle history snapshot
+ 'd_oil_2y',
+ 'd_oil_1y',
+ 'd_oil_0y',
+ 'd_fullcycle',
+ 'd_fullcycleforced',
+ 'd_fullcycleflag',
+ 'd_lastpickupdate',
+ 'd_lastpickupquantity',
+ 'd_lastpaiddate',
+
+ // pricing / estimate
+ 'd_cycle',
+ 'd_rate',
+ 'd_estquantity',
+
+ // audit
+ 'd_createruid',
+ 'd_createddate',
+ 'd_inputdate',
+ 'd_modifydate',
+ 'd_ruid',
+
+ // misc
+ 'd_payeesign',
+ 'd_is_transfer'
+ ];
+ }
+
+ private function calculateEstQuantity(array $data, ?array $existing = null): int
+ {
+ $customerUid = $data['d_customeruid'] ?? ($existing['d_customeruid'] ?? 0);
+ $orderdate = $data['d_orderdate'] ?? ($existing['d_orderdate'] ?? '');
+
+ if (!$customerUid || !$orderdate) return 0;
+
+ $sqCus = qry("
+ SELECT c_fullquantity, c_fullquantitydaily
+ FROM tbl_customer
+ WHERE c_uid = '{$customerUid}'
+ LIMIT 1
+ ");
+ $customer = fetch_array($sqCus);
+
+ if (!$customer) return 0;
+
+ $today = new DateTime(date("Y-m-d"));
+ $searchDate = new DateTime(substr($orderdate,0,4)."-".substr($orderdate,4,2)."-".substr($orderdate,6,2));
+
+ $interval = $today->diff($searchDate);
+ $days = (int)$interval->days;
+
+ return max(
+ 0,
+ ($customer['c_fullquantity'] - $customer['c_fullquantitydaily']) +
+ ($days * $customer['c_fullquantitydaily'])
+ );
+ }
+
+ private function runAfterSave(?array $before, array $after, array $opt = []): void
+ {
+ $this->updateCustomerFromDaily($before, $after);
+ $this->updateRequestFromDaily($after);
+ $this->upsertDailyNote($after);
+ $this->handlePickupCleanup($before, $after);
+ $this->handlePickupReset($before, $after);
+ }
+
+ private function runAfterDelete(array $before, array $opt = []): void
+ {
+ $connect = $GLOBALS['conn'];
+
+ if (empty($before['d_customeruid'])) {
+ return;
+ }
+
+ $customerUid = mysqli_real_escape_string($connect, $before['d_customeruid']);
+ $orderdate = mysqli_real_escape_string($connect, $before['d_orderdate'] ?? '');
+
+ // 1) REQUEST 삭제
+ $this->deleteRequestByDaily($before);
+
+ // 2) CUSTOMER 재계산 (lastpick, lastpaid 등 포함)
+ $this->recalcCustomerFromDailyHistory($customerUid);
+
+ // 3) GHOST 재판정
+ $this->reEvaluateGhost($customerUid);
+ }
+
+ private function deleteRequestByDaily(array $before): void
+ {
+ $connect = $GLOBALS['conn'];
+
+ $customerUid = (int)($before['d_customeruid'] ?? 0);
+ $orderdate = preg_replace('/[^0-9]/', '', $before['d_orderdate'] ?? '');
+
+ if ($customerUid <= 0 || $orderdate === '') {
+ return;
+ }
+
+ mysqli_query($connect, "
+ DELETE FROM tbl_request
+ WHERE r_customeruid = '{$customerUid}'
+ AND r_requestdate = '{$orderdate}'
+ ");
+ }
+
+ private function updateCustomerFromDaily($before, $after)
+ {
+ $connect = $GLOBALS['conn'];
+
+ if (empty($after['d_customeruid'])) return;
+
+ $customer_uid = mysqli_real_escape_string($connect, $after['d_customeruid']);
+
+ // 고객 현재 상태 조회
+ $qr = mysqli_query($connect, "
+ SELECT
+ c_paymenttype,
+ c_is_top,
+ c_fpickup,
+ c_schedule,
+ c_scheduleday
+ FROM tbl_customer
+ WHERE c_uid = '{$customer_uid}'
+ LIMIT 1
+ ");
+
+ $customer = mysqli_fetch_assoc($qr);
+ if (!$customer) return;
+
+ $updateFields = [];
+
+ $ordertype = $after['d_ordertype'] ?? 'N';
+ $orderdate = $after['d_orderdate'] ?? '';
+ $visitdate = $after['d_visitdate'] ?? '';
+ $quantity = (int)($after['d_quantity'] ?? 0);
+ $paystatus = $after['d_paystatus'] ?? '';
+ $paymenttype = $after['d_paymenttype'] ?? '';
+
+ $isTop = $customer['c_is_top'] ?? '';
+
+ // --------------------------------------------------
+ // 0) Ghost Check
+ // --------------------------------------------------
+ if ($quantity < 10 && $isTop !== 'G') {
+ $updateFields[] = "c_is_top = 'G'";
+ }
+
+ if ($isTop === 'G' && $quantity >= 10) {
+ $updateFields[] = "c_is_top = ''";
+ }
+
+ // --------------------------------------------------
+ // 1) c_fpickup 처리
+ // --------------------------------------------------
+ if (!empty($orderdate)) {
+
+ $currentFpickup = $customer['c_fpickup'] ?? '';
+
+ if (empty($currentFpickup) || $currentFpickup < $orderdate) {
+ $updateFields[] = "c_fpickup = '{$orderdate}'";
+ }
+ }
+
+ // --------------------------------------------------
+ // 2) orderflag 처리
+ // --------------------------------------------------
+ if (!empty($after['d_visit']) && $after['d_visit'] === 'Y') {
+ $updateFields[] = "c_orderdate = ''";
+ $updateFields[] = "c_orderflag = 0";
+ } else {
+ $updateFields[] = "c_orderdate = '{$orderdate}'";
+ $updateFields[] = "c_orderflag = 1";
+ }
+
+ // --------------------------------------------------
+ // 3) Scheduled 처리 (d_ordertype == 'S')
+ // --------------------------------------------------
+ if ($ordertype === 'S' && !empty($visitdate)) {
+
+ $schedule = $customer['c_schedule'] ?? '';
+ $scheduleDay = $customer['c_scheduleday'] ?? '';
+
+ if ($schedule > '1W' && $schedule <= '6W') {
+
+ $weekCount = (int)substr($schedule, 0, 1);
+
+ if ($weekCount > 0 && !empty($scheduleDay)) {
+
+ $dayParts = explode('|', $scheduleDay);
+ $dayOfWeek = $dayParts[0] ?? '';
+
+ $calcStr = "+{$weekCount} week {$dayOfWeek}";
+ $nextDate = date('Ymd', strtotime($calcStr, strtotime($visitdate)));
+
+ $updateFields[] = "c_schedulebasic = '{$nextDate}'";
+ }
+ }
+ }
+
+ // --------------------------------------------------
+ // UPDATE 실행
+ // --------------------------------------------------
+ if (!empty($updateFields)) {
+
+ mysqli_query($connect, "
+ UPDATE tbl_customer
+ SET " . implode(",", $updateFields) . "
+ WHERE c_uid = '{$customer_uid}'
+ LIMIT 1
+ ");
+ }
+ }
+
+ private function updateRequestFromDaily(array $after): void
+ {
+ $connect = $GLOBALS['conn'];
+
+ if (empty($after['d_ordertype']) || $after['d_ordertype'] !== 'R') {
+ return;
+ }
+
+ if (empty($after['d_ruid'])) {
+ return;
+ }
+
+ // pickup 완료 조건 (방문 완료 + 상태 F)
+ if (
+ empty($after['d_visit']) ||
+ $after['d_visit'] !== 'Y' ||
+ empty($after['d_status']) ||
+ $after['d_status'] !== 'F'
+ ) {
+ return;
+ }
+
+ $r_uid = mysqli_real_escape_string($connect, $after['d_ruid']);
+
+ mysqli_query($connect, "
+ UPDATE tbl_request
+ SET r_status = 'F'
+ WHERE r_uid = '{$r_uid}'
+ LIMIT 1
+ ");
+ }
+
+ private function upsertDailyNote(array $after): void
+ {
+ $connect = $GLOBALS['conn'];
+
+ if (empty($after['d_uid'])) return;
+
+ // note는 saveDaily payload에 포함되어 있어야 함
+ if (empty($after['d_pickupnote']) && empty($after['d_note'])) {
+ return;
+ }
+
+ $noteText = trim($after['d_pickupnote'] ?? $after['d_note'] ?? '');
+
+ if (strlen($noteText) <= 1) return;
+
+ $dailyuid = mysqli_real_escape_string($connect, $after['d_uid']);
+ $customeruid = mysqli_real_escape_string($connect, $after['d_customeruid'] ?? '');
+ $memberuid = mysqli_real_escape_string($connect, $after['d_driveruid'] ?? '');
+ $noteEsc = mysqli_real_escape_string($connect, $noteText);
+ $now14 = date('YmdHis');
+ $level = mysqli_real_escape_string($connect, $after['d_level'] ?? 9);
+
+ // 기존 note 존재 여부 확인
+ $qr = mysqli_query($connect, "
+ SELECT n_uid
+ FROM tbl_note
+ WHERE n_dailyuid = '{$dailyuid}'
+ LIMIT 1
+ ");
+
+ $existing = mysqli_fetch_assoc($qr);
+
+ if ($existing) {
+ // UPDATE
+ mysqli_query($connect, "
+ UPDATE tbl_note
+ SET
+ n_memberuid = '{$memberuid}',
+ n_customeruid = '{$customeruid}',
+ n_type = 'D',
+ n_level = {$level},
+ n_view = 1,
+ n_note = '{$noteEsc}',
+ n_createddate = '{$now14}'
+ WHERE n_dailyuid = '{$dailyuid}'
+ LIMIT 1
+ ");
+ } else {
+ // INSERT
+ mysqli_query($connect, "
+ INSERT INTO tbl_note (
+ n_memberuid,
+ n_customeruid,
+ n_dailyuid,
+ n_type,
+ n_level,
+ n_view,
+ n_note,
+ n_createddate
+ ) VALUES (
+ '{$memberuid}',
+ '{$customeruid}',
+ '{$dailyuid}',
+ 'D',
+ {$level},
+ 1,
+ '{$noteEsc}',
+ '{$now14}'
+ )
+ ");
+ }
+ }
+
+ private function handlePickupCleanup(?array $before, array $after): void
+ {
+ $connect = $GLOBALS['conn'];
+
+ $beforeQty = (int)($before['d_quantity'] ?? 0);
+ $afterQty = (int)($after['d_quantity'] ?? 0);
+
+ $status = $after['d_status'] ?? '';
+ $visit = $after['d_visit'] ?? '';
+
+ // 최초 pickup
+ $isFirstPickup = ($beforeQty < 10 && $afterQty >= 10);
+
+ if (!$isFirstPickup) return;
+ if ($status !== 'F' || $visit !== 'Y') return;
+
+ $customerUid = mysqli_real_escape_string($connect, $after['d_customeruid']);
+ $today = date('Ymd');
+ $jobtype = mysqli_real_escape_string($connect, $after['d_jobtype'] ?? 'UCO');
+
+ // =========================
+ // 삭제 대상 조회
+ // =========================
+ $res = mysqli_query($connect, "
+ SELECT d_orderdate, d_accountno, d_jobtype
+ FROM tbl_daily
+ WHERE d_customeruid = '{$customerUid}'
+ AND d_orderdate > '{$today}'
+ AND d_status = 'A'
+ AND d_jobtype = '{$jobtype}'
+ ");
+
+ if (!$res) {
+ throw new Exception(mysqli_error($connect));
+ }
+
+ // =========================
+ // 하나씩 deleteDaily 호출
+ // =========================
+ while ($row = mysqli_fetch_assoc($res)) {
+
+ try {
+ $this->deleteDaily(
+ $row['d_orderdate'],
+ $row['d_accountno'],
+ $row['d_jobtype'],
+ ['in_tx' => true]
+ );
+
+ } catch (Exception $e) {
+ // 여기서 실패하면 전체 rollback 유도
+ throw $e;
+ }
+ }
+
+ error_log("[PickupCleanup] ERP-safe delete completed for customer={$customerUid}");
+ }
+
+ private function handlePickupReset(?array $before, array $after): void
+ {
+ $connect = $GLOBALS['conn'];
+
+ $beforeQty = (int)($before['d_quantity'] ?? 0);
+ $afterQty = (int)($after['d_quantity'] ?? 0);
+
+ $status = $after['d_status'] ?? '';
+ $visit = $after['d_visit'] ?? '';
+
+ $isFirstPickup = ($beforeQty < 10 && $afterQty >= 10);
+
+ if (!$isFirstPickup) return;
+ if ($status !== 'F' || $visit !== 'Y') return;
+
+ $customerUid = mysqli_real_escape_string($connect, $after['d_customeruid']);
+
+ $sql = "
+ UPDATE tbl_customer
+ SET
+ c_fullquantity = 0
+ WHERE c_uid = '{$customerUid}'
+ ";
+
+ mysqli_query($connect, $sql);
+
+ error_log("[PickupReset] customer={$customerUid} reset fullquantity");
+ }
+
+ public function deleteDaily(string $orderdate, string $accountno, string $jobtype, array $opt = [])
+ {
+ $connect = $GLOBALS['conn'] ?? null;
+ if (!$connect) {
+ throw new Exception("DB connection not found");
+ }
+
+ $inTx = !empty($opt['in_tx']);
+
+ // =========================
+ // KEY NORMALIZE
+ // =========================
+ $orderdate = preg_replace('/[^0-9]/', '', $orderdate);
+ if (strlen($orderdate) !== 8) {
+ throw new Exception("invalid orderdate");
+ }
+
+ $accountno = mysqli_real_escape_string($connect, trim($accountno));
+ if ($accountno === '') {
+ throw new Exception("invalid accountno");
+ }
+
+ $jobtype = mysqli_real_escape_string($connect, trim($jobtype));
+ if ($jobtype === '') {
+ $jobtype = 'UCO';
+ }
+
+ if (!$inTx) {
+ mysqli_query($connect, "START TRANSACTION");
+ }
+
+ try {
+
+ // =========================
+ // 1. 기존 데이터 조회
+ // =========================
+ $res = mysqli_query($connect, "
+ SELECT *
+ FROM tbl_daily
+ WHERE d_orderdate='{$orderdate}'
+ AND d_accountno='{$accountno}'
+ AND d_jobtype = '{$jobtype}'
+ LIMIT 1
+ ");
+ if (!$res) throw new Exception(mysqli_error($connect));
+
+ $existing = mysqli_fetch_assoc($res);
+
+ if (!$existing) {
+ throw new Exception("Daily record not found");
+ }
+
+ // =========================
+ // 2. ERP OUTBOX 기록
+ // =========================
+ $payload = mysqli_real_escape_string(
+ $connect,
+ json_encode([
+ 'key'=>[
+ 'd_orderdate'=>$orderdate,
+ 'd_accountno'=>$accountno,
+ 'd_jobtype' =>$jobtype
+ ],
+ 'before'=>$existing
+ ], JSON_UNESCAPED_UNICODE)
+ );
+
+ if (!mysqli_query($connect, "
+ INSERT INTO tbl_erp_outbox
+ (eo_event_type, eo_key_date, eo_key_accountno, eo_key_jobtype, eo_payload, eo_status, eo_created_at)
+ VALUES
+ ('DAILY_DELETED','{$orderdate}','{$accountno}','{$jobtype}','{$payload}','PENDING',NOW())
+ ")) {
+ throw new Exception(mysqli_error($connect));
+ }
+
+ // =========================
+ // 3. 물리 삭제
+ // =========================
+ if (!mysqli_query($connect, "
+ DELETE FROM tbl_daily
+ WHERE d_orderdate='{$orderdate}'
+ AND d_accountno='{$accountno}'
+ AND d_jobtype = '{$jobtype}'
+ LIMIT 1
+ ")) {
+ throw new Exception(mysqli_error($connect));
+ }
+
+ if (mysqli_affected_rows($connect) === 0) {
+ throw new Exception("Delete failed");
+ }
+
+ // =========================
+ // AFTER WORK 중앙화
+ // =========================
+ $this->runAfterDelete($existing, $opt);
+
+ // =========================
+ // COMMIT
+ // =========================
+ if (!$inTx) {
+ mysqli_query($connect, "COMMIT");
+ }
+
+ return true;
+
+ } catch (Exception $e) {
+
+ if (!$inTx) {
+ mysqli_query($connect, "ROLLBACK");
+ }
+
+ throw $e;
+ }
+ }
+
+ private function reEvaluateGhost(int $customerUid): void
+ {
+ $connect = $GLOBALS['conn'];
+
+ $res = mysqli_query($connect, "
+ SELECT d_quantity
+ FROM tbl_daily
+ WHERE d_customeruid = '{$customerUid}'
+ AND d_status = 'F'
+ ORDER BY d_orderdate DESC
+ LIMIT 1
+ ");
+
+ $row = mysqli_fetch_assoc($res);
+
+ if (!$row) {
+ // 데이터 없으면 ghost 해제
+ mysqli_query($connect, "
+ UPDATE tbl_customer
+ SET c_is_top = ''
+ WHERE c_uid = '{$customerUid}'
+ ");
+ return;
+ }
+
+ $qty = (int)$row['d_quantity'];
+
+ if ($qty < 10) {
+ mysqli_query($connect, "
+ UPDATE tbl_customer
+ SET c_is_top = 'G'
+ WHERE c_uid = '{$customerUid}'
+ ");
+ } else {
+ mysqli_query($connect, "
+ UPDATE tbl_customer
+ SET c_is_top = ''
+ WHERE c_uid = '{$customerUid}'
+ ");
+ }
+ }
+
+ private function recalcCustomerFromDailyHistory(string $customerUid): void
+ {
+ $connect = $GLOBALS['conn'];
+ $customerUidEsc = mysqli_real_escape_string($connect, $customerUid);
+
+ // 0) "오늘 포함 이후" 오더장 존재 여부 체크 (남아있으면 리셋 금지)
+ $today = date('Ymd');
+
+ $resFuture = mysqli_query($connect, "
+ SELECT 1
+ FROM tbl_daily
+ WHERE d_customeruid = '{$customerUidEsc}'
+ AND d_orderdate >= '{$today}'
+ AND d_status = 'A'
+ LIMIT 1
+ ");
+ if (!$resFuture) {
+ throw new Exception(mysqli_error($connect));
+ }
+ $hasFutureOrder = (bool)mysqli_fetch_assoc($resFuture);
+
+ // 1) 마지막 완료 주문(F) 기준으로 last pickup 재계산
+ $res = mysqli_query($connect, "
+ SELECT
+ d_orderdate,
+ d_quantity,
+ d_sludge,
+ d_paymenttype,
+ d_paystatus
+ FROM tbl_daily
+ WHERE d_customeruid = '{$customerUidEsc}'
+ AND d_status = 'F'
+ ORDER BY d_orderdate DESC
+ LIMIT 1
+ ");
+ if (!$res) {
+ throw new Exception(mysqli_error($connect));
+ }
+
+ $last = mysqli_fetch_assoc($res);
+
+ $lastPickupDate = '';
+ $lastPickupQty = 0;
+ $lastSludge = '';
+ $lastPaidDate = '';
+
+ if ($last) {
+ $lastPickupDate = $last['d_orderdate'];
+ $lastPickupQty = (int)$last['d_quantity'];
+ $lastSludge = (string)$last['d_sludge'];
+
+ if ($last['d_paymenttype'] === 'CA' && $last['d_paystatus'] === 'P') {
+ $lastPaidDate = $last['d_orderdate'];
+ }
+ }
+
+ // 2) 마지막 주문이 cash paid가 아니면, cash paid 마지막을 다시 찾음
+ if ($lastPaidDate === '') {
+
+ $res2 = mysqli_query($connect, "
+ SELECT d_orderdate
+ FROM tbl_daily
+ WHERE d_customeruid = '{$customerUidEsc}'
+ AND d_status = 'F'
+ AND d_paymenttype = 'CA'
+ AND d_paystatus = 'P'
+ ORDER BY d_orderdate DESC
+ LIMIT 1
+ ");
+ if (!$res2) {
+ throw new Exception(mysqli_error($connect));
+ }
+
+ $paid = mysqli_fetch_assoc($res2);
+ if ($paid) {
+ $lastPaidDate = $paid['d_orderdate'];
+ }
+ }
+
+ // 3) UPDATE 구성
+ $setParts = [];
+ $setParts[] = "c_lastpickupdate=" . ($lastPickupDate ? "'{$lastPickupDate}'" : "''");
+ $setParts[] = "c_lastpickupquantity='{$lastPickupQty}'";
+ $setParts[] = "c_lastpaiddate=" . ($lastPaidDate ? "'{$lastPaidDate}'" : "''");
+ $setParts[] = "c_sludge='" . mysqli_real_escape_string($connect, $lastSludge) . "'";
+
+ // 4) orderflag/orderdate 리셋 정책 반영
+ // - 오늘 포함 이후 오더장이 남아있으면 유지 (아무것도 안함)
+ // - 없으면 리셋
+ if (!$hasFutureOrder) {
+ $setParts[] = "c_orderdate=''";
+ $setParts[] = "c_orderflag=0";
+ }
+
+ $sql = "
+ UPDATE tbl_customer
+ SET " . implode(",", $setParts) . "
+ WHERE c_uid = '{$customerUidEsc}'
+ LIMIT 1
+ ";
+
+ if (!mysqli_query($connect, $sql)) {
+ throw new Exception(mysqli_error($connect));
+ }
+ }
+
+ /* ===============================
+ * 공통 JSON 응답
+ * =============================== */
+
+ private function jsonSuccess($data = [])
+ {
+ return json_encode([
+ 'result' => 'success',
+ 'data' => $data
+ ]);
+ }
+
+ private function jsonError($msg)
+ {
+ return json_encode([
+ 'result' => 'error',
+ 'message'=> $msg
+ ]);
+ }
+
+}
\ No newline at end of file
diff --git a/public_html/assets/internal_api.php b/public_html/assets/internal_api.php
index 2d5e4e3..048bd76 100644
--- a/public_html/assets/internal_api.php
+++ b/public_html/assets/internal_api.php
@@ -7,6 +7,8 @@ require_once getenv("DOCUMENT_ROOT")."/assets/conf.inc.php";
require_once getenv("DOCUMENT_ROOT")."/assets/dbCon.php";
include getenv("DOCUMENT_ROOT")."/include/session_include.php";
include_once getenv("DOCUMENT_ROOT")."/lib/erp_api.php";
+include_once getenv("DOCUMENT_ROOT")."/assets/api/install.php";
+include_once getenv("DOCUMENT_ROOT")."/assets/api/daily.php";
error_reporting(E_ALL);
ini_set('display_errors', '1');
@@ -14,6 +16,13 @@ ini_set('display_errors', '1');
date_default_timezone_set('America/Toronto');
class API extends CONF {
+ use InstallAPI;
+
+ protected $dailyService;
+ public function __construct() {
+ $this->dailyService = new DailyService();
+ }
+
public function processApi() {
$func = $_GET['func'];
@@ -61,6 +70,7 @@ class API extends CONF {
$result = array();
$uidList = "";
+ $customerUidArr = [];
$sqOptionPoint = qry("SELECT
'flag' AS type,
@@ -125,7 +135,7 @@ class API extends CONF {
td.d_ordertype,
td.d_driveruid,
td.d_druid,
- td.d_createruid,
+ td.d_createruid,
td.d_status
FROM
tbl_daily td
@@ -171,6 +181,7 @@ class API extends CONF {
}
$loc_comp[] = $crntLoc;
+ $customerUidArr[] = (int)$rstOptionPoint['c_uid'];
$d_ordertype = $rstOptionPoint['d_ordertype'];
if ($d_ordertype == 'S') $d_ordertype = '📅';
@@ -347,6 +358,7 @@ class API extends CONF {
}
$loc_comp[] = $crntLoc;
+ $customerUidArr[] = (int)$rstQtyPoint['c_uid'];
$c_schedule = $rstQtyPoint['c_schedule'];
if ($c_schedule == 'Will Call') $c_schedule = '📞';
@@ -377,6 +389,44 @@ class API extends CONF {
);
}
}
+ $customerUidArr = array_values(array_unique($customerUidArr));
+ $containerMap = [];
+
+ if (!empty($customerUidArr)) {
+ $in = implode(',', array_map('intval', $customerUidArr));
+
+ $sqCC = qry("
+ SELECT
+ cc_customer_uid,
+ cc_type,
+ cc_owner_type,
+ cc_has_lock,
+ cc_has_wheel,
+ cc_has_woodframe
+ FROM tbl_customer_container
+ WHERE cc_status = 'A'
+ AND cc_customer_uid IN ($in)
+ ORDER BY cc_customer_uid, cc_type, cc_uid
+ ");
+
+ while ($cc = fetch_array($sqCC)) {
+ $cu = (int)$cc['cc_customer_uid'];
+ if (!isset($containerMap[$cu])) $containerMap[$cu] = [];
+ $containerMap[$cu][] = [
+ 'cc_type' => $cc['cc_type'],
+ 'cc_owner_type' => $cc['cc_owner_type'],
+ 'cc_has_lock' => $cc['cc_has_lock'],
+ 'cc_has_wheel' => $cc['cc_has_wheel'],
+ 'cc_has_woodframe' => $cc['cc_has_woodframe'],
+ ];
+ }
+ }
+
+ for ($i = 0; $i < count($result); $i++) {
+ $cid = (int)$result[$i]['id']; // JSON에서 customer id로 쓰는 필드
+ $result[$i]['containers'] = $containerMap[$cid] ?? [];
+ }
+
$this->response($this->json(array("result"=>$result)), 200);
} catch(Exception $e) {
@@ -524,6 +574,7 @@ class API extends CONF {
$result = array();
$uidList = "";
+ $customerUidArr = [];
$sqOptionPoint = qry("SELECT
'flag' AS type,
@@ -634,6 +685,7 @@ class API extends CONF {
}
$crntLoc = array($rstOptionPoint['lat'],$rstOptionPoint['lon']);
+ $customerUidArr[] = (int)$rstOptionPoint['c_uid'];
for($i=0;$i < 99;$i++) {
if(in_array($crntLoc,$loc_comp)){
@@ -810,6 +862,7 @@ class API extends CONF {
}
$crntLoc = array($rstQtyPoint['lat'],$rstQtyPoint['lon']);
+ $customerUidArr[] = (int)$rstQtyPoint['c_uid'];
for($i=0;$i < 99;$i++) {
if(in_array($crntLoc,$loc_comp)){
@@ -851,8 +904,43 @@ class API extends CONF {
}
}
+ $customerUidArr = array_values(array_unique($customerUidArr));
+ $containerMap = [];
+
+ if (!empty($customerUidArr)) {
+ $in = implode(',', array_map('intval', $customerUidArr));
+
+ $sqCC = qry("
+ SELECT
+ cc_customer_uid,
+ cc_type,
+ cc_owner_type,
+ cc_has_lock,
+ cc_has_wheel,
+ cc_has_woodframe
+ FROM tbl_customer_container
+ WHERE cc_status = 'A'
+ AND cc_customer_uid IN ($in)
+ ORDER BY cc_customer_uid, cc_type, cc_uid
+ ");
+
+ while ($cc = fetch_array($sqCC)) {
+ $cu = (int)$cc['cc_customer_uid'];
+ if (!isset($containerMap[$cu])) $containerMap[$cu] = [];
+ $containerMap[$cu][] = [
+ 'cc_type' => $cc['cc_type'],
+ 'cc_owner_type' => $cc['cc_owner_type'],
+ 'cc_has_lock' => $cc['cc_has_lock'],
+ 'cc_has_wheel' => $cc['cc_has_wheel'],
+ 'cc_has_woodframe' => $cc['cc_has_woodframe'],
+ ];
+ }
+ }
-
+ for ($i = 0; $i < count($result); $i++) {
+ $cid = (int)$result[$i]['id']; // JSON에서 customer id로 쓰는 필드
+ $result[$i]['containers'] = $containerMap[$cid] ?? [];
+ }
$this->response($this->json(array("result"=>$result)), 200);
} catch(Exception $e) {
$error = array($e->getMessage());
@@ -1115,238 +1203,223 @@ class API extends CONF {
}
}
- public function addOrder(){
- try {
- qry("INSERT INTO tbl_daily (d_orderdate, d_ordertype, d_ruid, d_driveruid, d_customeruid, d_accountno, d_name, d_paymenttype, d_cycle, d_rate, d_form_eu, d_form_corsia, d_maincontainer, d_container, d_location, d_status)
- SELECT '".$_POST['orderdate']."', '".$_POST['ordertype']."', '".$_POST['ruid']."', '".$_POST['driveruid']."', c_uid, c_accountno, c_name, c_paymenttype, c_paymentcycle, c_rate, c_form_eu, c_form_corsia, c_maincontainer, c_container, c_location, 'A'
- FROM tbl_customer
- WHERE c_uid=".(int)$_POST['customer_uid']);
-
- $this->response($this->json(array("msg"=>"Order has been successfully added.", "c_index"=>$_POST['c_index'])), 200);
- } catch(Exception $e) {
- $error = array($e->getMessage());
- $this->response($this->json($error), 417);
- }
- }
-
- public function addOrderDirect(){
+ public function addOrder()
+ {
try {
-
- $sqCheckOrder = qry("SELECT count(d_uid) as rowcnt
- FROM tbl_daily
- WHERE d_orderdate='".$_POST['orderdate']."' AND d_customeruid=".(int)$_POST['customer_uid']);
- $rstCheckOrder = fetch_array($sqCheckOrder);
-
- if ($rstCheckOrder['rowcnt'] > 0) {
- $this->response($this->json(array("msg"=>"This order already exists.", "c_index"=>$_POST['c_index'], "c_return"=>"0")), 200);
- return;
- }
- // 고객 정보 조회
$customer_uid = (int)$_POST['customer_uid'];
- $sqCus = qry("SELECT * FROM tbl_customer WHERE c_uid = {$customer_uid}");
+ $orderdate = preg_replace('/[^0-9]/', '', $_POST['orderdate'] ?? '');
+ $ordertype = trim($_POST['ordertype'] ?? 'N');
+ $ruid = trim($_POST['ruid'] ?? '');
+ $driveruid = (int)$_POST['driveruid'];
+
+ if ($customer_uid <= 0) {
+ throw new Exception("invalid customer_uid");
+ }
+
+ if (strlen($orderdate) !== 8) {
+ throw new Exception("invalid orderdate");
+ }
+
+ // =========================
+ // customer 조회
+ // =========================
+ $sqCus = qry("
+ SELECT c_accountno, c_driveruid
+ FROM tbl_customer
+ WHERE c_uid = {$customer_uid}
+ LIMIT 1
+ ");
+
+ $customer = fetch_array($sqCus);
+
+ if (!$customer) {
+ throw new Exception("Customer not found");
+ }
+
+ $now14 = date("YmdHis");
+
+ // =========================
+ // payload 구성
+ // =========================
+ $payload = [
+ 'd_customeruid' => $customer_uid,
+ 'd_accountno' => $customer['c_accountno'],
+ 'd_orderdate' => $orderdate,
+ 'd_ordertype' => $ordertype,
+ 'd_ruid' => $ruid,
+ 'd_driveruid' => $customer['c_driveruid'], // legacy
+ 'd_druid' => $driveruid, // 실제 driver
+ 'd_status' => 'A',
+ 'd_createruid' => $_SESSION['ss_UID'] ?? '',
+ 'd_createddate' => $now14,
+ 'n_level' => $_SESSION['ss_LEVEL'],
+ ];
+
+ // =========================
+ // saveDaily 호출
+ // =========================
+ $afterData = $this->dailyService->saveDaily($payload);
+
+ // =========================
+ // response
+ // =========================
+ $this->response($this->json([
+ "msg" => "Order has been successfully added.",
+ "c_index" => $_POST['c_index'],
+ "d_uid" => $afterData['d_uid'] ?? null
+ ]), 200);
+
+ } catch (Exception $e) {
+ $error = array($e->getMessage());
+ $this->response($this->json($error), 417);
+ }
+ }
+
+ public function addOrderDirect()
+ {
+ try {
+
+ $customer_uid = (int)$_POST['customer_uid'];
+ $orderdate = preg_replace('/[^0-9]/', '', $_POST['orderdate'] ?? '');
+ $driveruid = (int)$_POST['driveruid'];
+ $creatoruid = trim($_POST['d_createruid'] ?? '');
+ $jobtype = $_POST['jobtype'] ?? 'UCO';
+
+ if ($customer_uid <= 0) {
+ throw new Exception("invalid customer_uid");
+ }
+
+ if (strlen($orderdate) !== 8) {
+ throw new Exception("invalid orderdate");
+ }
+
+ // =========================
+ // 중복 체크
+ // =========================
+ $sqCheckOrder = qry("
+ SELECT count(d_uid) as rowcnt
+ FROM tbl_daily
+ WHERE d_orderdate='{$orderdate}'
+ AND d_customeruid={$customer_uid}
+ AND d_jobtype = 'UCO'
+ ");
+ $rstCheckOrder = fetch_array($sqCheckOrder);
+
+ if ($rstCheckOrder['rowcnt'] > 0) {
+ $this->response($this->json([
+ "msg"=>"This order already exists.",
+ "c_index"=>$_POST['c_index'],
+ "c_return"=>"0"
+ ]), 200);
+ return;
+ }
+
+ // =========================
+ // 최소 customer 정보만 조회
+ // =========================
+ $sqCus = qry("
+ SELECT c_accountno, c_driveruid
+ FROM tbl_customer
+ WHERE c_uid = {$customer_uid}
+ LIMIT 1
+ ");
if (db_num_rows($sqCus) === 0) {
throw new Exception("Customer not found");
}
$customer = fetch_array($sqCus);
-
- // 예상 수량 계산
- $today = new DateTime(date("Y-m-d"));
- $searchDate = new DateTime($_POST['orderdate']);
- $interval = $today->diff($searchDate);
- $days = (int)$interval->days;
- $estquantity = max(
- 0,
- ($customer['c_fullquantity'] - $customer['c_fullquantitydaily']) + ($days * $customer['c_fullquantitydaily'])
- );
- $driveruid = (int)$_POST['driveruid'];
+ $now14 = date("YmdHis");
- $sqDriverInfo = qry("SELECT
- m_currentdriverinitial
- FROM
- tbl_member
- WHERE
- m_currentdriver = '".$driveruid."' ");
- $rstDriverInfo = fetch_array($sqDriverInfo);
-
- // insert into tbl_daily
- $c_name = addslashes($customer['c_name']);
- qry("
- INSERT INTO tbl_daily (
- d_orderdate, d_driveruid, d_customeruid, d_accountno,
- d_name, d_paymenttype, d_cycle, d_rate,
- d_form_eu, d_form_corsia, d_maincontainer, d_container,
- d_location, d_phone, d_address, d_city, d_postal, d_area,
- d_oil_2y, d_oil_1y, d_oil_0y,
- d_fullcycle, d_fullcycleforced,
- d_lastpickupdate, d_lastpickupquantity, d_lastpaiddate,
- d_druid, d_drinitial, d_regionuid, d_region,
- d_estquantity, d_createruid, d_createddate, d_status
- ) VALUES (
- '{$_POST['orderdate']}',
- '{$customer['c_driveruid']}',
- {$customer_uid},
- '{$customer['c_accountno']}',
- '{$c_name}',
- '{$customer['c_paymenttype']}',
- '{$customer['c_paymentcycle']}',
- '{$customer['c_rate']}',
- '{$customer['c_form_eu']}',
- '{$customer['c_form_corsia']}',
- '{$customer['c_maincontainer']}',
- '{$customer['c_container']}',
- '{$customer['c_location']}',
- '{$customer['c_phone']}',
- '{$customer['c_address']}',
- '{$customer['c_city']}',
- '{$customer['c_postal']}',
- '{$customer['c_area']}',
- 0, 0, 0,
- '{$customer['c_fullcycle']}',
- '{$customer['c_fullcycleforced']}',
- '{$customer['c_lastpickupdate']}',
- '{$customer['c_lastpickupquantity']}',
- '{$customer['c_lastpaiddate']}',
-
- '{$driveruid}',
- '{$rstDriverInfo['m_currentdriverinitial']}',
- '{$customer['c_regionuid']}',
- '{$customer['c_region']}',
-
- {$estquantity},
- '{$_POST['d_createruid']}',
- '".date("YmdHis")."',
- 'A'
- )
+ // =========================
+ // PAYLOAD
+ // =========================
+ $payload = [
+ 'd_customeruid' => $customer_uid,
+ 'd_accountno' => $customer['c_accountno'],
+ 'd_orderdate' => $orderdate,
+ 'd_driveruid' => $customer['c_driveruid'], // legacy 유지
+ 'd_druid' => $driveruid, // 실제 driver
+ 'd_status' => 'A',
+ 'd_ordertype' => 'N',
+ 'd_jobtype' => 'UCO',
+ 'd_createruid' => $creatoruid,
+ 'd_createddate' => $now14,
+ 'n_level' => $_SESSION['ss_LEVEL'],
+ ];
+
+ // =========================
+ // SAVE (모든 로직은 daily.php)
+ // =========================
+ $afterData = $this->dailyService->saveDaily($payload);
+
+ // =========================
+ // RESPONSE
+ // =========================
+ $this->response($this->json([
+ "msg"=>"Order has been successfully added.",
+ "c_index"=>$_POST['c_index'],
+ "c_return"=>1,
+ "d_uid"=>$afterData['d_uid'] ?? null
+ ]), 200);
+
+ return;
+
+ } catch(Exception $e) {
+ $error = [$e->getMessage()];
+ $this->response($this->json($error), 417);
+ }
+ }
+
+ public function removeOrder()
+ {
+ try {
+
+ $duid = (int)($_POST['duid'] ?? 0);
+ $customerId = (int)($_POST['id'] ?? 0);
+
+ if ($duid <= 0) {
+ throw new Exception("invalid duid");
+ }
+
+ // =========================
+ // 기존 daily 조회 (삭제용 key 확보)
+ // =========================
+ $sqDaily = qry("
+ SELECT d_orderdate, d_accountno, d_jobtype
+ FROM tbl_daily
+ WHERE d_uid = '{$duid}'
+ LIMIT 1
");
- // d_uid 가져오기
- $sqId = qry("SELECT MAX(d_uid) AS d_uid FROM tbl_daily");
- $rtId = fetch_array($sqId);
- $d_uid = $rtId['d_uid'];
+ $daily = fetch_array($sqDaily);
- // ====================
- // Integration to ERP
- // ====================
- $columns = array();
- $columns[] = "d_ordertype";
- $columns[] = "d_orderdate";
- $columns[] = "d_driveruid";
- $columns[] = "d_accountno";
- $columns[] = "d_paymenttype";
- $columns[] = "d_cycle";
- $columns[] = "d_rate";
- $columns[] = "d_status";
- $columns[] = "d_estquantity";
-
- // Data
- $values = array();
- $values[] = "N";
- $values[] = $_POST['orderdate'];
- $values[] = $_POST['driveruid'];
- $values[] = $customer['c_accountno'];
- $values[] = $customer['c_paymenttype'];
- $values[] = $customer['c_paymentcycle'];
- $values[] = $customer['c_rate'];
- $values[] = "A";
- $values[] = $estquantity;
-
- //
- $erp = new ErpApi();
- $erp->createDailyOrderFromMis($columns, $values, $_POST['d_createruid']);
-
- // 성공시
- qry("UPDATE tbl_daily SET d_is_transfer = 'Y' WHERE d_uid = ".(int)$d_uid);
-
- // customer 상태 업데이트 (이건 ERP에서는 트리거로)
- qry("UPDATE tbl_customer SET c_orderdate='".$_POST['orderdate']."', c_orderflag = 1 WHERE c_uid = ".(int)$_POST['customer_uid']);
-
- //
- $this->response($this->json(array("msg"=>"Order has been successfully added.", "c_index"=>$_POST['c_index'], "c_return"=>1)), 200);
- return;
- } catch(Exception $e) {
- $error = array($e->getMessage());
- $this->response($this->json($error), 417);
- }
- }
-
- public function removeOrder(){
- try {
-
- qry("DELETE FROM tbl_daily WHERE d_uid = '".$_POST['duid']."'");
- qry("UPDATE tbl_customer SET c_orderdate='', c_orderflag = 0 WHERE c_uid='".$_POST['id']."'");
- qry("DELETE FROM tbl_request WHERE r_customeruid = '".$_POST['id']."' AND r_requestdate = '".$_POST['orderdate']."'");
-
-
- // 오더장 삭제시 오더장 먼저 삭제하고 last pickupdate, quantity, last paid date 를 tbl_daily 에서 찾아서 tbl_customer 에 업데이트 (2023.11.17)
- // sludge 는 어떻게 처리? customer detail 에서 수정할수도 있고, 오더장에 입력시 전체 업데이트 됨. 어디서 언제 입력했는지 확인 불가.
- $sqrmInfo = qry("SELECT
- d_orderdate,d_visitdate,d_quantity,d_paymenttype,d_paystatus,d_sludge
- FROM tbl_daily
- WHERE
- d_customeruid = '".$_POST['id']."'
- AND d_status = 'F'
- ORDER BY d_orderdate DESC LIMIT 1");
- $rstrmInfo = fetch_array($sqrmInfo);
- // 완료(F) 데이터가 없으면 customer 마지막값 초기화
- if (empty($rstrmInfo)) {
- qry("UPDATE tbl_customer SET c_lastpickupdate = '', c_lastpickupquantity = '', c_lastpaiddate = '' WHERE c_uid = '".$_POST['id']."'");
- } else {
- // tbl_daily 의 마지막 데이터중 cash 이고 paid 면 c_lastpaiddate
- // 그렇지 않으면 다시 tbl_daily 에서 cash 이고 paid 인 마지막 데이터를 가져옴. 없으면 null 처리
- if (($rstrmInfo['d_paymenttype'] ?? '') === "CA" && ($rstrmInfo['d_paystatus'] ?? '') === "P") {
- $addQry = ", c_lastpaiddate = '".($rstrmInfo['d_visitdate'] ?? '')."' ";
- } else {
- $sqrmInfoLast = qry("SELECT
- d_visitdate
- FROM tbl_daily
- WHERE
- d_customeruid = '".$_POST['id']."'
- AND d_status = 'F'
- AND d_paymenttype = 'CA' AND d_paystatus = 'P'
- ORDER BY d_orderdate DESC LIMIT 1");
- $rstrmInfoLast = fetch_array($sqrmInfoLast);
-
- if (!empty($rstrmInfoLast) && !empty($rstrmInfoLast['d_visitdate'])) {
- $addQry = ", c_lastpaiddate = '".$rstrmInfoLast['d_visitdate']."' ";
- } else {
- $addQry = ", c_lastpaiddate = '' ";
- }
- }
- // last pickup 업데이트
- qry("UPDATE tbl_customer
- SET c_lastpickupdate='".$rstrmInfo['d_orderdate']."', c_lastpickupquantity = '".$rstrmInfo['d_quantity']."' ". $addQry ."
- WHERE c_uid = '".$_POST['id']."'");
+ if (!$daily) {
+ throw new Exception("Daily record not found");
}
-
- // ====================
- // Integration to ERP
- // 나머지는 trigger 처리
- // ====================
- $columns = array();
- $values = array();
- $columns[] = "d_accountno";
- $columns[] = "d_orderdate";
- $columns[] = "d_status";
- $values[] = $_POST['accountno'];
- $values[] = $_POST['orderdate'];
- $values[] = "D";
- $lguserid = $_POST['createruid'];
- // ERP로 전송 (payload 내부에서 자동 매핑)
- $erp = new ErpApi();
- $erp->updateDailyOrderFromMis($columns, $values, $lguserid);
- // 성공 시 플래그 & 로그 (지웠음)
- // $jdb->uQuery("tbl_daily", ["d_is_transfer"], ["Y"], " WHERE d_uid = '$d_uid'");
+ // =========================
+ // DELETE (중앙화)
+ // =========================
+ $this->dailyService->deleteDaily(
+ $daily['d_orderdate'],
+ $daily['d_accountno'],
+ $daily['d_jobtype']
+ );
+
+ // =========================
+ // RESPONSE
+ // =========================
+ $this->response($this->json([
+ "msg" => "Order has been successfully removed.",
+ "c_index" => $_POST['c_index']
+ ]), 200);
- //
- $this->response($this->json(array("msg"=>"Order has been successfully removed.", "c_index"=>$_POST['c_index'])), 200);
} catch(Exception $e) {
- $error = array($e->getMessage());
+ $error = [$e->getMessage()];
$this->response($this->json($error), 417);
- }
- }
+ }
+ }
public function initInput(){
try {
@@ -1355,6 +1428,7 @@ class API extends CONF {
td.d_customeruid,
td.d_orderdate,
td.d_ordertype,
+ td.d_jobtype,
td.d_driveruid,
td.d_druid,
td.d_ruid,
@@ -1375,7 +1449,9 @@ class API extends CONF {
WHERE
td.d_customeruid = tc.c_uid
AND td.d_customeruid='".$_POST['c_uid']."'
- AND td.d_orderdate='".$_POST['orderdate']."'");
+ AND td.d_orderdate='".$_POST['orderdate']."'
+ AND td.d_jobtype ='".($_POST['jobtype'] ?? 'UCO')."'"
+ );
$result = array();
if(db_num_rows($sqInput) > 0) {
@@ -1393,6 +1469,7 @@ class API extends CONF {
"d_uid" => $rstInput['d_uid'],
"d_customeruid" => $rstInput['d_customeruid'],
"d_orderdate" => $rstInput['d_orderdate'],
+ "d_jobtype" => $rstInput['d_jobtype'],
"d_driveruid" => $rstInput['d_driveruid'],
"d_druid" => $rstInput['d_druid'],
"d_visitdate" => $rstInput['d_visitdate'],
@@ -1450,282 +1527,192 @@ class API extends CONF {
$error = array($e->getMessage());
$this->response($this->json($error), 417);
}
- }
+ }
- public function saveInput(){
+ public function saveInput()
+ {
try {
- // 오늘 날짜
- $today = new DateTime(date("Y-m-d"));
- //$today = new DateTime('20240425');
- // 지정한 날짜
- $searchDate = new DateTime($_POST['orderdate']);
- // 두 날짜 간 차이 계산
- $interval = $today->diff($searchDate);
-
- $result = array(
- "d_uid" => $_POST['uid'],
- "d_customeruid" => $_POST['customeruid'],
- "d_orderdate" => $_POST['orderdate'],
- "d_driveruid" => $_POST['driveruid'],
- "d_druid" => $_POST['druid'],
- "d_visitdate" => $_POST['visitdate']."000000",
- "d_sludge" => $_POST['sludge'],
- "d_paymenttype" => $_POST['paymenttype'],
- "d_payamount" => $_POST['payamount'],
- "d_payeename" => $_POST['payeename'],
- "d_paystatus" => $_POST['paystatus'],
- "d_note" => $_POST['note']
- );
+ $connect = $GLOBALS['conn'] ?? null;
+ if (!$connect) {
+ throw new Exception("DB connection not found");
+ }
- if ($_POST['paymenttype'] == 'CA') $paystatusSTR = $_POST['paystatus'];
- else $paystatusSTR = "";
+ // =========================
+ // INPUT
+ // =========================
+ $uid = (int)($_POST['uid'] ?? 0);
+ $customerUid = (int)($_POST['customeruid'] ?? 0);
+ $driverUid = (int)($_POST['driveruid'] ?? 0); // member uid (legacy)
+ $druid = (int)($_POST['druid'] ?? 0); // driver uid (new)
+ $creatorUid = trim($_POST['createruid'] ?? '');
- // for integration
- $d_uid = null;
- $columns = array();
- $values = array();
+ $orderdate = preg_replace('/[^0-9]/', '', $_POST['orderdate'] ?? '');
+ $visitdate = preg_replace('/[^0-9]/', '', $_POST['visitdate'] ?? '');
+ $jobtype = $_POST['jobtype'] ?? 'UCO';
- //
- if(strlen($_POST['uid']) > 0) { //update
- qry("UPDATE tbl_daily
- SET d_orderdate = '".$_POST['visitdate']."',
- d_driveruid = '".$_POST['driveruid']."',
- d_inputdate = '".date('YmdHis')."',
- d_modifydate = '".date('YmdHis')."',
- d_quantity = '".$_POST['quantity']."',
- d_sludge = '".$_POST['sludge']."',
- d_paystatus = '".$paystatusSTR."',
- d_payamount = '".$_POST['payamount']."',
- d_visit = 'Y',
- d_visitdate = '".$_POST['visitdate']."000000',
- d_payeename = '".$_POST['payeename']."',
- d_status='F',
- d_is_transfer='N'
- WHERE d_uid='".(int)$_POST['uid']."'");
+ $quantity = (int)($_POST['quantity'] ?? 0);
+ $sludge = trim($_POST['sludge'] ?? '');
+ $paymenttype = trim($_POST['paymenttype'] ?? '');
+ $payamount = trim($_POST['payamount'] ?? '');
+ $payeename = trim($_POST['payeename'] ?? '');
+ $paystatus = trim($_POST['paystatus'] ?? '');
+ $note = trim($_POST['note'] ?? '');
- $sqNote = qry("SELECT n_uid FROM tbl_note WHERE n_dailyuid = '".(int)$_POST['uid']."'");
-
- if(db_num_rows($sqNote) > 0) {
- qry("UPDATE tbl_note
- SET n_note = '".$_POST['note']."'
- WHERE n_dailyuid = '".(int)$_POST['uid']."'");
- }
- else {
- if(strlen(trim($_POST['note'])) > 0){
+ // =========================
+ // VALIDATION
+ // =========================
+ if ($customerUid <= 0) {
+ throw new Exception("invalid customeruid");
+ }
- qry("INSERT INTO tbl_note (
- n_memberuid, n_customeruid, n_dailyuid,
- n_type, n_view, n_note, n_createddate)
- VALUE (
- '".$_POST['driveruid']."', '".$_POST['customeruid']."', '".$_POST['uid']."',
- 'D', 1, '".$_POST['note']."', '".date('YmdHis')."') ");
-
- }
+ if ($visitdate === '' || strlen($visitdate) !== 8) {
+ throw new Exception("invalid visitdate");
+ }
- }
- $d_uid = (int)$_POST['uid'];
+ if ($orderdate === '' || strlen($orderdate) !== 8) {
+ throw new Exception("invalid orderdate");
+ }
- }else{ //new
+ $paystatusSTR = ($paymenttype === 'CA') ? $paystatus : '';
- /* 오더장 있는지 확인 모듈 추가 (2025.02.20) */
- $sqData = qry("SELECT d_uid FROM tbl_daily
- WHERE d_orderdate = '".$_POST['visitdate']."'
- AND d_customeruid = '".$_POST['customeruid']."'");
-
- if(db_num_rows($sqData) <= 0) {
- // 1) 고객 정보 먼저 조회
- $sqCus = qry("
- SELECT
- c_paymenttype, c_paymentcycle, c_rate,
- c_fullquantity, c_fullquantitydaily,
- c_regionuid, c_region
- FROM tbl_customer
- WHERE c_uid = '".(int)$_POST['customeruid']."'
- ");
- $customer = fetch_array($sqCus);
+ // =========================
+ // CUSTOMER LOAD (최소 정보만)
+ // =========================
+ $sqCus = qry("
+ SELECT
+ c_uid,
+ c_accountno
+ FROM tbl_customer
+ WHERE c_uid = '{$customerUid}'
+ LIMIT 1
+ ");
+ $customer = fetch_array($sqCus);
- // 2) 예상수량 계산
- $estqty = max(
- 0,
- ($customer['c_fullquantity'] - $customer['c_fullquantitydaily']) +
- ($interval->days * $customer['c_fullquantitydaily'])
- );
- // 3) set values to erp
- $columns[] = "d_cycle"; $values[] = $customer['c_paymentcycle'];
- $columns[] = "d_rate"; $values[] = $customer['c_rate'];
- $columns[] = "d_estquantity"; $values[] = $estqty;
- $columns[] = "d_ordertype"; $values[] = "N";
+ if (!$customer || empty($customer['c_accountno'])) {
+ throw new Exception("Customer not found");
+ }
- // 기존 insert 문 그대로 사용
-
-
- $sqMem = qry("
- SELECT
- m_currentdriverinitial
- FROM tbl_member
- WHERE m_currentdriver = '".$_POST['druid']."'
- ");
- $rstMem = fetch_array($sqMem);
-
- qry("INSERT INTO tbl_daily (
- d_orderdate, d_driveruid, d_customeruid, d_accountno, d_name,
- d_paymenttype, d_cycle, d_rate, d_form_eu, d_form_corsia, d_maincontainer, d_container, d_location,
- d_address, d_city, d_postal, d_oil_2y, d_oil_1y, d_oil_0y,
- d_fullcycle, d_fullcycleforced, d_fullcycleflag,
- d_lastpickupdate, d_lastpickupquantity, d_lastpaiddate,
- d_druid, d_drinitial, d_regionuid, d_region,
- d_estquantity,
- d_createruid, d_createddate, d_inputdate,
- d_quantity, d_sludge, d_paystatus, d_payamount,
- d_visit, d_visitdate, d_status, d_payeename
- )
- SELECT
- '".$_POST['visitdate']."', '".$_POST['driveruid']."', c_uid, c_accountno, c_name,
- c_paymenttype, c_paymentcycle, c_rate, c_form_eu, c_form_corsia, c_maincontainer, c_container, c_location,
- c_address, c_city, c_postal, 0, 0, 0,
- c_fullcycle, c_fullcycleforced, c_fullcycleflag,
- c_lastpickupdate, c_lastpickupquantity, c_lastpaiddate,
- '".$_POST['druid']."', '{$rstMem['m_currentdriverinitial']}','{$customer['c_regionuid']}', '{$customer['c_region']}',
- IFNULL((c_fullquantity - c_fullquantitydaily + (".(int)$interval->days." * c_fullquantitydaily)),0),
- '".$_POST['createruid']."', '".date('YmdHis')."', '".date('YmdHis')."',
- ".$_POST['quantity'].", '".$_POST['sludge']."', '".$paystatusSTR."', '".$_POST['payamount']."',
- 'Y', '".$_POST['visitdate']."000000"."', 'F', '".$_POST['payeename']."'
- FROM tbl_customer
- WHERE c_uid='".(int)$_POST['customeruid']."'");
+ // =========================
+ // EXISTING DAILY (for update)
+ // =========================
+ $existing = null;
- $sqDailyUid = qry("SELECT d_uid FROM tbl_daily
- WHERE d_customeruid='".(int)$_POST['customeruid']."'
- AND d_orderdate='".$_POST['visitdate']."'
- ORDER BY d_uid DESC LIMIT 1 ");
- $rstDailyUid = fetch_array($sqDailyUid);
- $d_uid = $rstDailyUid['d_uid'];
-
- if(strlen(trim($_POST['note'])) > 0){
- qry("INSERT INTO tbl_note (
- n_memberuid, n_customeruid, n_dailyuid,
- n_type, n_view, n_note, n_createddate)
- VALUE (
- '".$_POST['driveruid']."', '".$_POST['customeruid']."', '".$rstDailyUid['d_uid']."',
- 'D', 1, '".$_POST['note']."', '".date('YmdHis')."') ");
- }
+ if ($uid > 0) {
+ $sqDaily = qry("
+ SELECT *
+ FROM tbl_daily
+ WHERE d_uid = '{$uid}'
+ LIMIT 1
+ ");
+ $existing = fetch_array($sqDaily);
-
- $folderPath = getenv("DOCUMENT_ROOT")."/upload_sign/".$_POST['customeruid'];
- $setFilename = "";
-
- if (is_dir($folderPath)) {
- $files = scandir($folderPath);
- $tmpFilename = "T_".$_POST['visitdate'];
- foreach ($files as $file) {
- if (strstr($file, $tmpFilename)) {
- $setFilename = $file;
- }
- }
-
- if ($setFilename != "") {
- $setFilenameNew = str_replace("T_", "", $setFilename);
- rename($folderPath."/".$setFilename, $folderPath."/".$setFilenameNew);
- qry("UPDATE tbl_daily SET d_payeesign='".$setFilenameNew."'
- WHERE d_uid = '".$rstDailyUid['d_uid']."' ");
- // for integration
- $columns[] = "d_payeesign"; $values[] = $setFilenameNew;
- }
- }
+ if (!$existing) {
+ throw new Exception("Daily record not found");
+ }
+ }
+ $now14 = date('YmdHis');
- }
-
+ // =========================
+ // PAYLOAD (최소값만)
+ // =========================
+ $payload = [
+ 'd_uid' => $uid ?: null,
+ 'd_customeruid' => $customerUid,
+ 'd_accountno' => $customer['c_accountno'],
+ 'd_orderdate' => $visitdate, // 완료 기준
+ 'd_driveruid' => $driverUid,
+ 'd_druid' => $druid,
+
+ 'd_visit' => 'Y',
+ 'd_visitdate' => $visitdate . '000000',
+ 'd_status' => 'F',
+ 'd_jobtype' => 'UCO',
+
+ 'd_quantity' => $quantity,
+ 'd_sludge' => $sludge,
+
+ 'd_paymenttype' => $paymenttype,
+ 'd_payamount' => $payamount,
+ 'd_payeename' => $payeename,
+ 'd_paystatus' => $paystatusSTR,
+
+ 'd_inputdate' => $now14,
+ 'd_is_transfer' => 'N',
+ 'd_level' => $_SESSION['ss_LEVEL'],
+ ];
+error_log("=== saveInput DEBUG ===");
+error_log($_SESSION['ss_LEVEL']);
+ // note → daily.php에서 처리됨
+ if ($note !== '') {
+ $payload['d_pickupnote'] = $note;
+ }
+
+ // 신규 생성 시만
+ if ($uid <= 0) {
+ $payload['d_ordertype'] = 'N';
+ $payload['d_createruid'] = $creatorUid;
+ $payload['d_createddate'] = $now14;
+ }
+
+ // =========================
+ // SIGN FILE 처리
+ // =========================
+ $folderPath = getenv("DOCUMENT_ROOT") . "/upload_sign/" . $customerUid;
+
+ if (is_dir($folderPath)) {
+ $files = scandir($folderPath);
+ $tmpFilename = "T_" . $visitdate;
+
+ foreach ($files as $file) {
+ if (strstr($file, $tmpFilename)) {
+
+ $newName = str_replace("T_", "", $file);
+
+ if ($file !== $newName) {
+ @rename($folderPath . "/" . $file, $folderPath . "/" . $newName);
+ }
+
+ $payload['d_payeesign'] = $newName;
+ break;
+ }
+ }
+ }
+
+ // =========================
+ // SAVE
+ // =========================
+ $opt = [];
+
+ if ($existing) {
+ $opt['match_uid'] = $uid;
+ $opt['old_key'] = [
+ 'd_orderdate' => $existing['d_orderdate'],
+ 'd_accountno' => $existing['d_accountno'],
+ 'd_jobtype' => $existing['d_jobtype'],
+ ];
+ $opt['allow_update'] = true;
}
- ////////////////////////////////////////////////////////////////////////////
- // tbl_customer 의 c_lastpickupdate, c_lastpickupquantity, c_lastpaiddate ,
- // c_orderdate = "", c_orderflag = 0, c_sludge 업데이트
- ////////////////////////////////////////////////////////////////////////////
+ $afterData = $this->dailyService->saveDaily($payload, $opt);
- // d_visitdate 가 c_lastpickupdate 보다 커야 tbl_customer 에 c_lastpickupdate, c_lastpickupquantity 저장
- $qry_a = qry("SELECT c_lastpickupdate, c_paymenttype FROM tbl_customer WHERE c_uid = '".$_POST['customeruid']."' ");
- $rt_a = fetch_array($qry_a);
+ // =========================
+ // RESPONSE
+ // =========================
+ $this->response($this->json([
+ "msg" => "Input has been successfully saved.",
+ "d_uid" => $afterData['d_uid'] ?? $uid
+ ]), 200);
- $c_lastpickupdate = $rt_a['c_lastpickupdate'];
-
- if ($_POST['visitdate'] >= $c_lastpickupdate) {
- $addQry_a = " c_lastpickupdate = '".$_POST['visitdate']."', c_lastpickupquantity = '".$_POST['quantity']."',";
-
- if (trim($_POST['sludge']) != "") {
- $add_sludge = " c_sludge = '".$_POST['sludge']."', ";
-
- // tbl_daily 의 sludge update - 2025-12-09 history 안건드리기
- // qry("UPDATE tbl_daily SET d_sludge='".$_POST['sludge']."'
- // WHERE d_customeruid = '".$_POST['customeruid']."' ");
- }
- else $add_sludge = "";
- }
- else {
- $addQry_a = "";
- $add_sludge = "";
- }
-
-
- if ($rt_a['c_paymenttype'] == "CA" && $_POST['paystatus'] == "P") {
- $addQry = " c_lastpaiddate = '".$_POST['visitdate']."', ";
- $addWhereQry = "AND (c_lastpaiddate < '".$_POST['visitdate']."' OR c_lastpaiddate IS NULL) ";
- } else {
- $addQry = "";
- $addWhereQry = "";
- }
-
- //if (trim($d_sludge) != "") $add_sludge = " c_sludge = '$d_sludge', ";
- //else $add_sludge = "";
-
- qry("UPDATE tbl_customer
- SET
- ".$addQry_a."
- ".$addQry."
- c_orderdate = '',
- ".$add_sludge."
- c_orderflag = 0
- WHERE c_uid = '".$_POST['customeruid']."' ". $addWhereQry ." ");
- // ====================
- // Integration to ERP
- // ====================
- $columns[] = "d_accountno"; $values[] = $_POST['customerno']; // c_accountno
- $columns[] = "d_orderdate"; $values[] = $_POST['visitdate']; // yyyymmdd (ERP에서 LocalDate로 변환)
- $columns[] = "d_driveruid"; $values[] = $_POST['driveruid']; // external driver id (MIS)
- $columns[] = "d_quantity"; $values[] = $_POST['quantity'];
- $columns[] = "d_sludge"; $values[] = $_POST['sludge'];
- $columns[] = "d_paymenttype"; $values[] = $_POST['paymenttype'];
- $columns[] = "d_payamount"; $values[] = $_POST['payamount'];
- $columns[] = "d_payeename"; $values[] = $_POST['payeename'];
- $columns[] = "d_paystatus"; $values[] = $paystatusSTR;
- $columns[] = "d_status"; $values[] = "F"; // 완료 상태
- $columns[] = "d_visit"; $values[] = "Y"; // 방문 상태
- $columns[] = "d_inputdate"; $values[] = date('YmdHis'); // 입력 시간
- if(strlen(trim($_POST['note'])) > 0){
- $columns[] = "d_pickupnote"; $values[] = $_POST['note'];
- }
-
- // ERP로 전송
- $erp = new ErpApi();
- $lguserid = $_POST['createruid'];
- if(strlen($_POST['uid']) > 0) {
- $erp->updateDailyOrderFromMis($columns, $values, $lguserid);
- } else {
- $erp->createDailyOrderFromMis($columns, $values, $lguserid);
- }
-
- // 성공 시 플래그 & 로그
- qry("UPDATE tbl_daily SET d_is_transfer = 'Y' WHERE d_uid = ".(int)$d_uid);
-
- //
- $this->response($this->json(array("msg"=>"Input has been successfully saved.")), 200);
- //$this->response($this->json(array("result"=>$result)), 200);
return;
- } catch(Exception $e) {
- $error = array($e->getMessage());
+
+ } catch (Exception $e) {
+
+ $error = [$e->getMessage()];
$this->response($this->json($error), 417);
- }
- }
+ }
+ }
public function inqMapCenter(){
diff --git a/public_html/doc/customer_detail.php b/public_html/doc/customer_detail.php
index 6450115..e549196 100644
--- a/public_html/doc/customer_detail.php
+++ b/public_html/doc/customer_detail.php
@@ -88,8 +88,6 @@ if ($mode == "update") {
$c_schedulebasicSTR = $func -> convertFormat ($c_schedulebasic, 3);
$c_fpickupSTR = $func -> convertFormat ($c_fpickup, 3);
- //$c_removaldateSTR = $func -> convertFormat ($c_removaldate, 3);
-
if ($c_removaldate != "N/A") $c_removaldateSTR = $func -> convertFormat ($c_removaldate, 3);
else $c_removaldateSTR = "N/A";
@@ -116,8 +114,6 @@ else {
// Get Status Info
foreach ($arrStatus AS $key=>$value)
{
- //echo "[$key][$value]"; => [0][Waiting][1][Confirmed][E][Declined]...
-
if ($key == $c_status) $selectStr = "selected";
else $selectStr = "";
@@ -129,43 +125,32 @@ foreach ($arrStatus AS $key=>$value)
// Get Payment Info
foreach ($arrPaymenttype AS $key=>$value)
{
- //echo "[$key][$value]"; => [0][Waiting][1][Confirmed][E][Declined]...
-
if ($key == $c_paymenttype) $selectStr = "selected";
else $selectStr = "";
- $c_paymenttypeSTR .= "
- ";
+ $c_paymenttypeSTR .= "";
}
-
// Get Bin (Main Container) Info
foreach ($arrBin AS $key=>$value)
{
- //echo "[$key][$value]"; => [0][Waiting][1][Confirmed][E][Declined]...
-
if ($key == $c_maincontainer) $selectStr = "selected";
else $selectStr = "";
- $c_maincontainerSTR .= "
- ";
+ $c_maincontainerSTR .= "";
}
// Get Pickup Schedule
foreach ($arrSchedule AS $key=>$value)
{
- //echo "[$key][$value]"; => [0][Waiting][1][Confirmed][E][Declined]...
-
if ($key == $c_schedule) $selectStr = "selected";
else $selectStr = "";
- $c_scheduleSTR .= "
- ";
+ $c_scheduleSTR .= "";
}
-$curDR = "";
-
// Get Driver Info => Region
+$curDR = "";
$qry_driver = "SELECT * FROM tbl_member WHERE m_level = 9 AND m_region != '' ORDER by m_initial ASC ";
$rt_driver = $jdb->nQuery($qry_driver, "list error");
@@ -177,13 +162,10 @@ while($lt_driver=mysqli_fetch_array($rt_driver, MYSQLI_ASSOC)) {
}
else $selectStr = "";
- $c_driveruidSTR .= "
- ";
+ $c_driveruidSTR .= "";
}
-
-
// Get Driver Info (Request)
$qry_dr = "SELECT * FROM tbl_driver WHERE dr_status = 'A' ORDER by dr_initial ASC ";
$rt_dr = $jdb->nQuery($qry_dr, "list error");
@@ -193,12 +175,9 @@ while($lt_dr=mysqli_fetch_array($rt_dr, MYSQLI_ASSOC)) {
if ($lt_dr['dr_uid'] == $curDR) $selectStr = "selected";
else $selectStr = "";
- $c_driveruidSTRRQ .= "
- ";
-
+ $c_driveruidSTRRQ .= "";
}
-
// Get City Info
$qry_city = "SELECT * FROM tbl_area WHERE a_status = 'A' ORDER by a_city ASC ";
$rt_city = $jdb->nQuery($qry_city, "list error");
@@ -213,12 +192,9 @@ while($lt_city=mysqli_fetch_array($rt_city, MYSQLI_ASSOC)) {
$selectStr = "";
}
- $c_citySTR .= "
- ";
-
+ $c_citySTR .= "";
}
-
// get scheduled day info
$c_scheduledayTMP = explode('|', $c_scheduleday);
@@ -231,7 +207,6 @@ for ($i=0; $i < count($c_scheduledayTMP); $i++) {
if ($c_scheduledayTMP[$i] == "SAT") $c_scheduledaySAT = "checked";
}
-
// Get Sale Person
$qry_sp = "SELECT * FROM tbl_salesperson WHERE s_status = 'A' ORDER by s_name ASC ";
$rt_sp = $jdb->nQuery($qry_sp, "list error");
@@ -241,38 +216,28 @@ while($lt_sp=mysqli_fetch_array($rt_sp, MYSQLI_ASSOC)) {
if ($lt_sp['s_name'] == $c_salesperson) $selectStr = "selected";
else $selectStr = "";
- $c_salespersonSTR .= "
- ";
+ $c_salespersonSTR .= "";
}
-
// Get Form info
foreach ($arrForm AS $key=>$value)
{
- //echo "[$key][$value]"; => [0][Waiting][1][Confirmed][E][Declined]...
-
if ($key == $c_form_new) $selectStr = "selected";
else $selectStr = "";
- $c_form_newSTR .= "
- ";
+ $c_form_newSTR .= "";
}
-
// Get Sales Method info
foreach ($arrSalesMethod AS $key=>$value)
{
- //echo "[$key][$value]"; => [0][Waiting][1][Confirmed][E][Declined]...
-
if ($key == $c_salesmethod) $selectStr = "selected";
else $selectStr = "";
- $c_salesmethodSTR .= "
- ";
+ $c_salesmethodSTR .= "";
}
-
// Get Form info
foreach ($arrPaymentCycle AS $key=>$value)
{
@@ -281,144 +246,113 @@ foreach ($arrPaymentCycle AS $key=>$value)
if ($key == $c_paymentcycle) $selectStr = "selected";
else $selectStr = "";
- $c_paymentcycleSTR .= "
- ";
+ $c_paymentcycleSTR .= "";
}
-
// 오늘 날짜의 오더장이 있는지 확인
// 있으면 정보를 가져와서 아래 조건 확인, 없는 경우 새로 생성
-
$qry_cnt_d = "SELECT COUNT(*) FROM tbl_daily WHERE d_customeruid = '$c_uid' AND d_orderdate = '".date("Ymd")."'";
$totcnt_d=$jdb->rQuery($qry_cnt_d, "record query error");
-if ($mode == "update") {
+//
+$pickupButtonHtml = "";
+$PICKUPstr = "";
+$add_qry = ($_SESSION['ss_LEVEL'] == 9) ? " AND dr_uid = '".$_SESSION['ss_DRUID']."' " : "";
- if ($totcnt_d == 0) {
- $PICKUPstr = "";
- //$PICKUPstr = "";
-
- $d_orderdateSTR = date("Y-m-d");
- $d_paymenttype = $c_paymenttype;
- $d_customeruid = $c_uid;
-
-
- $setDisplayNEWStr = " DISPLAY:none; ";
- $setDisplayBTNStr = " DISPLAY:block; ";
- $setDisplaySIGNYESStr = " DISPLAY:none; ";
- $setDisplaySIGNNEWStr = " DISPLAY:inline; ";
-
- } else {
- // d_orderdate 이 현재일이고, Finished 안된 경우만 입력할수 있음
- // 운영자는 예외
-
- // Get Information
- $query = "SELECT * FROM tbl_daily WHERE d_customeruid = '$c_uid' AND d_orderdate = '".date("Ymd")."'";
- $result=$jdb->fQuery($query, "fetch query error");
- // echo"$query";
-
- for($i=0; $i $value )
- $$key = $value;
- }
-
-
- // d_orderdate 는 변경못하게 했는데 수정할수 있게 해달라고 요청받음
- // 운영자의 경우 d_orderdate 를 변경할수 있으므로 오늘날짜를 다른것으로 바꾸면 d_mode 는 update 가 아님
- // 문제가 생길수 있음. 나중에 처리 필요
- $d_mode = "update";
- $d_orderdateSTR = $func -> convertFormat ($d_orderdate, 3);
-
- if (($d_orderdate == date("Ymd") && $d_status != "F") || $_SESSION['ss_LEVEL'] == "1") {
- $PICKUPstr = "";
- //$PICKUPstr = "";
- }
- else $PICKUPstr = "";
-
- // signiture 처리 (2023.11.28)
- $d_payeenameSTR = str_replace("\\", "", $d_payeename);
-
- $folderPath = getenv("DOCUMENT_ROOT")."/upload_sign/".$d_customeruid;
-
- if (is_file($folderPath."/".trim($d_payeesign))) {
- $d_payeesignSTR = "
";
- $setDisplayNEWStr = " DISPLAY:inline; ";
- $setDisplayBTNStr = " DISPLAY:none; ";
- $setDisplaySIGNYESStr = " DISPLAY:inline; ";
- $setDisplaySIGNNEWStr = " DISPLAY:none; ";
- }
- else {
- $setDisplayNEWStr = " DISPLAY:none; ";
- $setDisplayBTNStr = " DISPLAY:block; ";
- $setDisplaySIGNYESStr = " DISPLAY:none; ";
- $setDisplaySIGNNEWStr = " DISPLAY:inline; ";
- }
-
- // 이미 존재하는 오더장을 수정한다면 Note 정보도 가져와야 함
- $qry_note = "SELECT * FROM tbl_note WHERE n_dailyuid = '$d_uid' ";
- $rt_note=$jdb->fQuery($qry_note, "fetch query error");
- $n_noteSTRM = str_replace("\\", "", $rt_note['n_note']);
-
- //echo "
[$qry_note][$n_noteSTR]";
-
- }
-
-} else $PICKUPstr = "";
-
-if ($_SESSION['ss_LEVEL'] == 7) $PICKUPstr = "";
-
-if ($_SESSION['ss_LEVEL'] == 9) $add_qry = " AND dr_uid = '".$_SESSION['ss_DRUID']."' ";
-else $add_qry = "";
+// display 기본값
+$setDisplayNEWStr = " DISPLAY:none; ";
+$setDisplayBTNStr = " DISPLAY:block; ";
+$setDisplaySIGNYESStr = " DISPLAY:none; ";
+$setDisplaySIGNNEWStr = " DISPLAY:inline; ";
if ($mode == "update") {
- // Get Region Info
- $qry_rg = "SELECT * FROM tbl_member WHERE m_uid = ".$c_driveruid;
- $rt_rg = $jdb->fQuery($qry_rg, "list error");
- // Get Driver Info
- $qry_driver = "SELECT * FROM tbl_driver WHERE dr_uid >= 1 AND dr_status = 'A' ".$add_qry." ORDER by dr_initial ASC ";
- $rt_driver = $jdb->nQuery($qry_driver, "list error");
+ if ($totcnt_d == 0) {
+ // 신규 pickup 입력 상태
+ $PICKUPstr = $pickupButtonHtml;
- while($lt_driver=mysqli_fetch_array($rt_driver, MYSQLI_ASSOC)) {
+ $d_orderdateSTR = date("Y-m-d");
+ $d_paymenttype = $c_paymenttype;
+ $d_customeruid = $c_uid;
- if ($lt_driver['dr_uid'] == $rt_rg['m_currentdriver']) $selectStr = "selected";
- else $selectStr = "";
+ } else {
+ // 기존 daily 정보 조회
+ $query = "SELECT * FROM tbl_daily WHERE d_customeruid = '$c_uid' AND d_orderdate = '".date("Ymd")."' AND d_jobtype = 'UCO'";
+ $result = $jdb->fQuery($query, "fetch query error");
- if ($d_mode == "update") {
- if ($lt_driver['dr_uid'] == $d_druid) $selectStr = "selected";
- else $selectStr = "";
- }
-
- $c_driveruidSTRM .= "
- ";
-
- }
+ if (is_array($result)) {
+ foreach ($result as $key => $value) {
+ $$key = $value;
+ }
+ }
+
+ // update 모드 강제
+ $d_mode = "update";
+ $d_orderdateSTR = $func->convertFormat($d_orderdate, 3);
+
+ // pickup 버튼 노출 조건
+ $canInputPickup = (
+ ($d_orderdate == date("Ymd") && $d_status != "F")
+ || $_SESSION['ss_LEVEL'] == "1"
+ );
+
+ if ($canInputPickup) {
+ $PICKUPstr = $pickupButtonHtml;
+ }
+
+ // signature 처리
+ $d_payeenameSTR = str_replace("\\", "", $d_payeename);
+ $folderPath = getenv("DOCUMENT_ROOT")."/upload_sign/".$d_customeruid;
+ $signFilePath = $folderPath."/".trim($d_payeesign);
+
+ if (is_file($signFilePath)) {
+ $d_payeesignSTR = "
";
+
+ $setDisplayNEWStr = " DISPLAY:inline; ";
+ $setDisplayBTNStr = " DISPLAY:none; ";
+ $setDisplaySIGNYESStr = " DISPLAY:inline; ";
+ $setDisplaySIGNNEWStr = " DISPLAY:none; ";
+ }
+
+ // note 조회
+ $qry_note = "SELECT * FROM tbl_note WHERE n_dailyuid = '$d_uid'";
+ $rt_note = $jdb->fQuery($qry_note, "fetch query error");
+ $n_noteSTRM = str_replace("\\", "", $rt_note['n_note']);
+ }
}
-/*
-// Get Driver Info
-$qry_driver = "SELECT * FROM tbl_member WHERE m_level = 9 ".$add_qry." ORDER by m_initial ASC ";
-$rt_driver = $jdb->nQuery($qry_driver, "list error");
-
-while($lt_driver=mysqli_fetch_array($rt_driver, MYSQLI_ASSOC)) {
-
- if ($lt_driver['m_uid'] == $c_driveruid) $selectStr = "selected";
- else $selectStr = "";
-
- if ($d_mode == "update") {
- if ($lt_driver['m_uid'] == $d_driveruid) $selectStr = "selected";
- else $selectStr = "";
- }
-
- $c_driveruidSTRM .= "
- ";
-
+// Level 7, 8 은 pickup 버튼 숨김
+if ($_SESSION['ss_LEVEL'] == 7 || $_SESSION['ss_LEVEL'] == 8) {
+ $PICKUPstr = "";
}
-*/
+if ($mode == "update") {
+ // 현재 고객의 드라이버 정보
+ $qry_rg = "SELECT * FROM tbl_member WHERE m_uid = ".$c_driveruid;
+ $rt_rg = $jdb->fQuery($qry_rg, "list error");
+ // 활성 드라이버 목록
+ $qry_driver = "SELECT * FROM tbl_driver WHERE dr_uid >= 1 AND dr_status = 'A' $add_qry ORDER BY dr_initial ASC";
+ $rt_driver = $jdb->nQuery($qry_driver, "list error");
+
+ $c_driveruidSTRM = "";
+
+ while ($lt_driver = mysqli_fetch_array($rt_driver, MYSQLI_ASSOC)) {
+ $selected = "";
+
+ // 기본 선택값: member 의 current driver
+ if ($lt_driver['dr_uid'] == $rt_rg['m_currentdriver']) {
+ $selected = "selected";
+ }
+
+ // update 상태면 daily 의 d_druid 가 우선
+ if ($d_mode == "update") {
+ $selected = ($lt_driver['dr_uid'] == $d_druid) ? "selected" : "";
+ }
+
+ $c_driveruidSTRM .= "";
+ }
+}
addLog ("add", "CUSTOMER DETAIL", "VIEW", $lguserid, $query, $c_uid);
@@ -498,13 +432,6 @@ $(function () {
}
});
});
-
-
-/*
-$(function() {
- $( "#c_salescommissiondate" ).datepicker();
- });
-*/
});
@@ -512,34 +439,6 @@ $(function() {
-
-