> For the complete documentation index, see [llms.txt](https://lmile.gitbook.io/lmile-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lmile.gitbook.io/lmile-docs/reference/data-model.md).

# Data Model

## テーブル構造

```
sot.products (商品マスター)
  ├─ id (uuid) PK
  ├─ shop + barcode (UNIQUE) ← 受注・在庫との結合キー
  ├─ product_name, sku, variant_name, brand, category_l1/l2/l3
  ├─ current_price, current_compare_at_price, current_cost, currency
  ├─ is_non_inventory (非在庫サービス品フラグ。true はルーティング引き当て対象外 → serviceLines)
  ├─ is_accessory_service (付帯サービス。現物の無い明細。true は必ず is_non_inventory=true)
  ├─ inventory_push_disabled_source_ids (この商品の在庫連携を止めた出荷元の拠点 id。その出荷元の出荷元在庫の通知は 0 になる)
  │
  ├──< sot.product_update_logs (変更ログ)
  │     └─ change_type: created / updated (+ changed_fields)
  │
  └──< sot.inventory_levels (在庫)
        ├─ product_id FK → products.id
        ├─ location_id FK → locations.id
        ├─ on_hand_qty, available_qty, committed_qty, allocated_qty, reserved_qty, incoming_qty
        │   (ルーティング引き当ては routable = available_qty + committed_qty で判定)
        ├─ held_qty (取り置き合計) / available_qty_gross (取り置き前の取込値。取り置きのある行だけ)
        ├─ channel_available_qty / channel_available_as_of (販売チャネルでの販売可能数。外部倉庫の拠点で 0 以下なら available_qty = 0)
        │   available_qty = greatest(0, 取込値 − held_qty)。available_qty 更新時にトリガで引き直す
        │
        ├──< sot.lm_inventory_holds (取り置き台帳)
        │     └─ UNIQUE (shop, reference_id, location_id, product_id) / quantity>0 / expires_at (任意)
        │
        └──< sot.inventory_update_logs (変更ログ)
              └─ change_type: snapshot / available_set / available_delta / committed_set / on_hand_set

sot.locations (拠点マスター)
  ├─ id (uuid) PK
  ├─ display_label, location_type, region
  └─ ec_fulfillable, is_active

sot.order_line_master (受注 / 1 row = 1 販売単位)
  ├─ barcode ──結合──> products.barcode
  ├─ channel_id ──> channels.id, location_id ──> locations.id
  └─ net_amount_taxincl, tax_amount, refund_amount, ...

sot.lm_visit_reservations (来店予約。1 行 = 1 予約)
  ├─ location_id ──> locations.id / reservation_no (V + 7 桁) / starts_at・ends_at (UTC) + timezone / companion_count (同伴者の人数・枠の上限には数えない) / purpose (ご来店の目的)
  ├─ status: confirmed | cancelled_by_customer | cancelled_by_store | no_show / visit_status: not_arrived → arrived → served
  └──< sot.lm_visit_events (予約の履歴。visit_changed 等・actor_kind / actor_email)

sot.lm_stocktake_sessions (棚卸セッション。LM-2467)
  ├─ 拠点ごとに進行中 (counting / submitted) は 1 つ (部分 UNIQUE) / mode=shelf (MFC の棚ごと) | location (店舗・拠点全体。LM-2476) / status: counting → submitted → committed | cancelled
  ├──< sot.lm_stocktake_shelves (数える棚。PK (session_id, shelf_code) / status counting|closed / started_at / movement_detected / recount_no)
  └──< sot.lm_stocktake_counts (計数 = 棚 × 商品 × 状態)
        ├─ 有効行で UNIQUE (session_id, shelf_code, product_id, condition_code) (superseded_at IS NULL)
        ├─ counted_qty (数えた数。帳簿にあるが読まれなかった商品は 0) / expected_qty (棚を締めた時点の帳簿数)
        ├─ superseded_at (再計数で置き換えた旧行) / applied_at / applied_delta / apply_error_kind (counted_below_active | negative_after_delta)
        └─ 反映は差分 (counted − expected) を lm_shelf_inventory / lm_shelf_condition_stock に当て、lm_shelf_inventory_logs に reason=stocktake + stocktake_session_id
  ├──< sot.lm_stocktake_location_lines (mode=location の商品ごとの行。提出で固定。LM-2476)
  │     ├─ UNIQUE (session_id, product_id) / counted_good_qty / counted_other_qty (記録のみ)
  │     ├─ book_on_hand_qty (取り込み元の生の在庫数 inventory_levels.on_hand_qty) + allocated_unsecured_qty (allocated で未確保の unit) = expected_qty
  │     ├─ movement_detected (window_start 以降に inventory_update_logs か unit が動いた) / applied_at / applied_delta / apply_error_kind (moved_while_counting)
  │     └─ write_back: adjustment (下の調整を作った) | record_only (inbound_only / 外部 ID なし) | none (差 0)
  └──> sot.lm_inventory_external_adjustments (外部システムへ当てる差分 = 相対値。LM-2476)
        ├─ UNIQUE (session_id, product_id) / connector (smaregi | shopify) / delta (<>0)
        ├─ status: pending → claimed → applied | failed | unknown (claimed のまま一定時間で再 claim・attempts++)
        └─ claim / result は /api/routing/inventory-adjustments/* (x-ingest-secret)。lm-os は外部 API を知らない
  read view: agent_read.stocktake_sessions / stocktake_shelves / stocktake_counts (delta = counted − expected) / stocktake_location_lines / inventory_external_adjustments

sot.inventory_condition_codes (商品状態のマスタ。LM-1207 → LM-2466 で棚 × 状態の数の軸に)
  ├─ PK (shop, code)。is_default = 良品 (shop に 1 つ・既定 A) / allocatable_default (表示メタ。引当は見ない)
  ├─ seed A(default)/B/C/UNKNOWN。locations AFTER INSERT トリガで新規 shop に自動 seed (LM-1212)
  └─ 良品以外の数は sot.lm_shelf_condition_stock (棚 × barcode × 状態)。旧 inventory_balances (available の内訳) は LM-2475 で撤去

sot.inventory_ledger (取り置きの履歴 append-only / 真実源ではない)
  └─ event_type = hold・release (LM-2019)。旧 classify / block_release は LM-2475 で書き手ごと撤去
  read view: agent_read.inventory_condition_codes / inventory_ledger

sot.lm_fulfillment_source_members (出荷元 → 在庫ロケーション 紐付け / 1:N)
  └─ UNIQUE (shop, inventory_location_id) ← 在庫ロケーションは1出荷元のみ
        出荷元の合算 available_qty = member 在庫ロケーションの available_qty 合算

sot.lm_fulfillment_source_webhook_config (出荷元の合算在庫変動 webhook 送信設定)
  └─ UNIQUE (shop, fulfillment_source_location_id) / auth_secret_encrypted = pgcrypto暗号化 (鍵=Vault)
sot.lm_fulfillment_source_inventory_state (出荷元×product ごとの前回送信した合算値 = dedup)
  └─ UNIQUE (shop, fulfillment_source_location_id, product_id)
sot.lm_fulfillment_source_inventory_events (合算変動イベント outbox + 送信ログ / secret なし)
  └─ delivery_status: pending / sent / failed / skipped

sot.lm_routing_orders (受注ルーティングの注文ヘッダ / routing-native)
  ├─ delivery_method: shipping (既定) / pickup (店舗受け取り。受け取り店舗 = 出荷元・ラベル無し)
  ├─ UNIQUE (shop, source_system, external_order_ref) ← 入口冪等
  ├─ status: received / routed / dispatched / failed / no_stock / cancelled
  ├─ tag (ディスパッチ先選択条件)
  ├─ 詳細配送先 ship_to_name/company/phone/email/address1/address2 は PII
  │     → 公開 view lm_v_routing_orders からは除外 (service_role 直のみ)
  │     = 出荷ラベル宛先住所の単一ソース。住所修正で更新 + ship_to_corrected_at/by 監査
  ├─ ship_to_email_norm = lower(btrim(ship_to_email)) の生成列 (顧客注文照会 API の突合キー。
  │     PII のため公開 view / agent_read に出さない)
  │
  ├──< sot.lm_routing_order_ship_to_changes (宛先住所・氏名の変更履歴 / append-only)
  │     ├─ before / after = 変更前後の宛先住所スナップショット (PII) / changed_fields = 変更項目
  │     ├─ changed_by_staff_user_id (operator JWT 経由) / changed_by (correctedBy) / changed_at
  │     └─ service_role 専用 (公開 view / agent_read 非公開)。値が変わったときだけ 1 行 append
  │
  ├──< sot.lm_routing_decisions (unit 単位の判定結果, decision_status=applied)
  │     ├─ fulfillment_source_location_id=指定出荷元 / selected_location_id=引き当て先在庫ロケーション
  │     ├─ line_properties = 明細単位の任意キー/値 (routing lines[].properties。刻印等
  │     │     PII になり得るため agent_read 非公開)
  │     ├─ oversold / superseded_by_decision_id ← 売越し・再引き当て
  │     ├─ oversold_by_staff_user_id / created_by_staff_user_id (operator JWT 経由の操作者。機械間 secret 経由は NULL)
  │     └──< sot.lm_routing_candidates (拠点別スコア snapshot / 除外理由)
  │           └─ available_qty_at_decision / committed_qty_at_decision = 判定時の在庫 split
  │
  └──< sot.lm_shipping_instructions (出荷指示 dispatch ログ)
        └─ UNIQUE (shop, idempotency_key) ← 出口冪等
           delivery_status: pending / sent / failed / skipped

sot.lm_location_dispatch_config (在庫ロケーション単位の WMS 送信設定)
  └─ UNIQUE (shop, location_id, tag, action) / auth_secret_encrypted = pgcrypto暗号化 (鍵=Supabase Vault)
        tag=NULL は既定 / action=create|update|cancel|label|print。解決は action 完全一致 + tag 一致優先

sot.lm_wms_shipping_requests (WMS 出荷指示 SHIPPING_REQUEST の送信記録。/api/routing/wms-shipping-request)
  └─ mode: shadow|live / status: shadow|pending|success|error
        instruction     = 受け取った出荷指示 (倉庫ベンダー非依存の中立モデル)
        request_payload = 倉庫へ実際に送った本文 (様式変換は送信 app 側)
        いずれも配送先・請求先 PII を含むため view 非公開・service_role 専用
        label/print の解決キーは出荷元 (fulfillment source location)
sot.lm_location_dispatch_log (WMS 送信ログ / delivery_status, secret は含まない)

sot.lm_location_star_printers (在庫ロケーション → Star プリンター device ID 紐付け)
  └─ UNIQUE (shop, location_id) ← 1 ロケーション 1 プリンター

sot.lm_external_sku_mappings (外部システム SKU ↔ barcode の明示マッピング)
  └─ UNIQUE (shop, system, external_sku) / is_active / notes
        人間レビュー済みの登録のみ (SKU 名からの自動マッピング禁止)。system 例 'amazon_mcf_us'
        消費者 = fulfill-job の sellerSku 解決 + GET /api/ingest/sku-mappings の読み取り

sot.lm_fulfillment_shipments (出荷元ヘッダ = 梱包単位 / 注文 × from_location)
  ├─ UNIQUE (shop, routing_order_id, from_location_id)
  ├─ status: allocated → secured → in_transit_to_mfc → packing → shipped (+ oversell_*)
  ├─ handover_ready_at / handed_over_at (店舗受け取りの 受取待ち / 引渡し済み の時刻。order_status は ready_for_pickup / picked_up)
  ├─ tracking_number / carrier_code / label_pdf_path (ラベルは梱包単位に1つ)
  ├─ external_fulfillment_id / external_fulfillment_accepted_at (外部フルフィルメント発注の受理マーカー
  │     = fulfill-result が記録。fulfill-job の再発注 skip / fulfill-pending の走査対象判定)
  ├─ last_label_error (発行失敗のキャリア応答 → 住所修正 + retry-label でリカバリ)
  ├─ label_printed_at / last_print_error (出荷元 print server への物理印刷結果 → print-label で再印刷)
  ├─ label_retried_by_staff_user_id / label_printed_by_staff_user_id
  │     (operator JWT 経由でラベル再発行 / 手動再印刷を実行したスタッフ。機械間 secret 経由は NULL)
  ├─ status_reported_by_staff_user_id
  │     (operator JWT 経由で出荷ステータス遷移を報告したスタッフ。機械間 secret 経由は NULL)
  │
  └──< sot.lm_fulfillment_units (1 row = 1 販売単位 / order_line_master 方式・数量列なし)
        ├─ barcode / sku / line_instance_no, routing_decision_id へリンク
        ├─ line_properties (明細単位の任意キー/値。decision から非正規化, agent_read 非公開)
        ├─ allocated_location_id(引当) / fulfillment_source_location_id(出荷元)
        ├─ current_inventory_location_id(現在在庫・店舗→MFCで更新)
        ├─ status (ヘッダと同10値) / secured (在庫確保フラグ)
        │
        ├─ picked_at / picked_by (MFC 内ピッキング完了 = 配送 status と直交の作業状態。
        │     ユニットQR スキャンで更新。NULL = 未 pick。旧 mfc ready_for_pickup.status=picked 相当)
        ├─ secured_by_staff_user_id (operator JWT 経由で在庫確保したスタッフ。機械間 secret 経由は NULL)
        │
        ├──< sot.lm_oversell_cases (売越し 8ステップ + wont_do)
        │     ├─ found_location_id / tracking_number / external_shipment_ref / 各ステップ ts
        │     ├─ opened_by_staff_user_id / updated_by_staff_user_id (operator JWT 経由の起票者 / 前進操作者。機械間 secret 経由は NULL)
        │     (LM-498 の oversold フラグとは独立共存)
        │
        └──< sot.lm_fulfillment_source_changes (出荷元変更 + 返送レグ追跡)
              ├─ from/to_source_location_id (旧/新 出荷元) + from/to_inventory_location_id
              ├─ status: change_requested → return_in_transit → return_received (+ cancelled)
              ├─ return_tracking_number / return_label_pdf_path / reason / 各ステップ ts
              ├─ leg_mode: transfer (返送) / switch (出荷元だけ切替) / inbound (出荷元への入荷転送)
              └─ batch_id ──> sot.lm_transfer_batches (倉庫間移動バルク。NULL = 未所属)
              (出荷元そのものを切替。unit.status=source_change_pending/in_transit に連動)

sot.lm_transfer_batches (拠点間移動バルク)
  ├─ kind: return (出荷元→倉庫の返送。返送ラベルを発行する)
  │        / inbound (現物を出荷元へ運ぶ入荷転送。既発行の便を追跡するだけ)
  ├─ from/to_location_id (送り側 / 宛先の出荷元)
  ├─ status: open → dispatched → received (inbound は登録時から dispatched)
  ├─ tracking_config_location_id / _tag (配送状況を引くときの設定の解決先)
  ├─ tracking_status / _raw_status / _checked_at / _last_event / _error (配送状況スナップショット)
  └─ pdf_storage_path (内容物リスト PDF) / dispatched_at / received_at / created_by_staff_user_id

sot.lm_stock_transfers (拠点間 在庫移動 = 商品×数量の location→location 移動 / 返送バルクとは別物)
  ├─ origin/destination_location_id (出庫元 / 入庫先) + *_location_snapshot (削除耐性)
  ├─ 3 軸ステータス: progress (draft→pending_shipment→shipped→receiving→received / canceled)
  │     / approval (none/pending_request/pending/approved/rejected)
  │     / modification_request (none/requested/completed。requested は receiving 限定)
  ├─ origin/destination_kind (mfc_self/smaregi_store/shopify/other = 在庫効果の分岐ヒント)
  ├─ identification_no (伝票番号) / smaregi_shipping_id / shopify_inventory_transfer_gid (チャネル外部ID)
  ├─ UNIQUE (shop, idempotency_key) 冪等 / (shop, smaregi_shipping_id) / (shop, shopify_inventory_transfer_gid)
  ├─ CHECK: 自己移動禁止 / requested は receiving のみ / shipped は承認前(pending_request)不可
  │  ★実数量が動くのは自己在庫(source_system='mfc_inventory_ingest')の拠点のみ (ship/receive で棚± + recompute)
  │
  ├──< sot.lm_stock_transfer_lines (明細 = barcode × 数量)
  │     ├─ request/quantity(計画)/shipped/received_accepted/received_rejected_quantity
  │     ├─ origin/destination_shelf_code / shelf_ship_applied_qty / shelf_receive_applied_qty (棚±冪等マーカー)
  │     ├─ UNIQUE (stock_transfer_id, barcode) / (stock_transfer_id, line_no)
  │     └─ CHECK: shipped_quantity <= quantity (計画超の出庫を全 writer で禁止=売越防止)
  │            / received_accepted + received_rejected <= shipped_quantity
  │
  ├──< sot.lm_stock_transfer_modification_requests (入庫検品中の修正依頼)
  │     └─ status: requested/completed/deleted / lines_snapshot / active(requested) は partial unique 1 件
  │
  └──< sot.lm_stock_transfer_shelf_logs (移動が自己在庫棚を±した attribution 追記ログ)
        └─ reason: ship_out(出庫元−) / receive_in(入庫先+) / delta(<>0) / location_id / shelf_code
              (棚在庫ログ本体 lm_shelf_inventory_logs とは別 = 単一真実源を破らない)
  read view: agent_read.lm_stock_transfers (shopify_phase 派生 + line_count/total_quantity/received_quantity・PII なし)
           / agent_read.lm_stock_transfer_lines (barcode→products で sku/商品名付与)

sot.lm_shipment_memos (出荷メモ = shipment 単位の手書きメモ・追記のみ/監査ログ)
  ├─ shipment_id ──> sot.lm_fulfillment_shipments(id) (ON DELETE CASCADE)
  ├─ body (自由記述) / author_user_id / author_email (PII 相当 = service_role only・agent_read 非公開)
  └─ created_at のみ (追記のみ = updated_at なし) / INDEX (shop, shipment_id, created_at DESC)

sot.lm_share_analytics_shares / _items / _events (店舗→EC送客 = 共有・共有商品・追跡イベント)
  ├─ 冪等 upsert キー: UNIQUE (source, source_share_id / source_item_id / source_event_id)
  ├─ PII は hash 列のみ (source_share_token_hash / staff_email_hash / line_user_hash / customer_hash)。
  │     raw トークン・メール・LINE id・顧客 id は保存しない。order_id_reference のみ internal-only raw
  ├─ events.event_type CHECK: opened / line_pushed / line_liff_opened / product_click / add_to_cart / purchased
  └─ FK なし (イベント先行着弾を許容) / service_role only・agent_read 非公開

sot.lm_fulfillment_status_webhook_config (出荷元ステータス変動 webhook 送信設定)
  └─ UNIQUE NULLS NOT DISTINCT (shop, source_system)。source_system NULL = 既定宛先
        / auth_secret_encrypted = pgcrypto暗号化 (鍵=Vault, dispatch と共有)
sot.lm_fulfillment_status_events (status 遷移イベント outbox + 送信ログ / secret なし)
  └─ status_before → status_after / tracking_number / delivery_status: pending / sent / failed / skipped
        起票元 = lm_fulfillment_shipments.status の遷移 (routing-fulfillment が emit)

sot.lm_routing_allocation_webhook_config (引き当て暫定確定 webhook 送信設定)
  └─ UNIQUE (shop) / auth_secret_encrypted = pgcrypto暗号化 (鍵=Vault, dispatch と共有)
sot.lm_routing_allocation_events (引き当て結果イベント outbox + 送信ログ / secret なし)
  └─ allocation_status: allocated / unallocated + lines snapshot (barcode×properties 単位
        + sku/productName 同梱。properties は PII になり得るため公開 view では除去)
        起票元 = routing 完了時の出荷指示 (routing-orders が emit)
sot.lm_routing_cancel_events (確保前キャンセルイベント outbox + 送信ログ / secret・明細なし)
  └─ shipment_id 中心 (受信側の冪等キー) / 送信設定は lm_routing_allocation_webhook_config を再利用
        起票元 = 確保前 (secured_at IS NULL)・未出荷の shipment キャンセル (routing-cancel が emit)

sot.lm_oversell_status_webhook_config (売越しケース受付完了 webhook 送信設定)
  └─ UNIQUE (shop) / auth_secret_encrypted = pgcrypto暗号化 (鍵=Vault, dispatch と共有)
sot.lm_oversell_status_events (ケース受付完了イベント outbox + 送信ログ / secret なし)
  └─ status = warehouse_received のみ / found_location_id + lines snapshot (barcode 単位
        + sku/productName 同梱・quantity=1) / UNIQUE (oversell_case_id) で二重発行防止
        起票元 = lm_oversell_cases.status が warehouse_received へ遷移 (routing-oversell-case が emit)

sot.lm_order_update_webhook_config (受注情報更新 webhook 送信設定)
  └─ UNIQUE (shop) / auth_secret_encrypted = pgcrypto暗号化 (鍵=Vault, dispatch と共有)
sot.lm_order_update_events (受注更新イベント outbox + 送信ログ / secret なし)
  └─ change_type = address_corrected のみ (将来種別追加) / 修正後 ship_to snapshot (PII)
        + corrected_at / corrected_by / UNIQUE なし (1 修正 = 1 event)
        起票元 = lm_routing_orders.ship_to_* が /api/routing/shipment/address で更新 (routing-shipment-address が emit)
        ship_to (住所) は PII のため公開 read view を作らず service_role only

read view: lm_v_fulfillment_shipments / lm_v_fulfillment_units / lm_v_oversell_cases
          / lm_v_fulfillment_source_changes
          / lm_v_fulfillment_status_webhook_config(secret除外) / lm_v_fulfillment_status_events
          / lm_v_routing_allocation_webhook_config(secret除外) / lm_v_routing_allocation_events(lines の properties・request_payload 除外)
          / lm_v_oversell_status_webhook_config(secret除外) / lm_v_oversell_status_events(request_payload 除外)
          / lm_v_routing_order_fulfillment(ヘッダ粒度) / lm_v_routing_order_unit_fulfillment(単位粒度)

sot.lm_picking_lists (ピッキングリスト生成ログ / append-only)
  └─ routing_order_id FK → lm_routing_orders.id / format / pdf_url(Storage) / payload(jsonb)
        + 集計 location_count / item_kinds / total_quantity / unpickable_count / generated_at
        PDF は Storage bucket "picking-lists" (public read) に保存

sot.lm_shelf_links (棚コード ↔ fulfillment shipment 紐付け)
  ├─ location_id FK → locations.id / fulfillment_shipment_id FK → lm_fulfillment_shipments.id
  ├─ shelf_code (CHECK ^[A-Z0-9]+(-[A-Z0-9]+)+$ + 英字必須 + 32 文字以内)
  ├─ linked_by / linked_at / released_at / released_reason(shipped|manual_release|cancelled|source_changed)
  │     解除は DELETE せず released_at を埋める (行自体が履歴)
  └─ partial unique index (released_at IS NULL): 同一棚 1 shipment / 同一 shipment 1 棚

sot.lm_shelf_inventory (棚在庫 / qty 集約)
  ├─ UNIQUE (shop, location_id, shelf_code, barcode) / qty >= 0
  ├─ 商品参照は barcode のみ (Shopify 非依存)。同一棚に複数 barcode 不可
  ├─ MFC 入庫 (/api/ingest/mfc-inventory) は (barcode × shelf_code) を mode=absolute(絶対値 set)
  │     または mode=adjust(符号付き差分加減算) で反映し、同一トランザクションで barcode を全棚合算して
  │     inventory_levels.available_qty を更新 (棚番号は MFC 引き当て時の Star ラベル印字に使用)
  └─ /api/operator/shelf/pick の pick (picked_at 確定) で対象棚 qty を -1 (reason=pick) / unpick で +1
        (reason=receive)、続けて available_qty を再計算 (LM-769。自己在庫 MFC のみ。出荷前に物理棚を実態へ)
sot.lm_shelf_inventory_logs (棚在庫 増減ログ / append-only)
  └─ delta (<>0) / qty_after (>=0) / reason(receive|pick|adjust|oversell_receive|stocktake|relocate|condition_move) / operator / condition_code (NULL=良品) / stocktake_session_id

sot.lm_shelves (棚マスタ。LM-2466)
  ├─ UNIQUE (shop, location_id, shelf_code) / zone (売場 / バックヤードなどの区分) / is_active
  └─ 棚在庫・状態別在庫に新しい棚が現れると AFTER INSERT トリガーで自動登録 (既存の入庫・集荷は登録を要求しない)

sot.lm_shelf_condition_stock (棚 × barcode × 商品状態の数。良品以外だけ。LM-2466)
  ├─ UNIQUE (shop, location_id, shelf_code, barcode, condition_code) / qty > 0 / FK (shop, condition_code) → inventory_condition_codes
  ├─ 良品 (shop の既定 condition) は lm_shelf_inventory。ここの数は販売可能数に入らない (引当対象外)
  └─ 増減は lm_shelf_condition_move が lm_shelf_inventory_logs に condition_code 付きで記録 (reason=condition_move)

read view: lm_v_shelf_links / lm_v_shelf_inventory (内部 service / 管理用途。agent_read 非露出)

sot.lm_operator_staff_shops (倉庫スタッフ ↔ shop の operator API 認可束縛)
  ├─ staff_user_id (ユーザー) / shop (lower(btrim) 正規化) / is_active / UNIQUE (staff_user_id, shop)
  └─ /api/operator/* の shop 認可 SoT。失効は論理 (is_active=false / revoked_at)
        staff_email 等の個人情報を含むため service_role 限定・agent_read / 公開 view 非露出
        束縛の bind/unbind は内部管理のみ (公開 API ではない)
        アカウント削除 (POST /api/operator/account/delete) 時はユーザー削除に連動して解除

sot.lm_operator_account_deletions (本人アカウント削除の監査トレイル)
  ├─ staff_user_id (削除したユーザー。auth.users への FK なし=削除後も保持する snapshot)
  ├─ staff_email (削除時点のメール snapshot) / shops (束縛 shop snapshot) / source
  └─ requested_at / deleted_at。staff_email は個人情報のため service_role 限定・agent_read / 公開 view 非露出

sot.lm_apps (LMile ホスト型ミニアプリ registry)
  ├─ app_key UNIQUE / shop 束縛 / status / machine_id(実行環境) / manifest(購読・必要env宣言)
  │
  ├──< sot.lm_app_subscriptions (イベント購読 / UNIQUE (app_id, event_type))
  │
  ├──< sot.lm_app_deliveries (アプリ向けイベント配信 outbox + 送信ログ)
  │     └─ UNIQUE (app_id, idempotency_key) / event_payload は PII 除去済 snapshot
  │           delivery_status: pending / sent / failed / skipped (+ dead_letter)
  │
  └──< sot.lm_app_executions (handler 実行ログ / append-only)
        └─ status: ok / error / timeout + duration_ms / log_excerpt / actions_called

read view: lm_v_apps(token除外) / lm_v_app_subscriptions
          / lm_v_app_deliveries(event_payload の properties・shipTo 除去) / lm_v_app_executions
```

## テーブル一覧

| Schema | Table                                     | Description                                                                                                                                                                                                                                                          |
| ------ | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sot`  | `products`                                | 商品マスター（1 row = 1 barcode）                                                                                                                                                                                                                                            |
| `sot`  | `product_identifiers`                     | 商品識別子（shopify\_variant\_id 等）                                                                                                                                                                                                                                        |
| `sot`  | `product_update_logs`                     | 商品変更ログ（created / updated）                                                                                                                                                                                                                                            |
| `sot`  | `inventory_levels`                        | 在庫マスター（1 row = 1 商品 × 1 拠点・`available_qty` は取り置きを引いた後の値）                                                                                                                                                                                                             |
| `sot`  | `lm_inventory_holds`                      | 在庫の取り置き台帳（`UNIQUE (shop, reference_id, location_id, product_id)`・`quantity > 0`・解除した行は削除・合計が `inventory_levels.held_qty`）                                                                                                                                            |
| `sot`  | `inventory_update_logs`                   | 在庫変更ログ                                                                                                                                                                                                                                                               |
| `sot`  | `lm_visit_reservations`                   | 来店予約（1 行 = 1 予約・`status` / `visit_status`）                                                                                                                                                                                                                           |
| `sot`  | `lm_visit_events`                         | 来店予約の履歴（来店の記録は `visit_changed`）                                                                                                                                                                                                                                      |
| `sot`  | `lm_stocktake_sessions`                   | 棚卸セッション（拠点ごとに進行中 1 つ・`status`: `counting` → `submitted` → `committed` / `cancelled`・`mode`: `shelf` / `location`）                                                                                                                                                    |
| `sot`  | `lm_stocktake_shelves`                    | セッションの中で数える棚（`counting` / `closed`・`started_at`・`movement_detected`・`recount_no`）                                                                                                                                                                                    |
| `sot`  | `lm_shelves`                              | 棚マスタ（`UNIQUE (shop, location_id, shelf_code)`・`zone`・`is_active`）                                                                                                                                                                                                    |
| `sot`  | `lm_shelf_condition_stock`                | 棚 × barcode × 商品状態の数（良品以外だけ・販売可能数に入らない）                                                                                                                                                                                                                              |
| `sot`  | `lm_stocktake_counts`                     | 棚卸の計数（棚 × 商品 × 状態・`counted_qty` / `expected_qty` / `superseded_at` / `applied_at` / `apply_error_kind`）                                                                                                                                                              |
| `sot`  | `lm_stocktake_location_lines`             | 拠点全体の棚卸（店舗）の商品ごとの行（提出で固定・`expected_qty` = 生の在庫数 + 引き当て済み未確保・`movement_detected`・`write_back`）                                                                                                                                                                        |
| `sot`  | `lm_inventory_external_adjustments`       | 外部システム（スマレジ / Shopify）へ当てる在庫の差分（相対値・`status`: `pending` → `claimed` → `applied` / `failed` / `unknown`）                                                                                                                                                              |
| `sot`  | `inventory_condition_codes`               | 商品状態のマスタ（`PK (shop, code)`・`is_default` = 良品・`allocatable_default` は表示メタ。A/B/C/UNKNOWN。良品以外の数は `lm_shelf_condition_stock`）                                                                                                                                           |
| `sot`  | `inventory_ledger`                        | 取り置きの履歴 append-only（`event_type` = `hold` / `release`・`idempotency_key` 指定時一意・真実源ではない）                                                                                                                                                                               |
| `sot`  | `locations`                               | 拠点マスター                                                                                                                                                                                                                                                               |
| `sot`  | `location_identifiers`                    | 拠点識別子                                                                                                                                                                                                                                                                |
| `sot`  | `customers`                               | 顧客マスター                                                                                                                                                                                                                                                               |
| `sot`  | `customer_identifiers`                    | 顧客識別子                                                                                                                                                                                                                                                                |
| `sot`  | `order_line_master`                       | 受注（1 row = 1 販売単位）                                                                                                                                                                                                                                                   |
| `sot`  | `order_line_master_update_logs`           | 受注変更ログ                                                                                                                                                                                                                                                               |
| `sot`  | `lm_customers`                            | 顧客（メールごとに 1 人。注文・来店・受信メール・Shopify の顧客から作る。受注明細の取引は `order_line_master.lm_customer_id` で結び付く）                                                                                                                                                                         |
| `sot`  | `lm_customer_shopify_links`               | 顧客 ↔ Shopify の顧客（`PK (shopify_shop, shopify_customer_id)`・順序ガード `shopify_updated_at`・顧客の削除で消える）                                                                                                                                                                      |
| `sot`  | `lm_fulfillment_source_members`           | 出荷元 → 在庫ロケーション 紐付け（1:N）                                                                                                                                                                                                                                              |
| `sot`  | `lm_fulfillment_source_webhook_config`    | 出荷元の合算在庫変動 webhook 送信設定（出荷元単位・secret 暗号化）                                                                                                                                                                                                                            |
| `sot`  | `lm_fulfillment_source_inventory_state`   | 出荷元×product ごとの前回送信した合算値（dedup）                                                                                                                                                                                                                                      |
| `sot`  | `lm_fulfillment_source_inventory_events`  | 合算在庫変動イベント outbox + 送信ログ（secret なし）                                                                                                                                                                                                                                  |
| `sot`  | `lm_routing_orders`                       | 受注ルーティングの注文ヘッダ（routing-native）                                                                                                                                                                                                                                       |
| `sot`  | `lm_routing_order_ship_to_changes`        | 宛先住所・氏名の変更履歴（append-only・before/after・PII・service\_role 専用）                                                                                                                                                                                                          |
| `sot`  | `lm_routing_decisions`                    | ルーティング判定結果（unit 単位）                                                                                                                                                                                                                                                  |
| `sot`  | `lm_routing_candidates`                   | ルーティング候補スコア snapshot                                                                                                                                                                                                                                                 |
| `sot`  | `lm_shipping_instructions`                | 出荷指示 dispatch ログ                                                                                                                                                                                                                                                     |
| `sot`  | `lm_routing_allocation_webhook_config`    | 引き当て暫定確定 webhook 送信設定（shop 単位・secret 暗号化）                                                                                                                                                                                                                            |
| `sot`  | `lm_routing_allocation_events`            | 引き当て結果イベント outbox + 送信ログ（lines snapshot・secret なし）                                                                                                                                                                                                                   |
| `sot`  | `lm_location_dispatch_config`             | WMS ディスパッチ設定（在庫ロケ単位・secret 暗号化）                                                                                                                                                                                                                                      |
| `sot`  | `lm_location_dispatch_log`                | WMS 送信ログ（secret なし）                                                                                                                                                                                                                                                  |
| `sot`  | `lm_wms_shipping_requests`                | WMS 出荷指示 SHIPPING\_REQUEST の送信記録（payload は PII を含むため view 非公開）                                                                                                                                                                                                       |
| `sot`  | `lm_location_star_printers`               | 在庫ロケーション → Star プリンター device ID 紐付け（1:1）                                                                                                                                                                                                                             |
| `sot`  | `lm_fulfillment_shipments`                | 出荷元ヘッダ（注文 × from\_location・追跡番号/ラベルPDF/status・外部フルフィルメント受理マーカー `external_fulfillment_id`）                                                                                                                                                                            |
| `sot`  | `lm_external_sku_mappings`                | 外部システム SKU ↔ barcode の明示マッピング（`UNIQUE (shop, system, external_sku)`・`is_active`・人間レビュー済みの登録のみ）                                                                                                                                                                       |
| `sot`  | `lm_fulfillment_status_webhook_config`    | 出荷ステータス変動 webhook 送信設定（shop × 取込元単位・`source_system` NULL = 既定宛先・secret 暗号化）                                                                                                                                                                                          |
| `sot`  | `lm_fulfillment_status_events`            | 出荷ステータス遷移イベント outbox + 送信ログ（secret なし）                                                                                                                                                                                                                               |
| `sot`  | `lm_fulfillment_units`                    | 単位フルフィルメント明細（1 row = 1 販売単位）                                                                                                                                                                                                                                         |
| `sot`  | `lm_shipment_memos`                       | 出荷（shipment）単位の手書きメモ（追記のみ = 監査ログ・`body`/投稿者は PII 相当で service\_role only / agent\_read 非露出）                                                                                                                                                                           |
| `sot`  | `lm_share_analytics_shares`               | 店舗→EC送客の共有（1 共有 = 1 行・トークン/スタッフメールは hash 列のみ・`UNIQUE source+source_share_id`・service\_role only / agent\_read 非露出）                                                                                                                                                   |
| `sot`  | `lm_share_analytics_items`                | 送客共有の商品スナップショット（`UNIQUE source+source_item_id`）                                                                                                                                                                                                                      |
| `sot`  | `lm_share_analytics_events`               | 送客の追跡イベント（開封/LINE push/LIFF 開封/商品クリック/カート追加/購入。PII は hash 化・`order_id_reference` は internal-only）                                                                                                                                                                    |
| `sot`  | `lm_oversell_cases`                       | 売越しケース（8 ステップ + wont\_do）                                                                                                                                                                                                                                            |
| `sot`  | `lm_oversell_status_webhook_config`       | 売越しケース受付完了 webhook 送信設定（shop 単位・secret 暗号化）                                                                                                                                                                                                                          |
| `sot`  | `lm_oversell_status_events`               | ケース受付完了イベント outbox + 送信ログ（lines snapshot・secret なし・`UNIQUE (oversell_case_id)`）                                                                                                                                                                                      |
| `sot`  | `lm_order_update_webhook_config`          | 受注情報更新 webhook 送信設定（shop 単位・secret 暗号化）                                                                                                                                                                                                                              |
| `sot`  | `lm_order_update_events`                  | 受注更新イベント outbox + 送信ログ（修正後 `ship_to` snapshot＝PII を含み service\_role only / 公開 view 非露出・`UNIQUE` なし）                                                                                                                                                                  |
| `sot`  | `lm_picking_lists`                        | ピッキングリスト生成ログ（append-only / PDF は Storage bucket `picking-lists`）                                                                                                                                                                                                     |
| `sot`  | `lm_shelf_links`                          | 棚コード ↔ fulfillment shipment 紐付け（アクティブ一意性は partial unique index / 解除は `released_at`）                                                                                                                                                                                  |
| `sot`  | `lm_shelf_inventory`                      | 棚在庫（qty 集約・`UNIQUE shop+location+shelf_code+barcode`・商品参照は barcode のみ・MFC 入庫は棚別 `mode=absolute`(絶対値 set) / `adjust`(差分) ＋ `inventory_levels` への barcode 集約 rollup）                                                                                                   |
| `sot`  | `lm_shelf_inventory_logs`                 | 棚在庫の増減ログ（append-only / `delta` / `qty_after` / `reason` / `operator`）                                                                                                                                                                                                |
| `sot`  | `lm_operator_staff_shops`                 | 倉庫スタッフ ↔ shop の operator API 認可束縛（`UNIQUE (staff_user_id, shop)`・失効は `is_active`・PII を含み service\_role only / agent\_read 非露出）                                                                                                                                       |
| `sot`  | `lm_operator_account_deletions`           | 本人アカウント削除（`/api/operator/account/delete`）の監査トレイル（`staff_user_id` は FK なしの snapshot・`staff_email` PII を含み service\_role only / agent\_read 非露出）                                                                                                                       |
| `sot`  | `lm_fulfillment_source_changes`           | 出荷元変更 + 返送レグ（旧/新 出荷元・在庫・返送追跡番号/ラベル・`batch_id` = 倉庫間移動バルク所属）                                                                                                                                                                                                          |
| `sot`  | `lm_transfer_batches`                     | 拠点間移動バルク（`kind`: `return` = 返送 / `inbound` = 出荷元への入荷転送。`open` → `dispatched` → `received`・配送状況スナップショット・内容物リスト PDF パス・作成者 snapshot。read は `agent_read.lm_transfer_batches` / `lm_transfer_batch_units` safe view）                                                     |
| `sot`  | `lm_carrier_pickups`                      | キャリア集荷依頼（オンコールピックアップ）1 回分のヘッダ（`prn` = 受付番号・集荷日・時間帯 `HHmm`・宛先国ごとの個口内訳 `pieces`・総重量・依頼者 snapshot。`status`: `pending`（キャリア問い合わせ前の予約）→ `requested` / `failed`・取消は `cancelled`。メンバーは `lm_fulfillment_shipments.pickup_id`）                                                |
| `sot`  | `lm_stock_transfers`                      | 拠点間 在庫移動ヘッダ（商品×数量の location→location 移動。3 軸ステータス `progress`/`approval`/`modification_request`・`UNIQUE (shop, idempotency_key)` 冪等・実数量は自己在庫のみ棚±で反映。**返送バルク `lm_transfer_batches` とは別物**。read は `agent_read.lm_stock_transfers`）                                       |
| `sot`  | `lm_stock_transfer_lines`                 | 在庫移動明細（`barcode` × 数量 request/quantity/shipped/received accepted/rejected・`UNIQUE (stock_transfer_id, barcode)`・CHECK `shipped_quantity <= quantity`（売越防止）/ `received_accepted + received_rejected <= shipped_quantity`。read は `agent_read.lm_stock_transfer_lines`） |
| `sot`  | `lm_stock_transfer_modification_requests` | 在庫移動の出庫内容 修正依頼（入庫検品中のみ・`status`: `requested`/`completed`/`deleted`・active は partial unique 1 件・明細スナップショット）                                                                                                                                                           |
| `sot`  | `lm_stock_transfer_shelf_logs`            | 在庫移動が自己在庫棚を ± した attribution 追記ログ（`reason`: `ship_out`/`receive_in`。棚在庫ログ本体とは別）                                                                                                                                                                                      |
| `sot`  | `lm_apps`                                 | LMile ホスト型ミニアプリ registry（shop 束縛・manifest）                                                                                                                                                                                                                           |
| `sot`  | `lm_app_subscriptions`                    | アプリのイベント購読                                                                                                                                                                                                                                                           |
| `sot`  | `lm_app_deliveries`                       | アプリ向けイベント配信 outbox + 送信ログ（PII 除去済 snapshot）                                                                                                                                                                                                                          |
| `sot`  | `lm_app_executions`                       | アプリ handler 実行ログ（ok / error / timeout）                                                                                                                                                                                                                               |

read は `agent_read.*` の safe view 経由（`products` / `inventory_levels` / `inventory_update_logs` / `product_update_logs` / `order_line_master` / `stocktake_sessions` / `stocktake_counts` / `inventory_condition_codes` / `inventory_ledger` / `shelf_stock` / `shelves` / `stocktake_shelves` / `stocktake_location_lines` / `inventory_external_adjustments`）。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://lmile.gitbook.io/lmile-docs/reference/data-model.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
