Spaces:
Running

File size: 9,712 Bytes
0776bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""Phase 8 (Pakistan COD suite) tables. Migration ``0006_cod_suite``; FORCE RLS on all.



* ``ecom_rto_scores``: every RTO risk score computed for an order (history). The latest one

  is denormalized onto ``ecom_orders.risk_score/risk_band/risk_reasons``.

* ``ecom_cod_confirmations``: one row per confirmation attempt (the COD confirmation state

  machine). ``status``: ``pending`` (waiting for the customer) -> ``confirmed`` |

  ``rejected`` | ``no_answer`` (deadline passed) | ``superseded``.

* ``ecom_courier_accounts``: per-tenant courier configuration. ``config`` holds non-secret

  ids only (merchant/pickup codes, base URL override); ``secret_ref`` names a secret resolved

  from ``WP_SECRET_<REF>`` at call time (``core.channels.secrets``), never stored here.

* ``ecom_cod_remittances`` / ``ecom_cod_remittance_lines``: imported courier remittance

  statements (CSV upload or courier API), one line per parcel.

* ``ecom_cod_recon_issues``: reconciliation findings (mismatches, missing remittances),

  upserted by ``ecommerce.reconcile_cod``; ``status`` open | resolved.

"""

from __future__ import annotations

import uuid
from datetime import date, datetime
from typing import Any

from sqlalchemy import (
    Boolean,
    Date,
    DateTime,
    Float,
    ForeignKey,
    Integer,
    String,
    UniqueConstraint,
    func,
)
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column

from core.db.base import Base, TenantMixin, new_id

RISK_BANDS = ("low", "medium", "high")
CONFIRMATION_ATTEMPT_STATUSES = ("pending", "confirmed", "rejected", "no_answer", "superseded")
DECISIONS = ("CONFIRM", "CANCEL", "ADDRESS_CHANGE", "UNCLEAR")
RECON_KINDS = (
    "amount_mismatch",  # remitted amount differs from the shipment's COD amount
    "missing_remittance",  # delivered COD parcel, no remittance after the grace period
    "remitted_not_delivered",  # remitted, but our shipment is not delivered
    "unknown_tracking",  # remittance line for a tracking number we do not know
    "duplicate_remittance",  # the same parcel remitted in two statements
)
MATCH_STATUSES = (
    "matched",
    "amount_mismatch",
    "not_delivered",
    "unknown_tracking",
    "duplicate",
)

COD_TABLES = (
    "ecom_rto_scores",
    "ecom_cod_confirmations",
    "ecom_courier_accounts",
    "ecom_cod_remittances",
    "ecom_cod_remittance_lines",
    "ecom_cod_recon_issues",
)


def _ts(nullable: bool = False) -> Any:
    if nullable:
        return mapped_column(DateTime(timezone=True), nullable=True)
    return mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)


def _pk() -> Any:
    return mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id)


def _order_fk() -> Any:
    return mapped_column(
        UUID(as_uuid=True), ForeignKey("ecom_orders.id", ondelete="CASCADE"), index=True
    )


class RtoScore(TenantMixin, Base):
    __tablename__ = "ecom_rto_scores"

    id: Mapped[uuid.UUID] = _pk()
    order_id: Mapped[uuid.UUID] = _order_fk()
    score: Mapped[float] = mapped_column(Float, nullable=False)  # calibrated P(RTO)
    band: Mapped[str] = mapped_column(String(10), nullable=False)
    # [{"feature", "value", "contribution", "text"}], top contributors (TreeSHAP)
    reasons: Mapped[list[dict[str, Any]]] = mapped_column(JSONB, nullable=False, default=list)
    model_version: Mapped[str] = mapped_column(String(64), nullable=False)
    features: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict)
    stage: Mapped[str] = mapped_column(String(20), nullable=False, default="created")
    created_at: Mapped[datetime] = _ts()


class CodConfirmation(TenantMixin, Base):
    __tablename__ = "ecom_cod_confirmations"

    id: Mapped[uuid.UUID] = _pk()
    order_id: Mapped[uuid.UUID] = _order_fk()
    attempt: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
    channel: Mapped[str] = mapped_column(String(12), nullable=False)  # whatsapp|auto|manual
    band: Mapped[str | None] = mapped_column(String(10), nullable=True)
    status: Mapped[str] = mapped_column(String(12), nullable=False, default="pending")
    phone: Mapped[str | None] = mapped_column(String(20), nullable=True, index=True)  # on file
    message_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
    reply_message_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
    decision: Mapped[str | None] = mapped_column(String(16), nullable=True)
    decision_source: Mapped[str | None] = mapped_column(String(20), nullable=True)
    payment_link: Mapped[dict[str, Any] | None] = mapped_column(JSONB, nullable=True)
    deadline_at: Mapped[datetime | None] = _ts(nullable=True)
    resolved_at: Mapped[datetime | None] = _ts(nullable=True)
    created_at: Mapped[datetime] = _ts()


class CourierAccount(TenantMixin, Base):
    __tablename__ = "ecom_courier_accounts"
    __table_args__ = (
        UniqueConstraint("tenant_id", "courier", name="uq_ecom_courier_accounts_courier"),
    )

    id: Mapped[uuid.UUID] = _pk()
    courier: Mapped[str] = mapped_column(String(20), nullable=False)  # postex|leopards|tcs|mp|mock
    enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    is_default: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    # Feature flag for adapters built without official docs (see connectors/couriers).
    allow_unverified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    config: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict)
    secret_ref: Mapped[str | None] = mapped_column(String(120), nullable=True)
    created_at: Mapped[datetime] = _ts()
    updated_at: Mapped[datetime] = _ts()


class CodRemittance(TenantMixin, Base):
    __tablename__ = "ecom_cod_remittances"
    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "courier", "statement_ref", name="uq_ecom_cod_remittances_statement"
        ),
    )

    id: Mapped[uuid.UUID] = _pk()
    courier: Mapped[str] = mapped_column(String(20), nullable=False)
    statement_ref: Mapped[str] = mapped_column(String(100), nullable=False)
    source: Mapped[str] = mapped_column(String(10), nullable=False)  # csv|api
    period_start: Mapped[date | None] = mapped_column(Date, nullable=True)
    period_end: Mapped[date | None] = mapped_column(Date, nullable=True)
    line_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    total_cod: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    total_fees: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    total_net: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    imported_by: Mapped[str] = mapped_column(String(120), nullable=False, default="")
    imported_at: Mapped[datetime] = _ts()


class CodRemittanceLine(TenantMixin, Base):
    __tablename__ = "ecom_cod_remittance_lines"

    id: Mapped[uuid.UUID] = _pk()
    remittance_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("ecom_cod_remittances.id", ondelete="CASCADE"), index=True
    )
    tracking_number: Mapped[str] = mapped_column(String(60), nullable=False, index=True)
    order_ref: Mapped[str | None] = mapped_column(String(40), nullable=True)
    cod_amount: Mapped[int] = mapped_column(Integer, nullable=False)  # collected from customer
    fee: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    net_amount: Mapped[int] = mapped_column(Integer, nullable=False)  # paid to the merchant
    delivered_on: Mapped[date | None] = mapped_column(Date, nullable=True)
    shipment_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("ecom_shipments.id", ondelete="SET NULL"), index=True
    )
    match_status: Mapped[str] = mapped_column(String(20), nullable=False)
    created_at: Mapped[datetime] = _ts()


class CodReconIssue(TenantMixin, Base):
    __tablename__ = "ecom_cod_recon_issues"
    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "kind", "tracking_number", name="uq_ecom_cod_recon_issues_kind_tracking"
        ),
    )

    id: Mapped[uuid.UUID] = _pk()
    kind: Mapped[str] = mapped_column(String(30), nullable=False)
    tracking_number: Mapped[str] = mapped_column(String(60), nullable=False)
    courier: Mapped[str | None] = mapped_column(String(40), nullable=True)
    shipment_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("ecom_shipments.id", ondelete="SET NULL"), index=True
    )
    line_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("ecom_cod_remittance_lines.id", ondelete="SET NULL"),
        index=True,
    )
    order_number: Mapped[str | None] = mapped_column(String(40), nullable=True)
    expected_amount: Mapped[int | None] = mapped_column(Integer, nullable=True)
    remitted_amount: Mapped[int | None] = mapped_column(Integer, nullable=True)
    difference: Mapped[int | None] = mapped_column(Integer, nullable=True)
    days_outstanding: Mapped[int | None] = mapped_column(Integer, nullable=True)
    detail: Mapped[str] = mapped_column(String(300), nullable=False, default="")
    status: Mapped[str] = mapped_column(String(12), nullable=False, default="open")
    created_at: Mapped[datetime] = _ts()
    updated_at: Mapped[datetime] = _ts()
    resolved_at: Mapped[datetime | None] = _ts(nullable=True)