diff --git a/src/app/api/m/orders/items/update/route.ts b/src/app/api/m/orders/items/update/route.ts index 5ec64df..9a8983c 100644 --- a/src/app/api/m/orders/items/update/route.ts +++ b/src/app/api/m/orders/items/update/route.ts @@ -113,6 +113,43 @@ export async function POST(req: NextRequest) { const isFree = cur.is_tax_free === "Y"; const calc = calcLine({ unitPrice: Number(cur.unit_price), qty: newQty, isTaxFree: isFree }); + + // 출고완료(APPROVED) 상태에서 수량 변경 시 재고 ± 동기화 + stock_moves 이력 + // ITEM 종류만 (택배/용차는 재고 미차감이라 skip — 위 cur.kind 검사로 ITEM 확정됨) + if (order.status === "APPROVED") { + const oldQty = Number(cur.qty); + const diff = newQty - oldQty; // +면 추가 차감, -면 복원 + if (diff !== 0) { + // 출고 시 사용된 창고 — momo_stock_moves 의 OUT ref_objid 매칭으로 lookup + const whRes = await client.query( + `SELECT wh_objid FROM momo_stock_moves + WHERE ref_type = 'ORDER' AND ref_objid = $1 AND item_objid = $2 + ORDER BY regdate ASC LIMIT 1`, + [orderObjid, cur.item_objid] + ); + if (whRes.rowCount && whRes.rows[0].wh_objid) { + const whObjid = whRes.rows[0].wh_objid; + await client.query( + `UPDATE momo_stocks SET qty = qty - $1, update_date = NOW() + WHERE wh_objid = $2 AND item_objid = $3`, + [diff, whObjid, cur.item_objid] + ); + // 이력 — qty 부호: +이면 추가 출고(-diff), -이면 복원(+|diff|). + // move_type 은 OUT(-) / IN(+) 으로 표기, qty 컬럼은 부호 그대로. + const moveType = diff > 0 ? "OUT" : "IN"; + const moveQty = -diff; // OUT 이면 -, IN 이면 + + const moveObjid = String(Date.now()) + String(Math.floor(Math.random() * 10000)); + await client.query( + `INSERT INTO momo_stock_moves + (objid, wh_objid, item_objid, move_type, qty, ref_type, ref_objid, memo, regdate, regid) + VALUES ($1, $2, $3, $4, $5, 'ORDER', $6, $7, NOW(), $8)`, + [moveObjid, whObjid, cur.item_objid, moveType, moveQty, orderObjid, + `수량 수정: ${oldQty} → ${newQty}`, r.user.objid ?? r.user.userId] + ); + } + } + } + await client.query( `UPDATE momo_order_items SET qty = $2,