Compare commits
10
Commits
19d490e790
...
8c5d971d1f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c5d971d1f | ||
|
|
92831ed33e | ||
|
|
be5ca829d2 | ||
|
|
7019cad932 | ||
|
|
3ac9e92e9f | ||
|
|
5bacade748 | ||
|
|
4d3b15c3b9 | ||
|
|
884413513d | ||
|
|
e020e6a633 | ||
|
|
45633b5aa0 |
@@ -15,3 +15,7 @@ apps/api/storage/uploads/*
|
||||
# apps/api/release/app.js + apps/api/release/vendor/ (Prisma)
|
||||
# apps/admin-panel/dist/
|
||||
# apps/user-app/dist/
|
||||
|
||||
# Live henza data dump (customers' personal data). Never commit.
|
||||
# Only the structure-only oapi-struncture.sql belongs in the repo.
|
||||
/oapi.sql
|
||||
|
||||
@@ -127,7 +127,12 @@
|
||||
class="cursor-pointer w-5 ml-1"
|
||||
:class="stepIconClass(getStepOneIcon(record))"
|
||||
/>
|
||||
<div>{{ getStepOneText(record) }}</div>
|
||||
<div>
|
||||
<div>{{ getStepOneText(record) }}</div>
|
||||
<div v-if="record.verificationStep === 'REJECTED'" class="text-danger text-xs">
|
||||
رد شده{{ record.verification_rejection_reason ? `: ${record.verification_rejection_reason}` : '' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a-popconfirm>
|
||||
</a-menu-item>
|
||||
@@ -213,6 +218,26 @@
|
||||
</template>
|
||||
</XTable>
|
||||
|
||||
<!-- Reject = REJECTED with an optional reason (owner ruling 2026-10-07). -->
|
||||
<a-modal
|
||||
:open="rejectDialog.open"
|
||||
title="رد مدارک مشتری"
|
||||
ok-text="ثبت رد"
|
||||
cancel-text="انصراف"
|
||||
:ok-button-props="{ danger: true }"
|
||||
:confirm-loading="rejectDialog.saving"
|
||||
@ok="submitReject"
|
||||
@cancel="rejectDialog.open = false"
|
||||
>
|
||||
<p>دلیل رد (اختیاری) — در پروندهی مشتری ثبت میشود.</p>
|
||||
<a-textarea
|
||||
v-model:value="rejectDialog.reason"
|
||||
:rows="3"
|
||||
:maxlength="500"
|
||||
placeholder="مثلاً: تصویر کارت ملی خوانا نیست"
|
||||
/>
|
||||
</a-modal>
|
||||
|
||||
<BulkCustomer
|
||||
v-if="showAddButton"
|
||||
:key="editingId ?? 'new'"
|
||||
@@ -365,12 +390,38 @@ async function postVerify(payload: Record<string, unknown>, errorMsg: string) {
|
||||
|
||||
const acceptStepOne = (id: string) =>
|
||||
postVerify({ customer_id: id, sts_verify_step_one: 2 }, 'خطا در تغییر وضعیت اولیه مشتری');
|
||||
const rejectStepOne = (id: string) =>
|
||||
postVerify({ customer_id: id, sts_verify_step_one: 3 }, 'خطا در تغییر وضعیت اولیه مشتری');
|
||||
const rejectStepOne = (id: string) => openReject(id, 'sts_verify_step_one');
|
||||
const acceptStepTwo = (id: string) =>
|
||||
postVerify({ customer_id: id, sts_verify_step_two: 2 }, 'خطا در تغییر وضعیت سفارش مشتری');
|
||||
const rejectStepTwo = (id: string) =>
|
||||
postVerify({ customer_id: id, sts_verify_step_two: 3 }, 'خطا در تغییر وضعیت سفارش مشتری');
|
||||
const rejectStepTwo = (id: string) => openReject(id, 'sts_verify_step_two');
|
||||
|
||||
/**
|
||||
* A reject asks for an optional reason first; the customer is then stored as
|
||||
* REJECTED with it (admin-customers.service.ts verify()).
|
||||
*/
|
||||
type VerifyStep = 'sts_verify_step_one' | 'sts_verify_step_two';
|
||||
const rejectDialog = ref<{ open: boolean; saving: boolean; id: string; step: VerifyStep; reason: string }>({
|
||||
open: false,
|
||||
saving: false,
|
||||
id: '',
|
||||
step: 'sts_verify_step_one',
|
||||
reason: '',
|
||||
});
|
||||
|
||||
function openReject(id: string, step: VerifyStep) {
|
||||
rejectDialog.value = { open: true, saving: false, id, step, reason: '' };
|
||||
}
|
||||
|
||||
async function submitReject() {
|
||||
const d = rejectDialog.value;
|
||||
d.saving = true;
|
||||
await postVerify(
|
||||
{ customer_id: d.id, [d.step]: 3, reason: d.reason.trim() || null },
|
||||
d.step === 'sts_verify_step_one' ? 'خطا در تغییر وضعیت اولیه مشتری' : 'خطا در تغییر وضعیت سفارش مشتری',
|
||||
);
|
||||
d.saving = false;
|
||||
d.open = false;
|
||||
}
|
||||
|
||||
/** legacy inline ternary on @confirm, preserved including the NonVerified quirk */
|
||||
function onConfirmStepOne(record: Record<string, any>) {
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
"@types/supertest": "^7.2.1",
|
||||
"esbuild": "^0.25.0",
|
||||
"jest": "^30.5.2",
|
||||
"mysql2": "^3.24.5",
|
||||
"prisma": "^5.19.0",
|
||||
"supertest": "^7.2.2",
|
||||
"ts-jest": "^29.4.12",
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
-- ============================================================================
|
||||
-- Preparation for the legacy data migration — PURELY ADDITIVE.
|
||||
--
|
||||
-- Owner decisions of 2026-10-06 and 2026-10-07, recorded in
|
||||
-- docs/DATA-MIGRATION-MAP.md §5.2, §5.5, §10, §10.4, §10.5.5.
|
||||
--
|
||||
-- Nothing here drops, renames or retypes an existing column. Every statement
|
||||
-- either removes a constraint or adds a new column/table, so code that works
|
||||
-- today keeps working. Verified NOT touched:
|
||||
-- * Customer.accounting{Gold,Rial}Balance / accountingBalanceAt (D27)
|
||||
-- * Product.accountingStock{Weight,Count} / accountingStockAt (D27)
|
||||
-- * ProductVariant.imageId (PROTECTED.md §B)
|
||||
-- * AccountingLink / AccountingOutbox / AccountingIssue
|
||||
-- * SmsMessage and the SMS module
|
||||
-- These are target-only capabilities under PROTECTED.md §G ("a keep-out
|
||||
-- list"), and the owner confirmed on 2026-10-06 that their data is real.
|
||||
--
|
||||
-- D15: idempotent (IF NOT EXISTS / duplicate_object guards) because this runs
|
||||
-- under BOTH ledgers — the Prisma CLI in development and the app's own runner
|
||||
-- (src/prisma/migrate.ts) in the deploy container, which wraps each file in a
|
||||
-- transaction. The runner's splitSqlStatements() handles $$-quoted blocks
|
||||
-- (migrate.ts:83-91), so the DO blocks below are split correctly.
|
||||
-- ============================================================================
|
||||
|
||||
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- 1. Customer.nationalCode becomes OPTIONAL
|
||||
--
|
||||
-- Source reality (docs/migration-precheck.sql, run 2026-10-06 on the live
|
||||
-- `oapi` MySQL schema): empty_ncode = 1595 of n_customers = 1595. NOT ONE of
|
||||
-- the 1,616 legacy customers has a national code. dup_ncode_groups = 0.
|
||||
--
|
||||
-- Owner ruling 2026-10-07: "ساختن کد ملی فیک تخلف دیتایی است و مانع از
|
||||
-- احراز هویتهای قانونی بعدی میشود" — fabricating one is a data violation, so
|
||||
-- the column must be nullable. Without this the customer migration cannot
|
||||
-- insert a single row.
|
||||
--
|
||||
-- This also RETIRES three existing workarounds that only exist because the
|
||||
-- column is required. They write the MOBILE NUMBER into the national-code
|
||||
-- field, i.e. they store wrong data today:
|
||||
-- * admin-customers.service.ts:625 nationalCode: mobile
|
||||
-- comment: "schema requires it and it is unique; singleCustomer.vue
|
||||
-- collects no ncode"
|
||||
-- * admin-customers.service.ts:685 nationalCode: nationalCode || mobile
|
||||
-- * customer-auth.service.ts:258 ... || admin.mobile
|
||||
-- Removing those fallbacks is a SERVICE-LAYER change, deliberately NOT done
|
||||
-- here: this migration only makes it possible. Until they are removed the
|
||||
-- behaviour is exactly as it is today.
|
||||
--
|
||||
-- The UNIQUE index "Customer_nationalCode_key" (first/migration.sql:304) is
|
||||
-- left in place. In PostgreSQL NULLs are not equal to each other, so any
|
||||
-- number of rows may hold NULL under a unique index — which is precisely why
|
||||
-- the migration tool must write NULL and never the empty string: '' would
|
||||
-- collide on the second row (see §10.4).
|
||||
--
|
||||
-- DROP NOT NULL takes only a brief ACCESS EXCLUSIVE lock on the catalog; it
|
||||
-- does not rewrite the table and does not scan the data.
|
||||
ALTER TABLE "Customer" ALTER COLUMN "nationalCode" DROP NOT NULL;
|
||||
|
||||
COMMENT ON COLUMN "Customer"."nationalCode" IS
|
||||
'Legacy customers.ncode. OPTIONAL: no legacy customer has one (1595/1595 empty as of 2026-10-06), and fabricating a value is a data violation (owner, 2026-10-07). Still UNIQUE — write NULL, never '''', because NULLs do not collide under a unique index but empty strings do.';
|
||||
|
||||
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- 2. Customer.birthDate — new, nullable, unread until backfilled
|
||||
--
|
||||
-- Legacy `customers.birth_date timestamp NULL` (oapi dump line 484), populated
|
||||
-- on 917 of 1,595 live rows (~57%). Owner ruling 2026-10-07: migrate it —
|
||||
-- "نرخ پرشدگی بالای ۵۵٪ است و داده برای کمپینهای وفاداری و پیامکی کاربرد
|
||||
-- مستقیم دارد".
|
||||
--
|
||||
-- Two sibling columns were deliberately NOT ported, same ruling:
|
||||
-- * marriage_date (5 rows) — "۵ ردیف توجیه معماری ندارد"
|
||||
-- * token_mobile (99 rows) — "توکنها اغلب منقضی شدهاند · زباله دیتایی"
|
||||
--
|
||||
-- ⚠ THE COLUMN IS CREATED EMPTY ON PURPOSE. Do not backfill it until the
|
||||
-- calendar question is settled (§5.9): legacy stores some dates as JALALI
|
||||
-- STRINGS elsewhere (cashes.recive_date is varchar(255), 88 of 89 values
|
||||
-- starting "14…"), so birth_date may hold Jalali years mis-entered into a
|
||||
-- timestamp. Copying those unchanged would silently produce 917 WRONG
|
||||
-- birthdays, which for an SMS campaign is worse than having none.
|
||||
-- docs/migration-precheck-3.sql answers this.
|
||||
ALTER TABLE "Customer" ADD COLUMN IF NOT EXISTS "birthDate" TIMESTAMP(3);
|
||||
|
||||
COMMENT ON COLUMN "Customer"."birthDate" IS
|
||||
'Legacy customers.birth_date (917 of 1595 rows populated). Created empty: verify Jalali-vs-Gregorian with docs/migration-precheck-3.sql BEFORE backfilling — legacy stores dates as Jalali strings in other tables.';
|
||||
|
||||
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- 3. Rejection trail for document verification
|
||||
--
|
||||
-- Legacy has THREE states per verification step, not two
|
||||
-- (MajorCustomerController.php:106-135): 1 = awaiting review, 2 = approved,
|
||||
-- 3 = REJECTED. The target's VerificationStep enum has no rejected state, so
|
||||
-- 14 already-rejected customers had nowhere to go.
|
||||
--
|
||||
-- Owner ruling 2026-10-07: mapping them to "awaiting" is "کاملاً مردود" —
|
||||
-- it would put closed cases back in the review queue and create duplicate
|
||||
-- work. REJECTED is added to the enum (statement 4 below) and these two
|
||||
-- columns carry the reason.
|
||||
--
|
||||
-- Legacy records NO reason: all 49 `customers` columns were checked and none
|
||||
-- is a reason/note/description field, and on rejection the server sends only
|
||||
-- a FIXED SMS ("اطلاعات شما تایید نشده است. لطفا با پیشتیبانی تماس حاصل
|
||||
-- فرمایید") with no cause stored anywhere. So for those 14 rows the reason is
|
||||
-- unrecoverable; the owner asked the tool to write an explicit sentinel rather
|
||||
-- than NULL, so support knows WHY it is blank:
|
||||
-- رد شده در سیستم قدیم — فاقد شرح علت ثبتشده
|
||||
-- That text is written by the migration tool, not by this migration, and only
|
||||
-- WHERE verificationRejectionReason IS NULL so a re-run can never overwrite a
|
||||
-- real reason entered in the new system (§5.5).
|
||||
--
|
||||
-- verificationRejectedAt stays NULL for the 14 legacy rows: legacy did not
|
||||
-- record a rejection timestamp either.
|
||||
ALTER TABLE "Customer" ADD COLUMN IF NOT EXISTS "verificationRejectionReason" TEXT;
|
||||
ALTER TABLE "Customer" ADD COLUMN IF NOT EXISTS "verificationRejectedAt" TIMESTAMP(3);
|
||||
|
||||
COMMENT ON COLUMN "Customer"."verificationRejectionReason" IS
|
||||
'Why document verification was rejected. Legacy stored no reason (only a fixed SMS), so rows migrated from henza carry the sentinel «رد شده در سیستم قدیم — فاقد شرح علت ثبتشده». Write only WHERE this IS NULL so a re-run never overwrites a real reason.';
|
||||
|
||||
COMMENT ON COLUMN "Customer"."verificationRejectedAt" IS
|
||||
'When verification was rejected. NULL for rows migrated from henza — legacy did not record a rejection timestamp.';
|
||||
|
||||
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- 4. VerificationStep gains REJECTED
|
||||
--
|
||||
-- ADD VALUE is additive: existing rows and existing queries are unaffected.
|
||||
-- IF NOT EXISTS makes a re-run a no-op.
|
||||
--
|
||||
-- ⚠ CONSUMER AUDIT STILL OWED. Every read of VerificationStep must be checked
|
||||
-- for a Persian label / switch that does not yet know this value, or the admin
|
||||
-- panel will render a blank cell. Flagged in §10.5.5 as a separate task; it is
|
||||
-- a display gap, not a data risk, and nothing writes REJECTED until the
|
||||
-- migration tool runs.
|
||||
--
|
||||
-- Postgres note: before v12 ADD VALUE could not run inside a transaction, and
|
||||
-- the app's own runner wraps each file in one (migrate.ts:198). This project
|
||||
-- targets a modern Postgres where that restriction is lifted. If the deploy
|
||||
-- container ever errors with "ALTER TYPE ... ADD VALUE cannot be executed
|
||||
-- inside a transaction block", this statement must move to its own file.
|
||||
DO $$
|
||||
BEGIN
|
||||
ALTER TYPE "VerificationStep" ADD VALUE IF NOT EXISTS 'REJECTED';
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- 5. CustomerFavorite — the legacy `fav` table finally gets a home
|
||||
--
|
||||
-- Legacy `fav` holds 251 rows (customer_id, product_id) and the target had NO
|
||||
-- model for it, so every customer's saved products would have been lost.
|
||||
-- Owner ruling 2026-10-06: they matter. docs/PWA-PORT-PLAN.md reached the same
|
||||
-- conclusion independently.
|
||||
--
|
||||
-- Legacy `fav` has only two columns and NO primary key, so duplicate pairs are
|
||||
-- possible in principle. The composite primary key here closes that, and the
|
||||
-- precheck confirmed fav_duplicate_pairs = 0, so no de-duplication is needed —
|
||||
-- but the tool should still SELECT DISTINCT, since the source cannot enforce it.
|
||||
--
|
||||
-- 14 of the 251 rows point at a customer that no longer exists
|
||||
-- (fav.customer_id orphans). Those must be SKIPPED by the tool; the foreign
|
||||
-- keys below would reject them anyway.
|
||||
--
|
||||
-- ON DELETE CASCADE on both sides: a favourite is a pure join row with no
|
||||
-- meaning once either end is gone. This differs from ProductVariant.imageId,
|
||||
-- which uses SetNull precisely so a deleted image never cascades into order
|
||||
-- history — the distinction is deliberate.
|
||||
--
|
||||
-- Legacy also keeps a denormalised `product.count_fav` counter. It is NOT
|
||||
-- recreated as a column; derive it from this table (§5.2 group B) rather than
|
||||
-- showing a stale or zero value.
|
||||
CREATE TABLE IF NOT EXISTS "CustomerFavorite" (
|
||||
"customerId" TEXT NOT NULL,
|
||||
"productId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "CustomerFavorite_pkey" PRIMARY KEY ("customerId", "productId")
|
||||
);
|
||||
|
||||
-- The PK already indexes (customerId, productId) left-to-right, so "my
|
||||
-- favourites" needs no extra index. This one serves the reverse lookup —
|
||||
-- "how many customers favourited this product" — which is how count_fav is
|
||||
-- derived.
|
||||
CREATE INDEX IF NOT EXISTS "CustomerFavorite_productId_idx"
|
||||
ON "CustomerFavorite"("productId");
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
ALTER TABLE "CustomerFavorite"
|
||||
ADD CONSTRAINT "CustomerFavorite_customerId_fkey"
|
||||
FOREIGN KEY ("customerId") REFERENCES "Customer"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
ALTER TABLE "CustomerFavorite"
|
||||
ADD CONSTRAINT "CustomerFavorite_productId_fkey"
|
||||
FOREIGN KEY ("productId") REFERENCES "Product"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
COMMENT ON TABLE "CustomerFavorite" IS
|
||||
'Legacy `fav` (251 rows). Composite PK replaces the source table''s missing primary key. Derive product.count_fav from here rather than storing a counter.';
|
||||
@@ -0,0 +1,22 @@
|
||||
-- ============================================================================
|
||||
-- Customer.cityNameRaw — PURELY ADDITIVE.
|
||||
--
|
||||
-- Owner ruling 2026-10-07 (docs/DATA-MIGRATION-MAP.md §5.9): keep the city a
|
||||
-- customer typed at sign-up verbatim, and set cityId only on an exact match.
|
||||
--
|
||||
-- Legacy `customers.new_city` is free text (all 172 live values are names, 0
|
||||
-- are ids). The legacy city table has only 15 rows, so 43 of those names match
|
||||
-- no known city at all, and only ~72 match one of the 15 after ي/ك
|
||||
-- normalisation. Dropping the text would lose where those customers are.
|
||||
--
|
||||
-- Legacy sign-up also forced city_id = 5 (تهران) on every new customer
|
||||
-- (Major/CustomerController.php:21); 91 of the 92 customers with both values
|
||||
-- carry that forced Tehran. For them the typed name is the truth.
|
||||
--
|
||||
-- D15: idempotent, runs under both migration ledgers.
|
||||
-- ============================================================================
|
||||
|
||||
ALTER TABLE "Customer" ADD COLUMN IF NOT EXISTS "cityNameRaw" TEXT;
|
||||
|
||||
COMMENT ON COLUMN "Customer"."cityNameRaw" IS
|
||||
'Legacy customers.new_city — city name as typed at sign-up, kept verbatim. cityId is set too only on an exact (ي/ك-normalised) match; legacy forced city_id=5 (Tehran) on sign-up, so prefer this text over that cityId.';
|
||||
@@ -0,0 +1,31 @@
|
||||
-- ============================================================================
|
||||
-- Customer identity cleanup — data only, no schema change. Idempotent.
|
||||
--
|
||||
-- Owner ruling 2026-10-07: «هر دیتایی باید سر جای خودش بشینه».
|
||||
--
|
||||
-- 1. nationalCode held the MOBILE (or "<mobile>-<provider>-<code>") on every
|
||||
-- customer created without a national code, because the column used to be
|
||||
-- NOT NULL. It is optional since 20261007120000, and the code paths that
|
||||
-- wrote those stand-ins are fixed in the same change as this file. The
|
||||
-- stand-ins are cleared to NULL; a real national code is never touched.
|
||||
-- Accounting is unaffected: it only ever received validNationalCode(),
|
||||
-- which already mapped a mobile to null.
|
||||
--
|
||||
-- 2. passwordHash '' becomes the explicit "no password login" marker
|
||||
-- (auth/password-hash.ts). Both are refused before bcrypt by
|
||||
-- compareLocalHash, so nobody's ability to sign in changes.
|
||||
-- ============================================================================
|
||||
|
||||
UPDATE "Customer"
|
||||
SET "nationalCode" = NULL
|
||||
WHERE "nationalCode" = ''
|
||||
OR "nationalCode" = "mobile"
|
||||
OR "nationalCode" LIKE "mobile" || '-%';
|
||||
|
||||
UPDATE "Customer" SET "passwordHash" = '!OTP_ONLY_NO_PASSWORD_LOGIN' WHERE "passwordHash" = '';
|
||||
UPDATE "AdminUser" SET "passwordHash" = '!NO_PASSWORD_SET_YET' WHERE "passwordHash" = '';
|
||||
|
||||
-- The earlier comment named the wrong source table: `fav` belongs to the retail
|
||||
-- shop; wholesale favourites come from `major_favorites` (DATA-MIGRATION-MAP §10.7).
|
||||
COMMENT ON TABLE "CustomerFavorite" IS
|
||||
'Legacy `major_favorites` (wholesale; deduplicated on import). Composite PK replaces the source table''s missing primary key. Derive a favourite count from here rather than storing a counter.';
|
||||
@@ -56,6 +56,13 @@ enum VerificationStep {
|
||||
STEP_ONE_SUBMITTED
|
||||
STEP_TWO_SUBMITTED
|
||||
VERIFIED
|
||||
|
||||
/// Legacy had THREE states per step, not two
|
||||
/// (MajorCustomerController.php:106-135): 1 = awaiting, 2 = approved,
|
||||
/// 3 = REJECTED. Mapping rejected customers to UNVERIFIED would put closed
|
||||
/// cases back in the review queue, so the owner ruled it out (2026-10-07).
|
||||
/// 14 legacy rows land here; see Customer.verificationRejectionReason.
|
||||
REJECTED
|
||||
}
|
||||
|
||||
/// Legacy kept retail and wholesale orders in two SEPARATE tables
|
||||
@@ -367,11 +374,32 @@ model Customer {
|
||||
lastName String?
|
||||
|
||||
mobile String @unique
|
||||
nationalCode String @unique
|
||||
/// Legacy customers.ncode. OPTIONAL since 2026-10-07: not one of the 1,616
|
||||
/// legacy customers has a national code (1595/1595 empty), and fabricating
|
||||
/// one is a data violation that would block later legal identity checks
|
||||
/// (owner ruling). Still @unique — in PostgreSQL NULLs do not collide, so
|
||||
/// the migration tool must write NULL and never '', which would collide on
|
||||
/// the second row.
|
||||
///
|
||||
/// Three service-layer workarounds exist ONLY because this used to be
|
||||
/// required, and they store the MOBILE NUMBER here:
|
||||
/// admin-customers.service.ts:625,685 and customer-auth.service.ts:258.
|
||||
/// Retiring them is a separate change; see docs/DATA-MIGRATION-MAP.md §10.4.
|
||||
nationalCode String? @unique
|
||||
passwordHash String
|
||||
cityId String?
|
||||
city City? @relation(fields: [cityId], references: [id])
|
||||
|
||||
/// Legacy customers.new_city — the city name exactly as the customer typed it
|
||||
/// at app sign-up (Major/CustomerController.php:36). Kept verbatim because
|
||||
/// the legacy city table has only 15 rows, so the typed name is often the only
|
||||
/// record of where the customer is (172 customers; 43 match no known city).
|
||||
/// cityId is set alongside it only on an exact, ي/ك-normalised name match.
|
||||
/// Legacy sign-up also forced city_id = 5 (Tehran) on everyone
|
||||
/// (Major/CustomerController.php:21), so for those rows the typed name, not
|
||||
/// cityId, is the truth. Owner ruling 2026-10-07: keep both.
|
||||
cityNameRaw String?
|
||||
|
||||
/// Legacy Customer.type — distinguishes بنکدار from مغازه دار, which the
|
||||
/// BankerList / ShopkeeperList screens filter on.
|
||||
kind CustomerKind @default(APP_SHOPKEEPER)
|
||||
@@ -429,6 +457,30 @@ model Customer {
|
||||
businessLicenseUrl String?
|
||||
shopImageUrl String?
|
||||
|
||||
/// Why verification was rejected (VerificationStep.REJECTED).
|
||||
///
|
||||
/// Legacy recorded NO reason: none of its 49 `customers` columns is a
|
||||
/// reason/note field, and on rejection it only sent a fixed SMS. So the 14
|
||||
/// rows migrated from henza carry the sentinel
|
||||
/// «رد شده در سیستم قدیم — فاقد شرح علت ثبتشده» instead of NULL, so support
|
||||
/// knows why it is blank (owner ruling 2026-10-07). The migration tool
|
||||
/// writes it only WHERE this IS NULL, so a re-run cannot overwrite a real
|
||||
/// reason entered in the new system.
|
||||
verificationRejectionReason String?
|
||||
|
||||
/// NULL for rows migrated from henza — legacy recorded no rejection time.
|
||||
verificationRejectedAt DateTime?
|
||||
|
||||
/// Legacy customers.birth_date, populated on 917 of 1,595 rows. Kept for the
|
||||
/// birthday SMS / loyalty campaigns (owner ruling 2026-10-07).
|
||||
///
|
||||
/// ⚠ Legacy stores dates as JALALI STRINGS in other tables
|
||||
/// (cashes.recive_date is varchar, 88/89 values starting "14…"), so this
|
||||
/// timestamp may hold mis-entered Jalali years. Confirm the calendar with
|
||||
/// docs/migration-precheck-3.sql BEFORE backfilling: copying them unchanged
|
||||
/// would produce 917 wrong birthdays, worse for an SMS campaign than none.
|
||||
birthDate DateTime?
|
||||
|
||||
/// Legacy `image_id` — the profile photo (عکس پروفایل) on the sales-agent
|
||||
/// form. Legacy stored an FK to its Image table and read it back as a nested
|
||||
/// `image: { id, image }`, so this is a relation, not a bare URL string.
|
||||
@@ -457,12 +509,35 @@ model Customer {
|
||||
notifications NotificationRecipient[]
|
||||
activityLogs CustomerActivityLog[]
|
||||
otpChallenges CustomerOtp[]
|
||||
favorites CustomerFavorite[]
|
||||
|
||||
@@index([referredByAgentId])
|
||||
@@index([firstName])
|
||||
@@index([lastName])
|
||||
}
|
||||
|
||||
/// Legacy `fav` (251 rows) — saved products. The target had no model for this,
|
||||
/// so every customer's favourites would have been lost in the migration; the
|
||||
/// owner confirmed on 2026-10-06 that they matter.
|
||||
///
|
||||
/// Legacy `fav` has two columns and NO primary key. The composite key here
|
||||
/// supplies the constraint the source lacks (the precheck found 0 duplicate
|
||||
/// pairs, but the tool should still SELECT DISTINCT). 14 of the 251 rows point
|
||||
/// at a deleted customer and must be skipped.
|
||||
///
|
||||
/// Legacy's denormalised `product.count_fav` counter is deliberately NOT
|
||||
/// recreated as a column — derive it from this table.
|
||||
model CustomerFavorite {
|
||||
customerId String
|
||||
customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)
|
||||
productId String
|
||||
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@id([customerId, productId])
|
||||
@@index([productId])
|
||||
}
|
||||
|
||||
model CustomerAddress {
|
||||
id String @id @default(cuid())
|
||||
customerId String
|
||||
@@ -579,6 +654,7 @@ model Product {
|
||||
comments Comment[]
|
||||
promotions Promotion[]
|
||||
allocationItems BranchAllocationItem[]
|
||||
favoritedBy CustomerFavorite[]
|
||||
}
|
||||
|
||||
model ProductImage {
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* henza (MySQL `oapi`) → gold-bank (PostgreSQL) data import.
|
||||
*
|
||||
* The rules live in docs/DATA-MIGRATION-MAP.md; every step cites its section.
|
||||
*
|
||||
* Usage (from apps/api):
|
||||
*
|
||||
* npx ts-node --transpile-only scripts/legacy-import/index.ts \
|
||||
* --source "mysql://user:pass@127.0.0.1:3307/oapi" \
|
||||
* --target "postgresql://user:pass@localhost:5432/goldbank_import_test" \
|
||||
* [--images "F:/henza/storage" --upload-dir "./storage/uploads"] \
|
||||
* [--only customers,ledger] [--report ./legacy-import-report.md] --yes
|
||||
*
|
||||
* Safety:
|
||||
* - The source is only read. Point it at a COPY of production anyway.
|
||||
* - --target is required and never taken from .env, so the dev database is
|
||||
* never written by accident. Without --yes nothing is written; a target
|
||||
* whose name does not contain "import" or "staging" also needs
|
||||
* --confirm-db=<its exact name>.
|
||||
* - Re-runnable: every written row is recorded in legacy_import.id_map, so a
|
||||
* second run updates instead of duplicating, and a run that stops half way
|
||||
* is finished by running it again.
|
||||
* - Never writes Customer/Product accounting* columns, ProductVariant.imageId,
|
||||
* or the Accounting* tables, and never deletes a ProductImage.
|
||||
* - Writes go straight through Prisma, not through the API services, so no
|
||||
* SMS is sent and nothing is queued to the accounting software.
|
||||
*/
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { IdMap, makeContext, openSource, type Ctx, type Options } from './lib/context';
|
||||
import { admins, branches, cities, customers, experts, roles, workshops } from './steps/people';
|
||||
import { brands, categories, products, variants } from './steps/catalog';
|
||||
import { favorites, ledger, orders, preOrders } from './steps/commerce';
|
||||
import { reconcile } from './steps/reconcile';
|
||||
|
||||
/** Order matters: each step reads the ids the earlier ones mapped. */
|
||||
const STEPS: [string, (ctx: Ctx) => Promise<void>][] = [
|
||||
['cities', cities],
|
||||
['roles', roles],
|
||||
['branches', branches],
|
||||
['admins', admins],
|
||||
['experts', experts],
|
||||
['workshops', workshops],
|
||||
['customers', customers],
|
||||
['brands', brands],
|
||||
['categories', categories],
|
||||
['products', products],
|
||||
['variants', variants],
|
||||
['orders', orders],
|
||||
['ledger', ledger],
|
||||
['favorites', favorites],
|
||||
['preorders', preOrders],
|
||||
['reconcile', reconcile],
|
||||
];
|
||||
|
||||
const ENTITIES = [
|
||||
'city', 'ut', 'branch', 'admin', 'expert', 'workshop', 'customer', 'file', 'brand', 'category',
|
||||
'product', 'pimage', 'variant', 'order', 'orderitem', 'ledger', 'preorder',
|
||||
];
|
||||
|
||||
/** Columns the prep migrations added; the import refuses to run without them. */
|
||||
const REQUIRED = [
|
||||
['Customer', 'nationalCode'], ['Customer', 'birthDate'], ['Customer', 'cityNameRaw'],
|
||||
['Customer', 'verificationRejectionReason'], ['CustomerFavorite', 'customerId'],
|
||||
];
|
||||
|
||||
function parseArgs(argv: string[]) {
|
||||
const a = new Map<string, string>();
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const k = argv[i];
|
||||
if (!k.startsWith('--')) continue;
|
||||
const eq = k.indexOf('=');
|
||||
if (eq > 0) a.set(k.slice(2, eq), k.slice(eq + 1));
|
||||
else if (argv[i + 1] && !argv[i + 1].startsWith('--')) a.set(k.slice(2), argv[++i]);
|
||||
else a.set(k.slice(2), 'true');
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
const fail = (msg: string): never => {
|
||||
console.error(`\n✖ ${msg}\n`);
|
||||
process.exit(1);
|
||||
};
|
||||
|
||||
async function main() {
|
||||
const a = parseArgs(process.argv.slice(2));
|
||||
const opt: Options = {
|
||||
sourceUrl: a.get('source') ?? fail('--source <mysql url> is required'),
|
||||
targetUrl: a.get('target') ?? fail('--target <postgres url> is required (never read from .env)'),
|
||||
imagesDir: a.get('images'),
|
||||
uploadDir: a.get('upload-dir'),
|
||||
only: a.get('only') ? new Set(a.get('only')!.split(',').map((s) => s.trim())) : undefined,
|
||||
reportPath: resolve(a.get('report') ?? 'legacy-import-report.md'),
|
||||
};
|
||||
if (opt.imagesDir && !opt.uploadDir) fail('--images needs --upload-dir (the target UPLOAD_DIR)');
|
||||
if (opt.only) for (const s of opt.only) if (!STEPS.some(([n]) => n === s)) fail(`unknown step "${s}"`);
|
||||
|
||||
const db = new PrismaClient({ datasources: { db: { url: opt.targetUrl } } });
|
||||
const src = openSource(opt.sourceUrl);
|
||||
|
||||
try {
|
||||
/* preflight — read only */
|
||||
const [{ db: dbName }] = await db.$queryRawUnsafe<{ db: string }[]>('SELECT current_database() AS db');
|
||||
const [srcInfo] = await (await src.query('SELECT DATABASE() AS db, VERSION() AS v'))[0] as { db: string; v: string }[];
|
||||
const missing: string[] = [];
|
||||
for (const [t, c] of REQUIRED) {
|
||||
const [{ n }] = await db.$queryRawUnsafe<{ n: bigint }[]>(
|
||||
`SELECT COUNT(*) AS n FROM information_schema.columns WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2`, t, c,
|
||||
);
|
||||
if (Number(n) === 0) missing.push(`${t}.${c}`);
|
||||
}
|
||||
const counts = {
|
||||
customers: await db.customer.count(),
|
||||
products: await db.product.count(),
|
||||
ledger: await db.ledgerEntry.count(),
|
||||
};
|
||||
console.log(`source mysql ${srcInfo.v} · database ${srcInfo.db}`);
|
||||
console.log(`target postgres · database ${dbName} · ${counts.customers} customers, ${counts.products} products, ${counts.ledger} ledger entries`);
|
||||
if (missing.length) fail(`target is missing ${missing.join(', ')} — apply the prep migrations first`);
|
||||
|
||||
if (a.get('yes') !== 'true') {
|
||||
console.log('\nNothing written. Re-run with --yes to import.');
|
||||
return;
|
||||
}
|
||||
if (!/import|staging/i.test(dbName) && a.get('confirm-db') !== dbName) {
|
||||
fail(`"${dbName}" does not look like a test or staging copy. To write to it anyway add --confirm-db=${dbName}`);
|
||||
}
|
||||
|
||||
/* run */
|
||||
await IdMap.ensureSchema(db);
|
||||
const ctx = makeContext(opt, src, db);
|
||||
for (const e of ENTITIES) await ctx.map.load(e);
|
||||
|
||||
for (const [name, step] of STEPS) {
|
||||
if (opt.only && !opt.only.has(name)) continue;
|
||||
const t0 = Date.now();
|
||||
process.stdout.write(`▸ ${name} … `);
|
||||
await step(ctx);
|
||||
console.log(`${((Date.now() - t0) / 1000).toFixed(1)}s`);
|
||||
}
|
||||
|
||||
const md = ctx.report.render([
|
||||
`- started: ${ctx.report.startedAt.toISOString()} · finished: ${new Date().toISOString()}`,
|
||||
`- source: \`${srcInfo.db}\` (MySQL ${srcInfo.v}) · target: \`${dbName}\``,
|
||||
`- steps: ${opt.only ? [...opt.only].join(', ') : 'all'}`,
|
||||
`- images: ${opt.imagesDir ? `${opt.imagesDir} → ${opt.uploadDir}` : 'not copied (no --images)'}`,
|
||||
]);
|
||||
writeFileSync(opt.reportPath, md);
|
||||
console.log(`\nreport: ${opt.reportPath}`);
|
||||
} finally {
|
||||
await src.end();
|
||||
await db.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,327 @@
|
||||
/**
|
||||
* Shared state for one import run: both connections, the id map and the report.
|
||||
*/
|
||||
import { copyFileSync, existsSync, mkdirSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { createPool, type Pool, type RowDataPacket } from 'mysql2/promise';
|
||||
|
||||
export interface Options {
|
||||
sourceUrl: string;
|
||||
targetUrl: string;
|
||||
/** henza `storage/` folder holding the image files (optional). */
|
||||
imagesDir?: string;
|
||||
/** Target UPLOAD_DIR the files are copied into (required with imagesDir). */
|
||||
uploadDir?: string;
|
||||
/** Run only these steps (by name); all when unset. */
|
||||
only?: Set<string>;
|
||||
reportPath: string;
|
||||
}
|
||||
|
||||
/* ───────────── report ───────────── */
|
||||
|
||||
interface Section {
|
||||
counts: Map<string, number>;
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* What the run did, step by step. Counts say how many rows went which way;
|
||||
* notes are the things a person must look at. Rendered to markdown at the end.
|
||||
*/
|
||||
export class Report {
|
||||
readonly startedAt = new Date();
|
||||
private readonly sections = new Map<string, Section>();
|
||||
|
||||
private section(step: string): Section {
|
||||
let s = this.sections.get(step);
|
||||
if (!s) {
|
||||
s = { counts: new Map(), notes: [] };
|
||||
this.sections.set(step, s);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
count(step: string, key: string, n = 1) {
|
||||
const s = this.section(step);
|
||||
s.counts.set(key, (s.counts.get(key) ?? 0) + n);
|
||||
}
|
||||
|
||||
note(step: string, message: string) {
|
||||
this.section(step).notes.push(message);
|
||||
}
|
||||
|
||||
get(step: string, key: string): number {
|
||||
return this.sections.get(step)?.counts.get(key) ?? 0;
|
||||
}
|
||||
|
||||
render(header: string[]): string {
|
||||
const out: string[] = ['# henza → gold-bank import report', '', ...header, ''];
|
||||
for (const [step, s] of this.sections) {
|
||||
out.push(`## ${step}`, '');
|
||||
if (s.counts.size) {
|
||||
out.push('| | |', '|---|---:|');
|
||||
for (const [k, v] of s.counts) out.push(`| ${k} | ${v} |`);
|
||||
out.push('');
|
||||
}
|
||||
for (const n of s.notes) out.push(`- ${n}`);
|
||||
if (s.notes.length) out.push('');
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/* ───────────── id map ───────────── */
|
||||
|
||||
/**
|
||||
* Legacy id -> target id, per entity, persisted in the TARGET database under
|
||||
* its own schema `legacy_import` — outside the `public` schema Prisma manages,
|
||||
* so it is no app-schema change and drops cleanly after cutover
|
||||
* (`DROP SCHEMA legacy_import CASCADE`).
|
||||
*
|
||||
* It is what makes a re-run safe (a mapped row is updated, never re-created)
|
||||
* and what later redirects old links such as /product/123 (GO-LIVE-PLAN §7).
|
||||
* `how` records whether the row was created by the import or matched to a row
|
||||
* that already existed in the target (merge, §10.5).
|
||||
*/
|
||||
export type How = 'created' | 'matched' | 'merged';
|
||||
|
||||
export class IdMap {
|
||||
private readonly cache = new Map<string, Map<string, { target: string; how: How }>>();
|
||||
|
||||
constructor(private readonly db: PrismaClient) {}
|
||||
|
||||
static async ensureSchema(db: PrismaClient) {
|
||||
await db.$executeRawUnsafe(`CREATE SCHEMA IF NOT EXISTS legacy_import`);
|
||||
await db.$executeRawUnsafe(`
|
||||
CREATE TABLE IF NOT EXISTS legacy_import.id_map (
|
||||
entity text NOT NULL,
|
||||
legacy_id text NOT NULL,
|
||||
target_id text NOT NULL,
|
||||
how text NOT NULL,
|
||||
mapped_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (entity, legacy_id)
|
||||
)`);
|
||||
}
|
||||
|
||||
async load(entity: string) {
|
||||
const rows = await this.db.$queryRawUnsafe<{ legacy_id: string; target_id: string; how: How }[]>(
|
||||
`SELECT legacy_id, target_id, how FROM legacy_import.id_map WHERE entity = $1`,
|
||||
entity,
|
||||
);
|
||||
this.cache.set(entity, new Map(rows.map((r) => [r.legacy_id, { target: r.target_id, how: r.how }])));
|
||||
}
|
||||
|
||||
get(entity: string, legacyId: unknown): string | undefined {
|
||||
if (legacyId === null || legacyId === undefined) return undefined;
|
||||
return this.cache.get(entity)?.get(String(legacyId))?.target;
|
||||
}
|
||||
|
||||
how(entity: string, legacyId: unknown): How | undefined {
|
||||
return this.cache.get(entity)?.get(String(legacyId))?.how;
|
||||
}
|
||||
|
||||
async set(entity: string, legacyId: unknown, targetId: string, how: How) {
|
||||
const key = String(legacyId);
|
||||
await this.db.$executeRawUnsafe(
|
||||
`INSERT INTO legacy_import.id_map (entity, legacy_id, target_id, how)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (entity, legacy_id) DO UPDATE SET target_id = EXCLUDED.target_id, how = EXCLUDED.how`,
|
||||
entity, key, targetId, how,
|
||||
);
|
||||
let m = this.cache.get(entity);
|
||||
if (!m) {
|
||||
m = new Map();
|
||||
this.cache.set(entity, m);
|
||||
}
|
||||
m.set(key, { target: targetId, how });
|
||||
}
|
||||
|
||||
async drop(entity: string, legacyId: unknown) {
|
||||
await this.db.$executeRawUnsafe(
|
||||
`DELETE FROM legacy_import.id_map WHERE entity = $1 AND legacy_id = $2`,
|
||||
entity, String(legacyId),
|
||||
);
|
||||
this.cache.get(entity)?.delete(String(legacyId));
|
||||
}
|
||||
}
|
||||
|
||||
/* ───────────── upsert discipline ───────────── */
|
||||
|
||||
/**
|
||||
* The one way a step writes a row (§10.5: this is a MERGE into a live target):
|
||||
*
|
||||
* - already mapped -> `update(id, how)`; the step decides what it may touch
|
||||
* - matches a target row -> mapped as 'matched', then `update(id, 'matched')`
|
||||
* - otherwise -> `create()`, mapped as 'created'
|
||||
*
|
||||
* A mapping whose target row has since been deleted is dropped and redone, so a
|
||||
* re-run heals instead of failing on a dangling id.
|
||||
*/
|
||||
export async function upsert(
|
||||
ctx: Ctx,
|
||||
entity: string,
|
||||
legacyId: unknown,
|
||||
ops: {
|
||||
exists: (id: string) => Promise<boolean>;
|
||||
find: () => Promise<{ id: string } | null>;
|
||||
create: () => Promise<{ id: string }>;
|
||||
update: (id: string, how: How) => Promise<void>;
|
||||
},
|
||||
): Promise<{ id: string; how: How; isNew: boolean }> {
|
||||
const mapped = ctx.map.get(entity, legacyId);
|
||||
if (mapped) {
|
||||
if (await ops.exists(mapped)) {
|
||||
const how = ctx.map.how(entity, legacyId) ?? 'created';
|
||||
await ops.update(mapped, how);
|
||||
return { id: mapped, how, isNew: false };
|
||||
}
|
||||
await ctx.map.drop(entity, legacyId);
|
||||
}
|
||||
const found = await ops.find();
|
||||
if (found) {
|
||||
await ctx.map.set(entity, legacyId, found.id, 'matched');
|
||||
await ops.update(found.id, 'matched');
|
||||
return { id: found.id, how: 'matched', isNew: false };
|
||||
}
|
||||
const created = await ops.create();
|
||||
await ctx.map.set(entity, legacyId, created.id, 'created');
|
||||
return { id: created.id, how: 'created', isNew: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* For a row that already existed in the target (`matched`): only the fields
|
||||
* the target left empty are filled. The target's own values win — the owner
|
||||
* confirmed its data is real (§10.5).
|
||||
*/
|
||||
export function fillEmpty<T extends Record<string, unknown>>(current: Record<string, unknown>, patch: T): Partial<T> {
|
||||
const out: Partial<T> = {};
|
||||
for (const [k, v] of Object.entries(patch)) {
|
||||
const cur = current[k];
|
||||
if ((cur === null || cur === undefined || cur === '') && v !== null && v !== undefined) {
|
||||
(out as Record<string, unknown>)[k] = v;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ───────────── context ───────────── */
|
||||
|
||||
export interface Ctx {
|
||||
src: Pool;
|
||||
db: PrismaClient;
|
||||
map: IdMap;
|
||||
report: Report;
|
||||
opt: Options;
|
||||
/** A read-only query against the legacy MySQL. */
|
||||
q<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]>;
|
||||
/** Public URL for a legacy `image` row, copying its file when a source dir is given. */
|
||||
imageUrl(imageId: unknown, step: string): Promise<string | null>;
|
||||
/**
|
||||
* An `UploadedFile` row for a legacy image — what avatars point at
|
||||
* (Customer/AdminUser.avatarFileId are FKs, not URLs). Mapped as 'file'.
|
||||
*/
|
||||
uploadedFile(imageId: unknown, purpose: string, step: string): Promise<string | null>;
|
||||
}
|
||||
|
||||
const MIME: Record<string, string> = {
|
||||
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
|
||||
webp: 'image/webp', svg: 'image/svg+xml', pdf: 'application/pdf',
|
||||
};
|
||||
|
||||
export function openSource(url: string): Pool {
|
||||
return createPool({
|
||||
uri: url,
|
||||
connectionLimit: 4,
|
||||
charset: 'utf8mb4',
|
||||
// Timestamps come back as the wall-clock text legacy stored, and are
|
||||
// converted from Tehran time explicitly (normalize.tehran). The session
|
||||
// time zone is left at the server's own, which is what Laravel and the
|
||||
// Navicat dump both used.
|
||||
dateStrings: true,
|
||||
supportBigNumbers: true,
|
||||
bigNumberStrings: true,
|
||||
});
|
||||
}
|
||||
|
||||
export function makeContext(opt: Options, src: Pool, db: PrismaClient): Ctx {
|
||||
const map = new IdMap(db);
|
||||
const report = new Report();
|
||||
const imageRows = new Map<string, string | null>();
|
||||
|
||||
const ctx: Ctx = {
|
||||
src,
|
||||
db,
|
||||
map,
|
||||
report,
|
||||
opt,
|
||||
async q<T>(sql: string, params: unknown[] = []) {
|
||||
const [rows] = await src.query<RowDataPacket[]>(sql, params);
|
||||
return rows as unknown as T[];
|
||||
},
|
||||
async imageUrl(imageId: unknown, step: string) {
|
||||
if (imageId === null || imageId === undefined || imageId === '') return null;
|
||||
const key = String(imageId);
|
||||
if (!imageRows.has(key)) {
|
||||
const [row] = await ctx.q<{ image: string | null }>('SELECT image FROM image WHERE id = ?', [key]);
|
||||
imageRows.set(key, row?.image ? String(row.image).trim() : null);
|
||||
}
|
||||
const file = imageRows.get(key);
|
||||
if (!file) {
|
||||
report.count(step, 'image reference with no `image` row');
|
||||
return null;
|
||||
}
|
||||
copyImage(ctx, file, step);
|
||||
// Same shape the admin upload writes (admin-uploads.service.ts:61).
|
||||
return `/uploads/${file}`;
|
||||
},
|
||||
async uploadedFile(imageId: unknown, purpose: string, step: string) {
|
||||
if (imageId === null || imageId === undefined || imageId === '') return null;
|
||||
// Resolve first even when mapped: resolving copies the file (see productImages).
|
||||
const url = await ctx.imageUrl(imageId, step);
|
||||
const mapped = map.get('file', imageId);
|
||||
if (mapped) return mapped;
|
||||
if (!url) return null;
|
||||
const [row] = await ctx.q<{ original_name: string | null; ext: string | null }>(
|
||||
'SELECT original_name, ext FROM image WHERE id = ?', [String(imageId)],
|
||||
);
|
||||
const file = url.slice('/uploads/'.length);
|
||||
const ext = (row?.ext ?? file.split('.').pop() ?? '').toLowerCase().trim();
|
||||
const src = ctx.opt.imagesDir ? join(ctx.opt.imagesDir, file) : null;
|
||||
const created = await db.uploadedFile.create({
|
||||
data: {
|
||||
url,
|
||||
originalName: (row?.original_name ?? '').trim() || file,
|
||||
mimeType: MIME[ext] ?? 'application/octet-stream',
|
||||
sizeBytes: src && existsSync(src) ? statSync(src).size : 0,
|
||||
purpose,
|
||||
},
|
||||
});
|
||||
await map.set('file', imageId, created.id, 'created');
|
||||
return created.id;
|
||||
},
|
||||
};
|
||||
return ctx;
|
||||
}
|
||||
|
||||
const copied = new Set<string>();
|
||||
|
||||
function copyImage(ctx: Ctx, file: string, step: string) {
|
||||
const { imagesDir, uploadDir } = ctx.opt;
|
||||
if (!imagesDir || !uploadDir || copied.has(file)) return;
|
||||
copied.add(file);
|
||||
const from = join(imagesDir, file);
|
||||
const to = join(uploadDir, file);
|
||||
if (existsSync(to)) {
|
||||
ctx.report.count('images', 'already in upload dir');
|
||||
return;
|
||||
}
|
||||
if (!existsSync(from) || !statSync(from).isFile()) {
|
||||
ctx.report.count('images', 'missing in henza storage');
|
||||
ctx.report.note('images', `missing file ${file} (referenced from ${step})`);
|
||||
return;
|
||||
}
|
||||
mkdirSync(uploadDir, { recursive: true });
|
||||
copyFileSync(from, to);
|
||||
ctx.report.count('images', 'copied');
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* Value conversion from the henza MySQL schema to the Prisma one.
|
||||
*
|
||||
* Every helper here is pure, so the rules can be read and tested in isolation.
|
||||
* Each rule is the one recorded in docs/DATA-MIGRATION-MAP.md.
|
||||
*/
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
const PERSIAN_DIGITS = '۰۱۲۳۴۵۶۷۸۹';
|
||||
const ARABIC_DIGITS = '٠١٢٣٤٥٦٧٨٩';
|
||||
|
||||
/** Persian/Arabic-Indic digits -> ASCII. Legacy did the same (Utility::faTOen). */
|
||||
export function latinDigits(s: string): string {
|
||||
return s.replace(/[۰-۹٠-٩]/g, (d) => {
|
||||
const i = PERSIAN_DIGITS.indexOf(d);
|
||||
return String(i >= 0 ? i : ARABIC_DIGITS.indexOf(d));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Persian text as stored: trimmed, single spaces, and Arabic ي/ك folded to
|
||||
* Persian ی/ک. Empty -> null, so '' never reaches a nullable target column.
|
||||
*/
|
||||
export function text(v: unknown): string | null {
|
||||
if (v === null || v === undefined) return null;
|
||||
const s = String(v)
|
||||
.replace(/ي/g, 'ی')
|
||||
.replace(/ك/g, 'ک')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
return s === '' ? null : s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Comparison key for matching names across systems. Also drops the zero-width
|
||||
* non-joiner, which legacy typed inconsistently ("مدیر اصلی" vs "مدیراصلی").
|
||||
* The ي/ك fold alone raised exact city matches from 32 to 72 (§10.4).
|
||||
*/
|
||||
export function matchKey(v: unknown): string | null {
|
||||
const t = text(v);
|
||||
return t === null ? null : t.replace(//g, '').replace(/\s/g, '').toLowerCase();
|
||||
}
|
||||
|
||||
/** Mobile as the login key: ASCII digits only, or null. */
|
||||
export function mobile(v: unknown): string | null {
|
||||
if (v === null || v === undefined) return null;
|
||||
const d = latinDigits(String(v)).replace(/\D/g, '');
|
||||
return d === '' ? null : d;
|
||||
}
|
||||
|
||||
function num(v: unknown): number {
|
||||
if (v === null || v === undefined || v === '') return 0;
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy stores money and weight as `double` (§4). Going through toFixed at the
|
||||
* target scale drops the binary noise (12.3 is really 12.30000000000000071…)
|
||||
* exactly as Decimal(14,4) would, so a reconciliation can compare like with like.
|
||||
*/
|
||||
export const grams = (v: unknown) => new Prisma.Decimal(num(v).toFixed(4));
|
||||
export const rial = (v: unknown) => new Prisma.Decimal(num(v).toFixed(2));
|
||||
export const percent = (v: unknown) => new Prisma.Decimal(num(v).toFixed(3));
|
||||
export const isZero = (v: unknown) => Math.abs(num(v)) < 0.00005;
|
||||
export const toNumber = num;
|
||||
|
||||
/** Integer or null — for tinyint flags and ids that may arrive as strings. */
|
||||
export function int(v: unknown): number | null {
|
||||
if (v === null || v === undefined || v === '') return null;
|
||||
const n = Number(v);
|
||||
return Number.isInteger(n) ? n : null;
|
||||
}
|
||||
|
||||
/* ───────────── time ───────────── */
|
||||
|
||||
/**
|
||||
* The Laravel app ran with timezone 'Asia/Tehran' (henza_server config/app.php:70),
|
||||
* so every timestamp is Tehran wall-clock time. Read as a UTC instant it would
|
||||
* be 3:30 (4:30 under the pre-2022 summer time) off, moving evening documents
|
||||
* to the next day on a statement. The ICU zone rules know Iran's historical
|
||||
* DST, so the offset is taken from them per instant rather than hard-coded.
|
||||
*/
|
||||
const tehranFormat = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: 'Asia/Tehran',
|
||||
hourCycle: 'h23',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
});
|
||||
|
||||
function tehranOffsetMs(utcMs: number): number {
|
||||
const p: Record<string, string> = {};
|
||||
for (const part of tehranFormat.formatToParts(new Date(utcMs))) p[part.type] = part.value;
|
||||
const asUtc = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second);
|
||||
return asUtc - utcMs;
|
||||
}
|
||||
|
||||
const WALL = /^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2}):(\d{2}))?/;
|
||||
|
||||
/** 'YYYY-MM-DD HH:MM:SS' in Tehran wall-clock time -> the UTC instant. */
|
||||
export function tehran(v: unknown): Date | null {
|
||||
if (v === null || v === undefined || v === '') return null;
|
||||
const m = WALL.exec(String(v));
|
||||
if (!m || m[1] === '0000') return null;
|
||||
const wall = Date.UTC(+m[1], +m[2] - 1, +m[3], +(m[4] ?? 0), +(m[5] ?? 0), +(m[6] ?? 0));
|
||||
// Two passes: the offset at the guessed instant can differ across a DST edge.
|
||||
let utc = wall - tehranOffsetMs(wall);
|
||||
utc = wall - tehranOffsetMs(utc);
|
||||
return new Date(utc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Birthdays (owner ruling 2026-10-07, §10.7): of 915 set values only 541 are
|
||||
* real. Dropped: the sign-up default (birth date == sign-up date, 190 rows) and
|
||||
* the impossible ones (a time of day, or born after 2008; 184 rows). A
|
||||
* birthday is a calendar date, so it is kept as UTC midnight of that date.
|
||||
*/
|
||||
export function birthday(birth: unknown, signup: unknown): Date | null {
|
||||
const b = WALL.exec(String(birth ?? ''));
|
||||
if (!b) return null;
|
||||
if ((b[4] ?? '00') !== '00' || (b[5] ?? '00') !== '00' || (b[6] ?? '00') !== '00') return null;
|
||||
if (+b[1] > 2008 || +b[1] < 1900) return null;
|
||||
const s = WALL.exec(String(signup ?? ''));
|
||||
if (s && s[1] === b[1] && s[2] === b[2] && s[3] === b[3]) return null;
|
||||
return new Date(Date.UTC(+b[1], +b[2] - 1, +b[3]));
|
||||
}
|
||||
|
||||
/* ───────────── Jalali dates ───────────── */
|
||||
|
||||
/**
|
||||
* `cashes.recive_date` is a varchar holding a Jalali date ("1403/05/12"; 88 of
|
||||
* 89 values start with 14). This is the standard jalaali-js arithmetic
|
||||
* (Borkowski), inlined so the tool needs no extra dependency.
|
||||
*
|
||||
* Its integer division TRUNCATES toward zero. Math.floor is not a substitute:
|
||||
* g2d's (gm - 8) / 6 is negative for March, and flooring it shifted every
|
||||
* converted date by a year.
|
||||
*/
|
||||
const div = (a: number, b: number) => Math.trunc(a / b);
|
||||
const mod = (a: number, b: number) => a - Math.trunc(a / b) * b;
|
||||
|
||||
function jalCal(jy: number) {
|
||||
const breaks = [-61, 9, 38, 199, 426, 686, 756, 818, 1111, 1181, 1210, 1635, 2060, 2097, 2192, 2262, 2324, 2394, 2456, 3178];
|
||||
const gy = jy + 621;
|
||||
let leapJ = -14;
|
||||
let jp = breaks[0];
|
||||
let jump = 0;
|
||||
for (let i = 1; i < breaks.length; i++) {
|
||||
const jm = breaks[i];
|
||||
jump = jm - jp;
|
||||
if (jy < jm) break;
|
||||
leapJ += div(jump, 33) * 8 + div(mod(jump, 33), 4);
|
||||
jp = jm;
|
||||
}
|
||||
const n = jy - jp;
|
||||
leapJ += div(n, 33) * 8 + div(mod(n, 33) + 3, 4);
|
||||
if (mod(jump, 33) === 4 && jump - n === 4) leapJ += 1;
|
||||
const leapG = div(gy, 4) - div((div(gy, 100) + 1) * 3, 4) - 150;
|
||||
return { gy, march: 20 + leapJ - leapG };
|
||||
}
|
||||
|
||||
function g2d(gy: number, gm: number, gd: number) {
|
||||
const d =
|
||||
div((gy + div(gm - 8, 6) + 100100) * 1461, 4) +
|
||||
div(153 * mod(gm + 9, 12) + 2, 5) +
|
||||
gd - 34840408;
|
||||
return d - div(div(gy + 100100 + div(gm - 8, 6), 100) * 3, 4) + 752;
|
||||
}
|
||||
|
||||
function d2g(jdn: number) {
|
||||
let j = 4 * jdn + 139361631;
|
||||
j = j + div(div(4 * jdn + 183187720, 146097) * 3, 4) * 4 - 3908;
|
||||
const i = div(mod(j, 1461), 4) * 5 + 308;
|
||||
const gd = div(mod(i, 153), 5) + 1;
|
||||
const gm = mod(div(i, 153), 12) + 1;
|
||||
const gy = div(j, 1461) - 100100 + div(8 - gm, 6);
|
||||
return { gy, gm, gd };
|
||||
}
|
||||
|
||||
/** Jalali y/m/d -> Gregorian y/m/d. */
|
||||
export function jalaliToGregorian(jy: number, jm: number, jd: number) {
|
||||
const r = jalCal(jy);
|
||||
const jdn = g2d(r.gy, 3, r.march) + (jm - 1) * 31 - div(jm, 7) * (jm - 7) + jd - 1;
|
||||
return d2g(jdn);
|
||||
}
|
||||
|
||||
/**
|
||||
* A free-text Jalali date ("1403/5/12", "۱۴۰۳-۰۵-۱۲") -> UTC midnight of the
|
||||
* same day, or null when it does not parse. Callers keep the raw text too.
|
||||
*/
|
||||
export function jalaliDate(v: unknown): Date | null {
|
||||
const s = latinDigits(String(v ?? '')).trim();
|
||||
const m = /^(1[34]\d{2})\D(\d{1,2})\D(\d{1,2})$/.exec(s);
|
||||
if (!m) return null;
|
||||
const jm = +m[2];
|
||||
const jd = +m[3];
|
||||
if (jm < 1 || jm > 12 || jd < 1 || jd > 31) return null;
|
||||
const g = jalaliToGregorian(+m[1], jm, jd);
|
||||
return new Date(Date.UTC(g.gy, g.gm - 1, g.gd));
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
/**
|
||||
* Catalogue: brands, categories, products, variants and product images.
|
||||
* Rules: docs/DATA-MIGRATION-MAP.md §9, §10.5.
|
||||
*
|
||||
* Which rows: every live product/variant, PLUS every soft-deleted variant (and
|
||||
* its product) that a live order line still points at. 473 of the 610 live
|
||||
* order lines reference a deleted variant; OrderItem.productVariantId is
|
||||
* required, so without those the order history would lose most of its lines.
|
||||
* They come over with isActive = false, so the shop never shows them.
|
||||
*
|
||||
* ProductVariant.imageId is never written (PROTECTED.md §B), and no
|
||||
* ProductImage is ever deleted: the variant FK is onDelete SetNull, so a
|
||||
* delete-and-recreate would silently clear every admin-picked variant image.
|
||||
*/
|
||||
import { ProductImageRole, Prisma } from '@prisma/client';
|
||||
import { fillEmpty, upsert, type Ctx } from '../lib/context';
|
||||
import { grams, int, isZero, matchKey, percent, tehran, text } from '../lib/normalize';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
const LIVE_ORDER_LINES = `
|
||||
SELECT oi.variant_id FROM order_items oi
|
||||
JOIN orders o ON o.id = oi.order_id AND o.deleted_at IS NULL
|
||||
WHERE oi.deleted_at IS NULL AND oi.variant_id IS NOT NULL`;
|
||||
|
||||
export async function brands(ctx: Ctx) {
|
||||
const S = 'brands';
|
||||
const rows = await ctx.q<Row>(
|
||||
`SELECT * FROM product_brand WHERE deleted_at IS NULL
|
||||
OR id IN (SELECT brand_id FROM product WHERE brand_id IS NOT NULL)`,
|
||||
);
|
||||
const existing = await ctx.db.brand.findMany();
|
||||
for (const r of rows) {
|
||||
const title = text(r.title);
|
||||
if (!title) continue;
|
||||
const res = await upsert(ctx, 'brand', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.brand.findUnique({ where: { id } })),
|
||||
find: async () => existing.find((b) => matchKey(b.title) === matchKey(title)) ?? null,
|
||||
create: () => ctx.db.brand.create({ data: { title } }),
|
||||
update: async (id, how) => {
|
||||
if (how === 'created') await ctx.db.brand.update({ where: { id }, data: { title } });
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, res.isNew ? 'created' : 'matched/updated');
|
||||
}
|
||||
}
|
||||
|
||||
export async function categories(ctx: Ctx) {
|
||||
const S = 'categories';
|
||||
const rows = await ctx.q<Row>('SELECT * FROM category_collection WHERE deleted_at IS NULL');
|
||||
const existing = await ctx.db.category.findMany();
|
||||
|
||||
for (const r of rows) {
|
||||
const title = text(r.title);
|
||||
if (!title) continue;
|
||||
const type = int(r.type) ?? 1;
|
||||
// The port's mapping (admin-categories.service.ts:75-80): image, icon,
|
||||
// meta -> metaTag, body_html -> description.
|
||||
const data = {
|
||||
title,
|
||||
type,
|
||||
imageUrl: await ctx.imageUrl(r.image_id ?? r.image_id_id, S),
|
||||
iconUrl: await ctx.imageUrl(r.icon_id, S),
|
||||
metaTag: text(r.meta),
|
||||
description: text(r.body_html),
|
||||
};
|
||||
const res = await upsert(ctx, 'category', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.category.findUnique({ where: { id } })),
|
||||
// Same title in the same tree (site / app) is the same category.
|
||||
find: async () => existing.find((c) => matchKey(c.title) === matchKey(title) && c.type === type) ?? null,
|
||||
create: () => ctx.db.category.create({ data }),
|
||||
update: async (id, how) => {
|
||||
if (how === 'created') {
|
||||
await ctx.db.category.update({ where: { id }, data });
|
||||
} else {
|
||||
const cur = await ctx.db.category.findUniqueOrThrow({ where: { id } });
|
||||
const patch = fillEmpty(cur, data);
|
||||
if (Object.keys(patch).length) await ctx.db.category.update({ where: { id }, data: patch });
|
||||
}
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, res.isNew ? 'created' : res.how === 'matched' ? 'matched existing' : 'updated');
|
||||
}
|
||||
|
||||
// Second pass, once every category has an id: the parent links.
|
||||
for (const r of rows) {
|
||||
const id = ctx.map.get('category', r.id);
|
||||
if (!id || r.parent_id_id === null) continue;
|
||||
const parentId = ctx.map.get('category', r.parent_id_id);
|
||||
if (!parentId) {
|
||||
ctx.report.count(S, 'parent not migrated (deleted in legacy) — left at top level');
|
||||
continue;
|
||||
}
|
||||
if (ctx.map.how('category', r.id) !== 'matched') {
|
||||
await ctx.db.category.update({ where: { id }, data: { parentId } });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function products(ctx: Ctx) {
|
||||
const S = 'products';
|
||||
const rows = await ctx.q<Row>(
|
||||
`SELECT * FROM product
|
||||
WHERE deleted_at IS NULL
|
||||
OR id IN (SELECT v.product_id_id FROM products_productvarient v WHERE v.id IN (${LIVE_ORDER_LINES}))`,
|
||||
);
|
||||
|
||||
// Legacy links products to categories many-to-many (category_collect) and
|
||||
// keeps TWO trees: type 1 = site, type 2 = app (admin-categories.service.ts:12).
|
||||
// Every product with more than one category (1,250) is simply in both trees.
|
||||
// The target keeps one categoryId, which the app shows and links to
|
||||
// (user-app-v2 SingleProduct.vue:228), so the APP category is the one kept;
|
||||
// the site one only when the product has no app category.
|
||||
const links = await ctx.q<Row>(
|
||||
`SELECT cc.product_id_id AS pid, cc.collection_id_id AS cid, c.type AS ctype FROM category_collect cc
|
||||
JOIN category_collection c ON c.id = cc.collection_id_id AND c.deleted_at IS NULL
|
||||
WHERE cc.deleted_at IS NULL ORDER BY cc.position, cc.id`,
|
||||
);
|
||||
const chosenCategory = new Map<string, { cid: string; app: boolean }>();
|
||||
const categoryCount = new Map<string, number>();
|
||||
for (const l of links) {
|
||||
const pid = String(l.pid);
|
||||
const app = int(l.ctype) === 2;
|
||||
categoryCount.set(pid, (categoryCount.get(pid) ?? 0) + 1);
|
||||
const cur = chosenCategory.get(pid);
|
||||
if (!cur || (app && !cur.app)) chosenCategory.set(pid, { cid: String(l.cid), app });
|
||||
}
|
||||
|
||||
for (const r of rows) {
|
||||
const title = text(r.title) ?? `محصول ${String(r.id)}`;
|
||||
const deleted = r.deleted_at !== null;
|
||||
const code = text(r.product_code);
|
||||
const data = {
|
||||
title,
|
||||
description: text(r.body_html),
|
||||
categoryId: ctx.map.get('category', chosenCategory.get(String(r.id))?.cid) ?? null,
|
||||
brandId: ctx.map.get('brand', r.brand_id) ?? null,
|
||||
productCode: code,
|
||||
showType: int(r.show_type) ?? 3,
|
||||
isActive: !deleted && int(r.is_active) === 1,
|
||||
};
|
||||
const chosen = chosenCategory.get(String(r.id));
|
||||
if (!chosen) ctx.report.count(S, 'no live category');
|
||||
else if ((categoryCount.get(String(r.id)) ?? 0) > 1) ctx.report.count(S, `in several legacy categories — ${chosen.app ? 'app' : 'site'} category kept`);
|
||||
if (int(r.disabled) === 1) ctx.report.count(S, 'legacy `disabled` = 1 (not represented; port ignores it too)');
|
||||
|
||||
const res = await upsert(ctx, 'product', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.product.findUnique({ where: { id } })),
|
||||
find: async () => (code ? ctx.db.product.findUnique({ where: { productCode: code }, select: { id: true } }) : null),
|
||||
create: () => ctx.db.product.create({ data: { ...data, createdAt: tehran(r.created_at) ?? undefined } }),
|
||||
update: async (id, how) => {
|
||||
// Never accountingStock* (D27): not in `data`.
|
||||
if (how === 'created') {
|
||||
await ctx.db.product.update({ where: { id }, data });
|
||||
} else {
|
||||
const cur = await ctx.db.product.findUniqueOrThrow({ where: { id } });
|
||||
const patch = fillEmpty(cur, data);
|
||||
if (Object.keys(patch).length) await ctx.db.product.update({ where: { id }, data: patch });
|
||||
}
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, `${res.isNew ? 'created' : res.how === 'matched' ? 'matched existing' : 'updated'}${deleted ? ' (deleted in legacy, kept inactive for order history)' : ''}`);
|
||||
if (res.how !== 'matched') await productImages(ctx, r, res.id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The port's image roles (admin-products.service.ts:185-188):
|
||||
* indicator_id -> FEATURED, mobile_pic -> FEATURED_MOBILE; the gallery is
|
||||
* products_productimage. Only for products the import created — a product the
|
||||
* target already had keeps exactly the images it has.
|
||||
*/
|
||||
async function productImages(ctx: Ctx, p: Row, productId: string) {
|
||||
const S = 'product images';
|
||||
const add = async (key: string, imageId: unknown, role: ProductImageRole, sortOrder: number) => {
|
||||
// Resolved even when the row exists, because resolving is what copies the
|
||||
// file: a first run without --images followed by one with it must still
|
||||
// bring the files over.
|
||||
const url = await ctx.imageUrl(imageId, S);
|
||||
if (!url || ctx.map.get('pimage', key)) return;
|
||||
const img = await ctx.db.productImage.create({ data: { productId, url, role, sortOrder } });
|
||||
await ctx.map.set('pimage', key, img.id, 'created');
|
||||
ctx.report.count(S, role);
|
||||
};
|
||||
await add(`featured:${String(p.id)}`, p.indicator_id_id, ProductImageRole.FEATURED, 0);
|
||||
await add(`mobile:${String(p.id)}`, p.mobile_pic_id, ProductImageRole.FEATURED_MOBILE, 0);
|
||||
const gallery = await ctx.q<Row>(
|
||||
'SELECT id, image_id FROM products_productimage WHERE deleted_at IS NULL AND product_id = ? ORDER BY id',
|
||||
[p.id],
|
||||
);
|
||||
let i = 1;
|
||||
for (const g of gallery) await add(`gallery:${String(g.id)}`, g.image_id, ProductImageRole.GALLERY, i++);
|
||||
}
|
||||
|
||||
export async function variants(ctx: Ctx) {
|
||||
const S = 'variants';
|
||||
const rows = await ctx.q<Row>(
|
||||
`SELECT * FROM products_productvarient
|
||||
WHERE deleted_at IS NULL OR id IN (${LIVE_ORDER_LINES})`,
|
||||
);
|
||||
for (const r of rows) {
|
||||
const productId = ctx.map.get('product', r.product_id_id);
|
||||
if (!productId) {
|
||||
ctx.report.count(S, 'skipped: product not migrated');
|
||||
continue;
|
||||
}
|
||||
const deleted = r.deleted_at !== null;
|
||||
let sku = text(r.barcode);
|
||||
if (sku) {
|
||||
const clash = await ctx.db.productVariant.findUnique({ where: { sku }, select: { id: true } });
|
||||
if (clash && clash.id !== ctx.map.get('variant', r.id)) {
|
||||
ctx.report.count(S, 'barcode already used by another variant — sku left empty');
|
||||
sku = null;
|
||||
}
|
||||
}
|
||||
// `Inventory` (capital I in the source column, §9) is legacy's stock count;
|
||||
// `qty` is what the port reads, so that is what is carried.
|
||||
const data: Prisma.ProductVariantUncheckedUpdateInput = {
|
||||
productId,
|
||||
title: text(r.title) ?? '-',
|
||||
sku,
|
||||
rashWeightGrams: grams(r.grams),
|
||||
defaultWagePercent: percent(r.percentage_pay),
|
||||
qty: int(r.qty) ?? 0,
|
||||
isPreOrder: int(r.is_pre_order) === 1,
|
||||
isActive: !deleted && int(r.is_active) === 1,
|
||||
// imageId: deliberately absent — PROTECTED.md §B.
|
||||
};
|
||||
if (!isZero(r.rial_pay)) ctx.report.count(S, 'rial charge (rial_pay) not carried — no target field');
|
||||
|
||||
const res = await upsert(ctx, 'variant', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.productVariant.findUnique({ where: { id } })),
|
||||
find: async () => (sku ? ctx.db.productVariant.findUnique({ where: { sku }, select: { id: true } }) : null),
|
||||
create: () => ctx.db.productVariant.create({ data: data as Prisma.ProductVariantUncheckedCreateInput }),
|
||||
update: async (id, how) => {
|
||||
if (how === 'created') await ctx.db.productVariant.update({ where: { id }, data });
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, `${res.isNew ? 'created' : res.how === 'matched' ? 'matched existing (left as is)' : 'updated'}${deleted ? ' (deleted in legacy, inactive)' : ''}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
/**
|
||||
* Orders, the ledger, favourites and custom orders.
|
||||
* Rules: docs/DATA-MIGRATION-MAP.md §7, §8, §10, §10.7.
|
||||
*/
|
||||
import {
|
||||
LedgerCurrency,
|
||||
LedgerDirection,
|
||||
LedgerSourceType,
|
||||
OrderChannel,
|
||||
OrderStatus,
|
||||
PreOrderStatus,
|
||||
Prisma,
|
||||
} from '@prisma/client';
|
||||
import { upsert, type Ctx } from '../lib/context';
|
||||
import { grams, int, jalaliDate, percent, rial, tehran, text, toNumber } from '../lib/normalize';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const D = Prisma.Decimal;
|
||||
|
||||
/** Order::$STS (Order.php:66-74). 7 «کنسل شده» is commented out in legacy and absent from the data. */
|
||||
const ORDER_STATUS: Record<number, OrderStatus> = {
|
||||
0: OrderStatus.SUSPENDED,
|
||||
1: OrderStatus.PLACED,
|
||||
2: OrderStatus.ADMIN_APPROVED,
|
||||
3: OrderStatus.SOURCING,
|
||||
4: OrderStatus.PREPARING,
|
||||
5: OrderStatus.DELIVERED_TO_AGENT,
|
||||
6: OrderStatus.DELIVERED_TO_CUSTOMER,
|
||||
};
|
||||
|
||||
/* ───────────── orders ───────────── */
|
||||
|
||||
export async function orders(ctx: Ctx) {
|
||||
const S = 'orders';
|
||||
// Wholesale only. Retail `orders_orders` is deferred by the owner (§7.2) and
|
||||
// must not be mapped with this status table: its 7 means «تحویل مشتری».
|
||||
const rows = await ctx.q<Row>('SELECT * FROM orders WHERE deleted_at IS NULL');
|
||||
for (const r of rows) {
|
||||
const customerId = ctx.map.get('customer', r.customer_id);
|
||||
if (!customerId) {
|
||||
ctx.report.count(S, 'skipped: customer not migrated');
|
||||
ctx.report.note(S, `legacy order #${String(r.id)} skipped: its customer #${String(r.customer_id)} was not migrated (status ${String(r.sts)})`);
|
||||
continue;
|
||||
}
|
||||
const sts = int(r.sts);
|
||||
const status = sts !== null ? ORDER_STATUS[sts] : undefined;
|
||||
if (!status) {
|
||||
ctx.report.count(S, 'skipped: unknown status');
|
||||
ctx.report.note(S, `legacy order #${String(r.id)} has status ${String(r.sts)}, which has no mapping`);
|
||||
continue;
|
||||
}
|
||||
const orderNumber = `H-${String(r.id)}`;
|
||||
const data = {
|
||||
customerId,
|
||||
channel: OrderChannel.WHOLESALE,
|
||||
status,
|
||||
// `input` is what legacy debits (CustomerController::updateRemain) and
|
||||
// equals `w` on all 300 live orders; `wage` is the making-charge part of it.
|
||||
totalGoldWeightGrams: grams(r.input),
|
||||
wageWeightGrams: grams(r.wage),
|
||||
flatRialCharge: rial(r.rial_input),
|
||||
// Legacy 0 «معلق» is the over-credit-limit hold.
|
||||
isSuspendedOverCreditLimit: sts === 0,
|
||||
// Legacy records no delivery time; the last change of a delivered order is the best available.
|
||||
deliveredAt: sts === 6 ? tehran(r.updated_at) : null,
|
||||
};
|
||||
const res = await upsert(ctx, 'order', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.order.findUnique({ where: { id } })),
|
||||
find: () => ctx.db.order.findUnique({ where: { orderNumber }, select: { id: true } }),
|
||||
create: () => ctx.db.order.create({ data: { ...data, orderNumber, createdAt: tehran(r.created_at) ?? undefined } }),
|
||||
update: async (id, how) => {
|
||||
if (how === 'created') await ctx.db.order.update({ where: { id }, data });
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, `${res.isNew ? 'created' : 'updated'} — ${status}`);
|
||||
if (r.reagent_id !== null) ctx.report.count(S, 'placing expert (orders.reagent_id) not carried — no target field');
|
||||
}
|
||||
await orderItems(ctx);
|
||||
}
|
||||
|
||||
async function orderItems(ctx: Ctx) {
|
||||
const S = 'order lines';
|
||||
const rows = await ctx.q<Row>(
|
||||
`SELECT oi.* FROM order_items oi JOIN orders o ON o.id = oi.order_id AND o.deleted_at IS NULL
|
||||
WHERE oi.deleted_at IS NULL`,
|
||||
);
|
||||
for (const r of rows) {
|
||||
const orderId = ctx.map.get('order', r.order_id);
|
||||
if (!orderId) continue;
|
||||
const productVariantId = ctx.map.get('variant', r.variant_id);
|
||||
if (!productVariantId) {
|
||||
ctx.report.count(S, 'skipped: variant not migrated');
|
||||
ctx.report.note(S, `legacy order line #${String(r.id)} (order #${String(r.order_id)}) lost: variant #${String(r.variant_id)} not found`);
|
||||
continue;
|
||||
}
|
||||
const data = {
|
||||
orderId,
|
||||
productVariantId,
|
||||
quantity: int(r.qty) ?? 1,
|
||||
rashWeightGramsSnapshot: grams(r.rash_weight),
|
||||
wagePercentSnapshot: percent(r.percent),
|
||||
discountPercentSnapshot: percent(r.discount),
|
||||
computedWeightGrams: grams(r.w),
|
||||
flatRialCharge: rial(r.rial_pay),
|
||||
};
|
||||
const res = await upsert(ctx, 'orderitem', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.orderItem.findUnique({ where: { id } })),
|
||||
find: async () => null,
|
||||
create: () => ctx.db.orderItem.create({ data }),
|
||||
update: async (id) => {
|
||||
await ctx.db.orderItem.update({ where: { id }, data });
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, res.isNew ? 'created' : 'updated');
|
||||
// §7.4: the target keeps one snapshot; legacy's audit pair is lost.
|
||||
if (toNumber(r.original_rash_weight) !== toNumber(r.rash_weight) || toNumber(r.original_percent) !== toNumber(r.percent)) {
|
||||
ctx.report.count(S, 'weight or wage edited after ordering (original_* not carried)');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ───────────── ledger ───────────── */
|
||||
|
||||
/** Cash::$TYPES (Major/Cash.php:56-62). Type 9 «سفارش» is handled from `orders`. */
|
||||
const CASH_SOURCE: Record<number, LedgerSourceType> = {
|
||||
1: LedgerSourceType.REPAYMENT_MELTED_GOLD,
|
||||
2: LedgerSourceType.REPAYMENT_TRANSFER,
|
||||
3: LedgerSourceType.REPAYMENT_CHEQUE,
|
||||
4: LedgerSourceType.REPAYMENT_CASH,
|
||||
};
|
||||
|
||||
/** Grams per mesghal. Legacy's price_per_gram is per mesghal (CashController.php:68). */
|
||||
const MESGHAL = 4.331802;
|
||||
|
||||
/**
|
||||
* Legacy debt is COMPUTED, never posted (CustomerController::updateRemain):
|
||||
*
|
||||
* remain = Σ orders.input (sts > 4) − Σ cashes.value (confirmed, type 1–4)
|
||||
* rial_remain = Σ orders.rial_input (sts > 4)
|
||||
*
|
||||
* so the ledger is rebuilt from exactly those rows. Recomputing that formula on
|
||||
* the 2026-10-04 dump reproduces the stored balance for 1,590 of 1,591
|
||||
* customers to 0.0001 g (§10.7). Consequences:
|
||||
* - `cashes` type 9 («سفارش») is NOT carried: it mirrors an order, and the
|
||||
* order already posts that debt. Both would count it twice.
|
||||
* - Rials paid (types 3/4 `price`) never reduce rial debt; a cash payment is
|
||||
* converted to gold (`value`) and reduces the gold debt. Kept as is.
|
||||
* - A balance the records cannot explain (customer #125: −9.8951 g, set by
|
||||
* hand after its only document was deleted) is carried as an explicit
|
||||
* ADJUSTMENT entry, so the customer sees the same number (owner, 2026-10-07).
|
||||
*/
|
||||
export async function ledger(ctx: Ctx) {
|
||||
const S = 'ledger';
|
||||
const entry = async (key: string, data: Prisma.LedgerEntryUncheckedCreateInput) => {
|
||||
const res = await upsert(ctx, 'ledger', key, {
|
||||
exists: async (id) => !!(await ctx.db.ledgerEntry.findUnique({ where: { id } })),
|
||||
find: async () => null,
|
||||
create: () => ctx.db.ledgerEntry.create({ data }),
|
||||
update: async (id) => {
|
||||
await ctx.db.ledgerEntry.update({ where: { id }, data });
|
||||
},
|
||||
});
|
||||
return res.id;
|
||||
};
|
||||
const signed = (amount: number) => ({
|
||||
direction: amount >= 0 ? LedgerDirection.DEBIT : LedgerDirection.CREDIT,
|
||||
amount: grams(Math.abs(amount)),
|
||||
});
|
||||
|
||||
// Orders delivered to the agent or the customer carry the debt.
|
||||
const delivered = await ctx.q<Row>('SELECT * FROM orders WHERE deleted_at IS NULL AND sts > 4');
|
||||
for (const o of delivered) {
|
||||
const customerId = ctx.map.get('customer', o.customer_id);
|
||||
const orderId = ctx.map.get('order', o.id);
|
||||
if (!customerId || !orderId) continue;
|
||||
const at = tehran(o.updated_at) ?? undefined;
|
||||
if (toNumber(o.input) !== 0) {
|
||||
await entry(`order:${String(o.id)}:gold`, {
|
||||
customerId, orderId, ...signed(toNumber(o.input)),
|
||||
currency: LedgerCurrency.GOLD_GRAM, sourceType: LedgerSourceType.ORDER_STOCK,
|
||||
confirmed: true, confirmedAt: at, createdAt: at,
|
||||
note: 'بدهی وزنی سفارش — انتقال از سیستم قدیم',
|
||||
});
|
||||
ctx.report.count(S, 'order debt (gold)');
|
||||
}
|
||||
if (toNumber(o.rial_input) !== 0) {
|
||||
const amt = toNumber(o.rial_input);
|
||||
await entry(`order:${String(o.id)}:rial`, {
|
||||
customerId, orderId,
|
||||
direction: amt >= 0 ? LedgerDirection.DEBIT : LedgerDirection.CREDIT,
|
||||
amount: rial(Math.abs(amt)),
|
||||
currency: LedgerCurrency.RIAL, sourceType: LedgerSourceType.ORDER_STOCK,
|
||||
confirmed: true, confirmedAt: at, createdAt: at,
|
||||
note: 'بدهی ریالی سفارش — انتقال از سیستم قدیم',
|
||||
});
|
||||
ctx.report.count(S, 'order debt (rial)');
|
||||
}
|
||||
}
|
||||
|
||||
const cashes = await ctx.q<Row>('SELECT * FROM cashes WHERE deleted_at IS NULL');
|
||||
for (const c of cashes) {
|
||||
const type = int(c.type);
|
||||
if (type === 9) {
|
||||
ctx.report.count(S, 'cash type 9 (order mirror) skipped — debt comes from the order');
|
||||
continue;
|
||||
}
|
||||
const sourceType = type !== null ? CASH_SOURCE[type] : undefined;
|
||||
if (!sourceType) {
|
||||
ctx.report.count(S, 'skipped: unknown document type');
|
||||
ctx.report.note(S, `legacy document #${String(c.id)} has type ${String(c.type)}`);
|
||||
continue;
|
||||
}
|
||||
const customerId = ctx.map.get('customer', c.customer_id);
|
||||
if (!customerId) {
|
||||
ctx.report.count(S, 'skipped: customer not migrated');
|
||||
continue;
|
||||
}
|
||||
// A repayment is a CREDIT; a negative `value` (4 transfers) is a debit.
|
||||
const value = toNumber(c.value);
|
||||
const received = jalaliDate(c.recive_date);
|
||||
const confirmed = int(c.confirmed) === 1;
|
||||
const ppg = toNumber(c.price_per_gram);
|
||||
await entry(`cash:${String(c.id)}`, {
|
||||
customerId,
|
||||
currency: LedgerCurrency.GOLD_GRAM,
|
||||
direction: value >= 0 ? LedgerDirection.CREDIT : LedgerDirection.DEBIT,
|
||||
amount: grams(Math.abs(value)),
|
||||
sourceType,
|
||||
confirmed,
|
||||
confirmedAt: confirmed ? tehran(c.updated_at) : null,
|
||||
postedByAdminUserId: ctx.map.get('admin', c.user_id) ?? null,
|
||||
karatPerMille: int(c.ayar),
|
||||
labName: text(c.lab),
|
||||
hallmark: text(c.ang),
|
||||
accountName: text(c.account_name),
|
||||
bankName: text(c.bank_name),
|
||||
transferTo: text(c.to),
|
||||
originalValue: c.original_value === null ? null : grams(c.original_value),
|
||||
priceRial: c.price === null ? null : rial(c.price),
|
||||
pricePerGramRialAtEntry: ppg ? rial(ppg / MESGHAL) : null,
|
||||
receivedAt: received,
|
||||
// The raw Jalali text is kept in the note when it did not parse.
|
||||
note: [text(c.title), text(c.note), !received && text(c.recive_date) ? `تاریخ دریافت: ${text(c.recive_date)}` : null]
|
||||
.filter(Boolean).join(' — ') || null,
|
||||
createdAt: tehran(c.created_at) ?? undefined,
|
||||
});
|
||||
ctx.report.count(S, `document ${sourceType}${confirmed ? '' : ' (unconfirmed — not in the balance)'}`);
|
||||
}
|
||||
|
||||
await balances(ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* Per migrated customer: compare what the import posted with the balance legacy
|
||||
* stored, carry any real difference as one ADJUSTMENT entry, then set the
|
||||
* cached balance to the sum of ALL confirmed entries (the rule every other
|
||||
* ledger path keeps: confirmed DEBIT adds, confirmed CREDIT subtracts).
|
||||
*/
|
||||
async function balances(ctx: Ctx) {
|
||||
const S = 'balances';
|
||||
const legacy = await ctx.q<Row>('SELECT id, remain, rial_remain FROM customers WHERE deleted_at IS NULL');
|
||||
const stored = new Map<string, { gold: number; rial: number }>();
|
||||
for (const r of legacy) {
|
||||
const target = ctx.map.get('customer', r.id);
|
||||
if (!target) continue;
|
||||
const cur = stored.get(target) ?? { gold: 0, rial: 0 };
|
||||
cur.gold += toNumber(r.remain);
|
||||
cur.rial += toNumber(r.rial_remain);
|
||||
stored.set(target, cur);
|
||||
}
|
||||
|
||||
const importedIds = new Set<string>();
|
||||
for (const row of await ctx.db.$queryRawUnsafe<{ target_id: string }[]>(
|
||||
`SELECT target_id FROM legacy_import.id_map WHERE entity = 'ledger' AND legacy_id NOT LIKE 'adjust:%'`,
|
||||
)) importedIds.add(row.target_id);
|
||||
|
||||
// Up to this a difference is the double → Decimal(14,4) rounding of §4, not a
|
||||
// real gap — inclusive: the first run posted two −0.0001 "adjustments" that
|
||||
// were nothing but rounding, and would have shown on those statements.
|
||||
const TOLERANCE = 0.0001;
|
||||
|
||||
for (const [customerId, want] of stored) {
|
||||
const entries = await ctx.db.ledgerEntry.findMany({ where: { customerId, confirmed: true } });
|
||||
const sum = (currency: LedgerCurrency, onlyImported: boolean) =>
|
||||
entries
|
||||
.filter((e) => e.currency === currency && (!onlyImported || importedIds.has(e.id)))
|
||||
.reduce((acc, e) => (e.direction === LedgerDirection.DEBIT ? acc.add(e.amount) : acc.sub(e.amount)), new D(0));
|
||||
|
||||
for (const [currency, wanted, label] of [
|
||||
[LedgerCurrency.GOLD_GRAM, want.gold, 'gold'],
|
||||
[LedgerCurrency.RIAL, want.rial, 'rial'],
|
||||
] as const) {
|
||||
const key = `adjust:${customerId}:${label}`;
|
||||
const diff = new D(wanted.toFixed(4)).sub(sum(currency, true));
|
||||
const existing = ctx.map.get('ledger', key);
|
||||
if (diff.abs().lte(TOLERANCE)) {
|
||||
if (!diff.isZero()) ctx.report.count(S, `rounding-only difference (${label}, ≤ ${TOLERANCE}) — no adjustment`);
|
||||
if (existing) {
|
||||
await ctx.db.ledgerEntry.deleteMany({ where: { id: existing } });
|
||||
await ctx.map.drop('ledger', key);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const data: Prisma.LedgerEntryUncheckedCreateInput = {
|
||||
customerId,
|
||||
currency,
|
||||
direction: diff.gt(0) ? LedgerDirection.DEBIT : LedgerDirection.CREDIT,
|
||||
amount: currency === LedgerCurrency.RIAL ? new D(diff.abs().toFixed(2)) : new D(diff.abs().toFixed(4)),
|
||||
sourceType: LedgerSourceType.ADJUSTMENT,
|
||||
confirmed: true,
|
||||
confirmedAt: new Date(),
|
||||
note: 'تراز انتقالی از سیستم قدیم — ماندهی ذخیرهشده در سیستم قدیم با اسناد قابل بازسازی نبود',
|
||||
};
|
||||
if (existing) await ctx.db.ledgerEntry.update({ where: { id: existing }, data });
|
||||
else {
|
||||
const created = await ctx.db.ledgerEntry.create({ data });
|
||||
await ctx.map.set('ledger', key, created.id, 'created');
|
||||
}
|
||||
ctx.report.count(S, `opening-balance adjustment (${label})`);
|
||||
ctx.report.note(S, `customer ${customerId}: ${label} adjustment ${diff.toString()} so the balance equals legacy's stored ${wanted.toFixed(4)}`);
|
||||
}
|
||||
|
||||
// The cached balance = Σ every confirmed entry, the target's own and the imported ones.
|
||||
const fresh = await ctx.db.ledgerEntry.findMany({ where: { customerId, confirmed: true } });
|
||||
const total = (currency: LedgerCurrency) =>
|
||||
fresh
|
||||
.filter((e) => e.currency === currency)
|
||||
.reduce((acc, e) => (e.direction === LedgerDirection.DEBIT ? acc.add(e.amount) : acc.sub(e.amount)), new D(0));
|
||||
const before = await ctx.db.customer.findUniqueOrThrow({ where: { id: customerId }, select: { goldDebtGrams: true, fiatDebtRial: true } });
|
||||
const gold = total(LedgerCurrency.GOLD_GRAM);
|
||||
const rialSum = total(LedgerCurrency.RIAL);
|
||||
if (!before.goldDebtGrams.eq(gold) || !before.fiatDebtRial.eq(rialSum)) {
|
||||
await ctx.db.customer.update({ where: { id: customerId }, data: { goldDebtGrams: gold, fiatDebtRial: rialSum } });
|
||||
ctx.report.count(S, 'cached balance set from the ledger');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ───────────── favourites ───────────── */
|
||||
|
||||
/**
|
||||
* The wholesale app's favourites are `major_favorites` (ApiMobileController
|
||||
* :73-465, model Major\Favorite) — 3,305 rows. `fav` (251) belongs to the
|
||||
* retail storefront (Customer\FavController, guard api-singleCustomer); its
|
||||
* customer_id points at retail logins, so it is deliberately NOT read here.
|
||||
*/
|
||||
export async function favorites(ctx: Ctx) {
|
||||
const S = 'favorites';
|
||||
const rows = await ctx.q<Row>(
|
||||
'SELECT customer_id, product_id, MIN(created_at) AS created_at FROM major_favorites WHERE deleted_at IS NULL GROUP BY customer_id, product_id',
|
||||
);
|
||||
const data: Prisma.CustomerFavoriteCreateManyInput[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const r of rows) {
|
||||
const customerId = ctx.map.get('customer', r.customer_id);
|
||||
const productId = ctx.map.get('product', r.product_id);
|
||||
if (!customerId) { ctx.report.count(S, 'skipped: customer not migrated'); continue; }
|
||||
if (!productId) { ctx.report.count(S, 'skipped: product deleted in legacy'); continue; }
|
||||
const k = `${customerId}|${productId}`;
|
||||
if (seen.has(k)) { ctx.report.count(S, 'duplicate collapsed (merged customers)'); continue; }
|
||||
seen.add(k);
|
||||
data.push({ customerId, productId, createdAt: tehran(r.created_at) ?? undefined });
|
||||
}
|
||||
const res = await ctx.db.customerFavorite.createMany({ data, skipDuplicates: true });
|
||||
ctx.report.count(S, 'created', res.count);
|
||||
ctx.report.count(S, 'already present', data.length - res.count);
|
||||
}
|
||||
|
||||
/* ───────────── custom orders ───────────── */
|
||||
|
||||
/** CustomOrder::$STS_EN (CustomOrder.php:41-47) maps one-to-one. */
|
||||
const PREORDER_STATUS: Record<number, PreOrderStatus> = {
|
||||
1: PreOrderStatus.PLACED,
|
||||
2: PreOrderStatus.ADMIN_APPROVED,
|
||||
3: PreOrderStatus.WORKSHOP_APPROVED,
|
||||
4: PreOrderStatus.READY_TO_SHIP,
|
||||
5: PreOrderStatus.DELIVERED,
|
||||
6: PreOrderStatus.CANCELLED,
|
||||
};
|
||||
|
||||
export async function preOrders(ctx: Ctx) {
|
||||
const S = 'custom orders';
|
||||
const rows = await ctx.q<Row>('SELECT * FROM custom_orders WHERE deleted_at IS NULL');
|
||||
for (const r of rows) {
|
||||
const customerId = ctx.map.get('customer', r.customer_id);
|
||||
if (!customerId) { ctx.report.count(S, 'skipped: customer not migrated'); continue; }
|
||||
const sumText = text(r.sum);
|
||||
const data = {
|
||||
customerId,
|
||||
cityId: ctx.map.get('city', r.city_id) ?? null,
|
||||
workshopId: ctx.map.get('workshop', r.workshop_id) ?? null,
|
||||
status: PREORDER_STATUS[int(r.sts) ?? 1] ?? PreOrderStatus.PLACED,
|
||||
designImageUrl: await ctx.imageUrl(r.file_id, S),
|
||||
colorName: text(r.color),
|
||||
sizeSpec: text(r.size),
|
||||
stoneColor: text(r.color_stone),
|
||||
minaColor: text(r.color_mina),
|
||||
estimatedWeightGrams: r.weight === null ? null : grams(r.weight),
|
||||
estimatedPriceRial: sumText && /^\d+(\.\d+)?$/.test(sumText) ? rial(sumText) : null,
|
||||
description: text(r.description),
|
||||
};
|
||||
const res = await upsert(ctx, 'preorder', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.preOrder.findUnique({ where: { id } })),
|
||||
find: async () => null,
|
||||
create: () => ctx.db.preOrder.create({ data: { ...data, createdAt: tehran(r.created_at) ?? undefined } }),
|
||||
update: async (id) => {
|
||||
await ctx.db.preOrder.update({ where: { id }, data });
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, res.isNew ? 'created' : 'updated');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
/**
|
||||
* People and places: cities, roles, branches, admin users, sales experts,
|
||||
* workshops and customers. Rules: docs/DATA-MIGRATION-MAP.md §2–§6, §10.4–§10.7.
|
||||
*/
|
||||
import { AdminRole, CustomerKind, Prisma, VerificationStep } from '@prisma/client';
|
||||
import { ALL_RIDS } from '../../../src/modules/auth/acl.constants';
|
||||
import { isPasswordHash, OTP_ONLY_PASSWORD_HASH } from '../../../src/modules/auth/password-hash';
|
||||
import { fillEmpty, upsert, type Ctx } from '../lib/context';
|
||||
import { birthday, grams, int, isZero, matchKey, mobile, percent, tehran, text } from '../lib/normalize';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
/** Owner ruling 2026-10-07 for the 7 legacy rejections, which recorded no reason. */
|
||||
export const LEGACY_REJECTION_REASON = 'رد شده در سیستم قدیم — فاقد شرح علت ثبتشده';
|
||||
|
||||
const fullNameOf = (r: Row) =>
|
||||
text(r.name) ?? text([text(r.fname), text(r.lname)].filter(Boolean).join(' ')) ?? String(r.mobile ?? '');
|
||||
|
||||
/** A legacy bcrypt hash keeps working; anything else becomes OTP-only (§10.4). */
|
||||
const passwordOf = (r: Row) => (isPasswordHash(r.password) ? String(r.password) : OTP_ONLY_PASSWORD_HASH);
|
||||
|
||||
/* ───────────── cities ───────────── */
|
||||
|
||||
export async function cities(ctx: Ctx) {
|
||||
const S = 'cities';
|
||||
// Live cities plus any deleted one a live customer still points at.
|
||||
const rows = await ctx.q<Row>(
|
||||
`SELECT id, title, parent, level, percent, percent_aux FROM cities
|
||||
WHERE deleted_at IS NULL
|
||||
OR id IN (SELECT city_id FROM customers WHERE deleted_at IS NULL AND city_id IS NOT NULL)`,
|
||||
);
|
||||
const all = new Map((await ctx.q<Row>('SELECT id, title, parent, level FROM cities')).map((r) => [String(r.id), r]));
|
||||
|
||||
// Legacy is a tree (country > province > city > district); the target City is
|
||||
// flat with a `province` label, taken from the level-1 ancestor.
|
||||
const provinceOf = (r: Row): string | null => {
|
||||
let cur: Row | undefined = r;
|
||||
for (let guard = 0; cur && guard < 10; guard++) {
|
||||
if (int(cur.level) === 1) return cur === r ? null : text(cur.title);
|
||||
cur = all.get(String(cur.parent));
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const existing = await ctx.db.city.findMany();
|
||||
const byKey = new Map(existing.map((c) => [matchKey(c.name), c.id]));
|
||||
|
||||
for (const r of rows) {
|
||||
const name = text(r.title);
|
||||
if (!name) {
|
||||
ctx.report.count(S, 'skipped: no title');
|
||||
continue;
|
||||
}
|
||||
const data = {
|
||||
name,
|
||||
province: provinceOf(r),
|
||||
percent: r.percent === null ? null : percent(r.percent),
|
||||
percentAux: r.percent_aux === null ? null : percent(r.percent_aux),
|
||||
};
|
||||
const res = await upsert(ctx, 'city', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.city.findUnique({ where: { id } })),
|
||||
find: async () => {
|
||||
const id = byKey.get(matchKey(name));
|
||||
return id ? { id } : null;
|
||||
},
|
||||
create: () => ctx.db.city.create({ data }),
|
||||
update: async (id, how) => {
|
||||
if (how === 'created') {
|
||||
await ctx.db.city.update({ where: { id }, data });
|
||||
} else {
|
||||
const cur = await ctx.db.city.findUniqueOrThrow({ where: { id } });
|
||||
const patch = fillEmpty(cur, data);
|
||||
if (Object.keys(patch).length) await ctx.db.city.update({ where: { id }, data: patch });
|
||||
}
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, res.isNew ? 'created' : res.how === 'matched' ? 'matched existing' : 'updated');
|
||||
byKey.set(matchKey(name), res.id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Target City id for an exact (normalised) name match, or null. */
|
||||
async function cityByName(ctx: Ctx, name: string | null): Promise<string | null> {
|
||||
if (!name) return null;
|
||||
const all = await ctx.db.city.findMany({ select: { id: true, name: true } });
|
||||
const key = matchKey(name);
|
||||
return all.find((c) => matchKey(c.name) === key)?.id ?? null;
|
||||
}
|
||||
|
||||
/* ───────────── roles & permissions ───────────── */
|
||||
|
||||
/**
|
||||
* Legacy 85 «مدیر» and target 85 «مدیر ارشد» are the same full-access role:
|
||||
* legacy 85 holds 173 permissions, more than any other type, and target 85 holds
|
||||
* every one of the 144 rids. Every other type is matched by TITLE, never by id —
|
||||
* legacy 86 is «حسابدار» but target 86 is «کارشناس فروش» (seed), so an id copy
|
||||
* would hand the accountant's 71 permissions to every sales expert.
|
||||
*/
|
||||
const SAME_ROLE: ReadonlyMap<number, number> = new Map([[85, 85]]);
|
||||
|
||||
/** AdminRole is a label only — every permission comes from the user type. */
|
||||
function adminRoleFor(legacyUt: number | null): AdminRole {
|
||||
if (legacyUt === 85 || legacyUt === 104 || legacyUt === 105) return AdminRole.SUPER_ADMIN; // مدیر · مدیر اصلی · مدیران
|
||||
if (legacyUt === 86) return AdminRole.ACCOUNTANT; // حسابدار
|
||||
return AdminRole.SYSTEM_APPROVER;
|
||||
}
|
||||
|
||||
export async function roles(ctx: Ctx) {
|
||||
const S = 'roles & permissions';
|
||||
// Legacy user types are config_statics rows (UserController.php:26:
|
||||
// `exists:config_statics,id`), titled by `val`.
|
||||
const types = await ctx.q<Row>(
|
||||
"SELECT id, val FROM config_statics WHERE `key` = '__list__ut' AND deleted_at IS NULL ORDER BY id",
|
||||
);
|
||||
const perms = await ctx.q<{ rid: string; ut: number }>('SELECT DISTINCT rid, ut FROM permission');
|
||||
const known = new Set<string>(ALL_RIDS as readonly string[]);
|
||||
const target = await ctx.db.userType.findMany();
|
||||
const byTitle = new Map(target.map((t) => [matchKey(t.title), t.id]));
|
||||
const takenIds = new Set(target.map((t) => t.id));
|
||||
|
||||
for (const t of types) {
|
||||
const legacyId = Number(t.id);
|
||||
const title = text(t.val) ?? `نقش ${legacyId}`;
|
||||
const mapped = ctx.map.get('ut', legacyId);
|
||||
let targetId: number;
|
||||
let created = false;
|
||||
|
||||
if (mapped) {
|
||||
targetId = Number(mapped);
|
||||
} else if (SAME_ROLE.has(legacyId) && takenIds.has(SAME_ROLE.get(legacyId)!)) {
|
||||
targetId = SAME_ROLE.get(legacyId)!;
|
||||
await ctx.map.set('ut', legacyId, String(targetId), 'matched');
|
||||
} else if (byTitle.has(matchKey(title))) {
|
||||
targetId = byTitle.get(matchKey(title))!;
|
||||
await ctx.map.set('ut', legacyId, String(targetId), 'matched');
|
||||
if (targetId !== legacyId) ctx.report.note(S, `legacy type ${legacyId} «${title}» → existing target type ${targetId} (same title, different number)`);
|
||||
} else {
|
||||
targetId = legacyId;
|
||||
if (takenIds.has(targetId)) {
|
||||
targetId = Math.max(...takenIds, ...types.map((x) => Number(x.id))) + 1;
|
||||
ctx.report.note(S, `legacy type ${legacyId} «${title}»: number taken by a different target role, created as ${targetId}`);
|
||||
}
|
||||
await ctx.db.userType.create({ data: { id: targetId, title } });
|
||||
takenIds.add(targetId);
|
||||
await ctx.map.set('ut', legacyId, String(targetId), 'created');
|
||||
created = true;
|
||||
}
|
||||
|
||||
const legacyRids = perms.filter((p) => Number(p.ut) === legacyId).map((p) => String(p.rid));
|
||||
if (created || ctx.map.how('ut', legacyId) === 'created') {
|
||||
// A role the import created gets legacy's permissions, limited to rids the
|
||||
// target ACL knows (the storefront's are out of scope, D13).
|
||||
const usable = legacyRids.filter((r) => known.has(r));
|
||||
const res = await ctx.db.permission.createMany({
|
||||
data: usable.map((rid) => ({ rid, userTypeId: targetId })),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
ctx.report.count(S, 'permissions copied', res.count);
|
||||
ctx.report.count(S, 'permissions dropped (rid unknown to the target ACL)', legacyRids.length - usable.length);
|
||||
ctx.report.count(S, 'types created');
|
||||
} else {
|
||||
// An existing target role keeps the target's permission set (D1: the
|
||||
// target's stricter auth stands). Nothing is added to it.
|
||||
ctx.report.count(S, 'types matched (permissions left as the target has them)');
|
||||
ctx.report.count(S, 'legacy permissions not applied to matched types', legacyRids.length);
|
||||
}
|
||||
}
|
||||
|
||||
const orphanUt = [...new Set(perms.map((p) => Number(p.ut)))].filter((u) => !types.some((t) => Number(t.id) === u));
|
||||
if (orphanUt.length) ctx.report.note(S, `permission rows for types with no config_statics row were skipped: ${orphanUt.join(', ')}`);
|
||||
}
|
||||
|
||||
/* ───────────── branches & workshops ───────────── */
|
||||
|
||||
export async function branches(ctx: Ctx) {
|
||||
const S = 'branches';
|
||||
const rows = await ctx.q<Row>('SELECT * FROM branches WHERE deleted_at IS NULL');
|
||||
const existing = await ctx.db.branch.findMany();
|
||||
for (const r of rows) {
|
||||
const name = text(r.name);
|
||||
if (!name) continue;
|
||||
const data = { name, address: text(r.address), phone: text(r.phone), isActive: int(r.is_active) !== 0 };
|
||||
const res = await upsert(ctx, 'branch', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.branch.findUnique({ where: { id } })),
|
||||
find: async () => existing.find((b) => matchKey(b.name) === matchKey(name)) ?? null,
|
||||
create: () => ctx.db.branch.create({ data }),
|
||||
update: async (id, how) => {
|
||||
if (how === 'created') await ctx.db.branch.update({ where: { id }, data });
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, res.isNew ? 'created' : 'matched/updated');
|
||||
}
|
||||
// branches.user_id names the branch's manager; the target Branch has no such field.
|
||||
ctx.report.note(S, 'branches.user_id (branch manager) has no target field and was not carried over.');
|
||||
}
|
||||
|
||||
export async function workshops(ctx: Ctx) {
|
||||
const S = 'workshops';
|
||||
const rows = await ctx.q<Row>('SELECT * FROM workshops WHERE deleted_at IS NULL');
|
||||
const existing = await ctx.db.workshop.findMany();
|
||||
for (const r of rows) {
|
||||
const name = text(r.name);
|
||||
if (!name) continue;
|
||||
const data = { name, address: text(r.address), phone: text(r.phone), isActive: int(r.is_active) !== 0 };
|
||||
const res = await upsert(ctx, 'workshop', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.workshop.findUnique({ where: { id } })),
|
||||
find: async () => existing.find((w) => matchKey(w.name) === matchKey(name)) ?? null,
|
||||
create: () => ctx.db.workshop.create({ data }),
|
||||
update: async (id, how) => {
|
||||
if (how === 'created') await ctx.db.workshop.update({ where: { id }, data });
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, res.isNew ? 'created' : 'matched/updated');
|
||||
}
|
||||
// Legacy Workshop::user() is belongsTo(Customer) (a type-5 customer); the
|
||||
// target supervisor is an AdminUser. No safe link exists, so none is guessed.
|
||||
ctx.report.note(S, 'supervisor not linked: legacy points at a customer (Workshop::user → Customer), the target expects an admin user.');
|
||||
}
|
||||
|
||||
/* ───────────── admin users (legacy `users`) ───────────── */
|
||||
|
||||
export async function admins(ctx: Ctx) {
|
||||
const S = 'admin users';
|
||||
const rows = await ctx.q<Row>('SELECT * FROM users WHERE deleted_at IS NULL');
|
||||
for (const r of rows) {
|
||||
const m = mobile(r.mobile);
|
||||
if (!m) {
|
||||
ctx.report.count(S, 'skipped: no mobile');
|
||||
continue;
|
||||
}
|
||||
const ut = int(r.ut);
|
||||
const userTypeId = ctx.map.get('ut', ut);
|
||||
const branchId = ctx.map.get('branch', r.branch_id) ?? null;
|
||||
const base = {
|
||||
fullName: fullNameOf(r),
|
||||
firstName: text(r.fname),
|
||||
lastName: text(r.lname),
|
||||
branchId,
|
||||
userTypeId: userTypeId ? Number(userTypeId) : null,
|
||||
};
|
||||
const res = await upsert(ctx, 'admin', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.adminUser.findUnique({ where: { id } })),
|
||||
find: () => ctx.db.adminUser.findUnique({ where: { mobile: m }, select: { id: true } }),
|
||||
create: () =>
|
||||
ctx.db.adminUser.create({
|
||||
data: {
|
||||
...base,
|
||||
mobile: m,
|
||||
passwordHash: passwordOf(r),
|
||||
role: adminRoleFor(ut),
|
||||
createdAt: tehran(r.created_at) ?? undefined,
|
||||
},
|
||||
}),
|
||||
update: async (id, how) => {
|
||||
if (how === 'created') {
|
||||
await ctx.db.adminUser.update({ where: { id }, data: base });
|
||||
} else {
|
||||
// An admin the target already has keeps its role, type, password and
|
||||
// branch; only empty name parts are filled.
|
||||
const cur = await ctx.db.adminUser.findUniqueOrThrow({ where: { id } });
|
||||
const patch = fillEmpty(cur, { firstName: base.firstName, lastName: base.lastName });
|
||||
if (Object.keys(patch).length) await ctx.db.adminUser.update({ where: { id }, data: patch });
|
||||
}
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, res.isNew ? 'created' : res.how === 'matched' ? 'matched existing (left as is)' : 'updated');
|
||||
if (res.isNew && !isPasswordHash(r.password)) ctx.report.count(S, 'created without a usable password');
|
||||
}
|
||||
}
|
||||
|
||||
/* ───────────── sales experts (legacy customers.type = 1) ───────────── */
|
||||
|
||||
/**
|
||||
* D17: an expert is an AdminUser (role SALES_EXPERT) with a SalesExpertProfile.
|
||||
* Their own orders and debt live on a separate trading Customer, created by the
|
||||
* customers step for the experts who have any (13 with orders, 14 with
|
||||
* documents in the 2026-10-04 dump).
|
||||
*
|
||||
* An expert whose mobile already belongs to an admin with another role (7 in
|
||||
* the dump, three of them full admins) is NOT demoted: the admin keeps its
|
||||
* role, and the expert's referrals point at that admin.
|
||||
*/
|
||||
export async function experts(ctx: Ctx) {
|
||||
const S = 'sales experts';
|
||||
const rows = await ctx.q<Row>('SELECT * FROM customers WHERE deleted_at IS NULL AND type = 1');
|
||||
|
||||
const existingExpertType = await ctx.db.adminUser.groupBy({
|
||||
by: ['userTypeId'],
|
||||
where: { role: AdminRole.SALES_EXPERT, userTypeId: { not: null } },
|
||||
_count: true,
|
||||
orderBy: { _count: { userTypeId: 'desc' } },
|
||||
});
|
||||
const expertType =
|
||||
existingExpertType[0]?.userTypeId ??
|
||||
(await ctx.db.userType.findMany()).find((t) => matchKey(t.title) === matchKey('کارشناس فروش'))?.id ??
|
||||
null;
|
||||
if (expertType === null) ctx.report.note(S, 'no target user type for sales experts found; created experts have no user type');
|
||||
|
||||
for (const r of rows) {
|
||||
const m = mobile(r.mobile);
|
||||
if (!m) {
|
||||
ctx.report.count(S, 'skipped: no mobile');
|
||||
continue;
|
||||
}
|
||||
const profile = {
|
||||
cityId: ctx.map.get('city', r.city_id) ?? null,
|
||||
gramLevel: grams(r.gram_level),
|
||||
phone: text(r.phone),
|
||||
nationalCode: text(r.ncode),
|
||||
};
|
||||
const owned = {
|
||||
fullName: fullNameOf(r),
|
||||
firstName: text(r.fname),
|
||||
lastName: text(r.lname),
|
||||
// AdminUser.wagePercent is "legacy Customer.percent" (schema).
|
||||
wagePercent: r.percent === null ? null : percent(r.percent),
|
||||
isActive: int(r.active) !== -1,
|
||||
avatarFileId: await ctx.uploadedFile(r.image_id, 'legacy-avatar', S),
|
||||
address: text(r.address),
|
||||
storeName: text(r.store_name),
|
||||
pasazhName: text(r.pasazh_name),
|
||||
memberCode: text(r.mcode),
|
||||
};
|
||||
const res = await upsert(ctx, 'expert', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.adminUser.findUnique({ where: { id } })),
|
||||
find: () => ctx.db.adminUser.findUnique({ where: { mobile: m }, select: { id: true } }),
|
||||
create: () =>
|
||||
ctx.db.adminUser.create({
|
||||
data: {
|
||||
...owned,
|
||||
mobile: m,
|
||||
passwordHash: passwordOf(r),
|
||||
role: AdminRole.SALES_EXPERT,
|
||||
userTypeId: expertType,
|
||||
createdAt: tehran(r.created_at) ?? undefined,
|
||||
},
|
||||
}),
|
||||
update: async (id, how) => {
|
||||
// A matched admin (the target's own, or a legacy `users` admin) is not
|
||||
// rewritten here; the role check below decides what else happens.
|
||||
if (how === 'created') await ctx.db.adminUser.update({ where: { id }, data: owned });
|
||||
},
|
||||
});
|
||||
|
||||
const admin = await ctx.db.adminUser.findUniqueOrThrow({
|
||||
where: { id: res.id },
|
||||
include: { salesExpertProfile: true },
|
||||
});
|
||||
if (admin.role !== AdminRole.SALES_EXPERT) {
|
||||
ctx.report.count(S, `mobile already an admin with role ${admin.role} — kept, not demoted`);
|
||||
ctx.report.note(S, `legacy expert #${String(r.id)} shares a mobile with admin role ${admin.role}; the admin was kept and referrals point to it.`);
|
||||
continue;
|
||||
}
|
||||
if (!admin.salesExpertProfile) {
|
||||
await ctx.db.salesExpertProfile.create({ data: { adminUserId: admin.id, ...profile } });
|
||||
} else if (res.how === 'created') {
|
||||
await ctx.db.salesExpertProfile.update({ where: { id: admin.salesExpertProfile.id }, data: profile });
|
||||
} else {
|
||||
const patch = fillEmpty(admin.salesExpertProfile, profile);
|
||||
if (Object.keys(patch).length) await ctx.db.salesExpertProfile.update({ where: { id: admin.salesExpertProfile.id }, data: patch });
|
||||
}
|
||||
ctx.report.count(S, res.isNew ? 'created' : res.how === 'matched' ? 'matched existing expert' : 'updated');
|
||||
}
|
||||
}
|
||||
|
||||
/* ───────────── customers ───────────── */
|
||||
|
||||
/** Legacy Customer::$TYPES (Customer.php:85-92); NULL predates sign-up's `type = 2`. */
|
||||
function kindFor(type: number | null): CustomerKind {
|
||||
switch (type) {
|
||||
case 3: return CustomerKind.WALK_IN_SHOPKEEPER;
|
||||
case 4: return CustomerKind.BANKER;
|
||||
case 5: return CustomerKind.WORKSHOP_SUPERVISOR;
|
||||
default: return CustomerKind.APP_SHOPKEEPER; // 2, 1 (expert's trading account), NULL
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Two 3-state legacy columns (1 pending, 2 accepted, 3 rejected; §5.5) to one
|
||||
* enum. Step one governs: a rejected step one closed the case in legacy
|
||||
* (`active = -1`), and a pending step one means review never got past it.
|
||||
*/
|
||||
function verificationFor(one: number | null, two: number | null): VerificationStep {
|
||||
if (one === 3 || (one !== 1 && two === 3)) return VerificationStep.REJECTED;
|
||||
if (one === 1) return VerificationStep.STEP_ONE_SUBMITTED;
|
||||
if (one === 2) return two === 2 ? VerificationStep.VERIFIED : VerificationStep.STEP_TWO_SUBMITTED;
|
||||
return VerificationStep.UNVERIFIED;
|
||||
}
|
||||
|
||||
export async function customers(ctx: Ctx) {
|
||||
const S = 'customers';
|
||||
const rows = await ctx.q<Row>('SELECT * FROM customers WHERE deleted_at IS NULL');
|
||||
const withOrders = new Set((await ctx.q<Row>('SELECT DISTINCT customer_id AS id FROM orders WHERE deleted_at IS NULL')).map((r) => String(r.id)));
|
||||
const withCash = new Set((await ctx.q<Row>('SELECT DISTINCT customer_id AS id FROM cashes WHERE deleted_at IS NULL')).map((r) => String(r.id)));
|
||||
const hasMoney = (r: Row) =>
|
||||
withOrders.has(String(r.id)) || withCash.has(String(r.id)) || !isZero(r.remain) || !isZero(r.rial_remain);
|
||||
|
||||
// An expert becomes a Customer only as a trading account, i.e. when they
|
||||
// have money of their own; otherwise they exist only as an AdminUser.
|
||||
const candidates = rows.filter((r) => int(r.type) !== 1 || hasMoney(r));
|
||||
ctx.report.count(S, 'experts without money (admin user only)', rows.length - candidates.length);
|
||||
|
||||
// Duplicate mobiles (27 groups, §10.4). The winner is the row with money
|
||||
// (never more than one in the dump), else the most recently updated.
|
||||
const groups = new Map<string, Row[]>();
|
||||
for (const r of candidates) {
|
||||
const m = mobile(r.mobile);
|
||||
if (!m) {
|
||||
// In the 2026-10-04 dump this is one test account whose "mobile" is the
|
||||
// word «تست»: it cannot log in under any system, so it is not invented a number.
|
||||
ctx.report.count(S, 'skipped: mobile has no digits');
|
||||
const own = withOrders.has(String(r.id)) || withCash.has(String(r.id));
|
||||
ctx.report.note(S, `legacy customer #${String(r.id)} skipped: its mobile contains no digits${own ? ' — its orders/documents are skipped with it' : ''}`);
|
||||
continue;
|
||||
}
|
||||
groups.set(m, [...(groups.get(m) ?? []), r]);
|
||||
}
|
||||
|
||||
for (const [m, group] of groups) {
|
||||
const ordered = [...group].sort(
|
||||
(a, b) =>
|
||||
Number(hasMoney(b)) - Number(hasMoney(a)) ||
|
||||
String(b.updated_at ?? '').localeCompare(String(a.updated_at ?? '')) ||
|
||||
Number(b.id) - Number(a.id),
|
||||
);
|
||||
const [r, ...losers] = ordered;
|
||||
const moneyLosers = losers.filter(hasMoney);
|
||||
if (moneyLosers.length) {
|
||||
// Not seen in the 2026-10-04 dump; if a fresh dump has it, the money of
|
||||
// two legacy rows lands on one customer and must be reviewed by hand.
|
||||
ctx.report.note(S, `⚠ duplicate mobile with money on several rows: legacy #${[r, ...moneyLosers].map((x) => String(x.id)).join(', #')} merged onto one customer — review`);
|
||||
}
|
||||
|
||||
const type = int(r.type);
|
||||
const step = verificationFor(int(r.sts_verify_step_one), int(r.sts_verify_step_two));
|
||||
const typedCity = text(r.new_city);
|
||||
// Sign-up forced city_id = 5 (تهران) on everyone (Major/CustomerController.php:21),
|
||||
// so when the customer typed a city, that text — not city_id 5 — is the truth.
|
||||
const cityId = typedCity
|
||||
? int(r.city_id) !== 5 && r.city_id !== null
|
||||
? ctx.map.get('city', r.city_id) ?? null
|
||||
: await cityByName(ctx, typedCity)
|
||||
: ctx.map.get('city', r.city_id) ?? null;
|
||||
|
||||
const owned = {
|
||||
firstName: text(r.fname),
|
||||
lastName: text(r.lname),
|
||||
nationalCode: text(r.ncode), // empty -> NULL; '' would collide under @unique (§10.4)
|
||||
cityId,
|
||||
cityNameRaw: typedCity,
|
||||
kind: kindFor(type),
|
||||
phone: text(r.phone),
|
||||
address: text(r.address),
|
||||
storeName: text(r.store_name),
|
||||
pasazhName: text(r.pasazh_name),
|
||||
zone: text(r.zone),
|
||||
memberCode: text(r.mcode),
|
||||
referredByAgentId: ctx.map.get('expert', r.reagent_id) ?? null,
|
||||
goldCreditLimitGrams: grams(r.gram_level),
|
||||
makingChargeOffsetPercent: percent(r.percent),
|
||||
verificationStep: step,
|
||||
verificationRejectionReason: step === VerificationStep.REJECTED ? LEGACY_REJECTION_REASON : null,
|
||||
nationalIdImageUrl: await ctx.imageUrl(r.ncode_image_id, S),
|
||||
businessLicenseUrl: await ctx.imageUrl(r.business_license_image_id, S),
|
||||
shopImageUrl: await ctx.imageUrl(r.shop_image_id, S),
|
||||
avatarFileId: await ctx.uploadedFile(r.image_id, 'legacy-avatar', S),
|
||||
birthDate: birthday(r.birth_date, r.created_at),
|
||||
canPlaceOrders: int(r.sts) !== -1,
|
||||
isActive: int(r.active) !== -1,
|
||||
isArchived: int(r.is_archive) === 1,
|
||||
};
|
||||
if (r.reagent_id !== null && !owned.referredByAgentId) ctx.report.count(S, 'referrer not mapped (not a migrated expert)');
|
||||
if (r.birth_date !== null && !owned.birthDate) ctx.report.count(S, 'birth date dropped (sign-up default or impossible)');
|
||||
|
||||
const res = await upsert(ctx, 'customer', r.id, {
|
||||
exists: async (id) => !!(await ctx.db.customer.findUnique({ where: { id } })),
|
||||
find: () => ctx.db.customer.findUnique({ where: { mobile: m }, select: { id: true } }),
|
||||
create: () =>
|
||||
ctx.db.customer.create({
|
||||
data: {
|
||||
...owned,
|
||||
fullName: fullNameOf(r),
|
||||
mobile: m,
|
||||
passwordHash: passwordOf(r),
|
||||
createdAt: tehran(r.created_at) ?? undefined,
|
||||
} satisfies Prisma.CustomerUncheckedCreateInput,
|
||||
}),
|
||||
update: async (id, how) => {
|
||||
if (how === 'created') {
|
||||
// Never the accounting* columns (D27, §10.5): not in `owned`.
|
||||
await ctx.db.customer.update({ where: { id }, data: owned });
|
||||
} else {
|
||||
const cur = await ctx.db.customer.findUniqueOrThrow({ where: { id } });
|
||||
const patch = fillEmpty(cur, owned);
|
||||
// The target's own verification state wins; a legacy rejection reason
|
||||
// on a customer the target shows as anything but REJECTED would contradict it.
|
||||
if (cur.verificationStep !== VerificationStep.REJECTED) delete patch.verificationRejectionReason;
|
||||
if (Object.keys(patch).length) await ctx.db.customer.update({ where: { id }, data: patch });
|
||||
}
|
||||
},
|
||||
});
|
||||
ctx.report.count(S, res.isNew ? 'created' : res.how === 'matched' ? 'matched existing (empty fields filled)' : 'updated');
|
||||
if (step === VerificationStep.REJECTED) ctx.report.count(S, 'rejected (legacy reason sentinel written)');
|
||||
|
||||
for (const l of losers) {
|
||||
await ctx.map.set('customer', l.id, res.id, 'merged');
|
||||
ctx.report.count(S, 'duplicate-mobile rows merged into the winner');
|
||||
}
|
||||
|
||||
// An expert's trading account (D17): link it from their profile.
|
||||
if (type === 1) {
|
||||
const adminId = ctx.map.get('expert', r.id);
|
||||
const profile = adminId ? await ctx.db.salesExpertProfile.findUnique({ where: { adminUserId: adminId } }) : null;
|
||||
if (profile && !profile.tradingCustomerId) {
|
||||
await ctx.db.salesExpertProfile.update({ where: { id: profile.id }, data: { tradingCustomerId: res.id } });
|
||||
ctx.report.count(S, 'expert trading accounts linked');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Reconciliation (GO-LIVE-PLAN §7): what legacy has vs what the target now
|
||||
* holds, with the tolerance of DATA-MIGRATION-MAP §4 instead of "zero
|
||||
* difference", which double → Decimal rounding makes impossible.
|
||||
*/
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type { Ctx } from '../lib/context';
|
||||
import { toNumber } from '../lib/normalize';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const TOLERANCE = new Prisma.Decimal('0.0001');
|
||||
|
||||
export async function reconcile(ctx: Ctx) {
|
||||
const S = 'reconciliation';
|
||||
|
||||
/* counts: legacy rows in scope vs ids mapped */
|
||||
const scope: [string, string, string][] = [
|
||||
['cities', 'city', `SELECT COUNT(*) n FROM cities WHERE deleted_at IS NULL`],
|
||||
['branches', 'branch', `SELECT COUNT(*) n FROM branches WHERE deleted_at IS NULL`],
|
||||
['workshops', 'workshop', `SELECT COUNT(*) n FROM workshops WHERE deleted_at IS NULL`],
|
||||
['admin users', 'admin', `SELECT COUNT(*) n FROM users WHERE deleted_at IS NULL`],
|
||||
['sales experts', 'expert', `SELECT COUNT(*) n FROM customers WHERE deleted_at IS NULL AND type = 1`],
|
||||
['live products', 'product', `SELECT COUNT(*) n FROM product WHERE deleted_at IS NULL`],
|
||||
['live variants', 'variant', `SELECT COUNT(*) n FROM products_productvarient WHERE deleted_at IS NULL`],
|
||||
['live orders', 'order', `SELECT COUNT(*) n FROM orders WHERE deleted_at IS NULL`],
|
||||
['custom orders', 'preorder', `SELECT COUNT(*) n FROM custom_orders WHERE deleted_at IS NULL`],
|
||||
];
|
||||
const rows: string[] = ['| | legacy | mapped |', '|---|---:|---:|'];
|
||||
for (const [label, entity, sql] of scope) {
|
||||
const [{ n }] = await ctx.q<{ n: number }>(sql);
|
||||
const [{ m }] = await ctx.db.$queryRawUnsafe<{ m: bigint }[]>(
|
||||
`SELECT COUNT(*) AS m FROM legacy_import.id_map WHERE entity = $1`, entity,
|
||||
);
|
||||
rows.push(`| ${label} | ${String(n)} | ${String(m)} |`);
|
||||
}
|
||||
ctx.report.note(S, `Counts (mapped may exceed legacy live rows where deleted rows were kept for order history):\n\n${rows.join('\n')}\n`);
|
||||
|
||||
/* balances: every migrated customer, legacy stored vs target cached */
|
||||
const legacy = await ctx.q<Row>('SELECT id, remain, rial_remain FROM customers WHERE deleted_at IS NULL');
|
||||
const want = new Map<string, { gold: number; rial: number }>();
|
||||
for (const r of legacy) {
|
||||
const id = ctx.map.get('customer', r.id);
|
||||
if (!id) continue;
|
||||
const w = want.get(id) ?? { gold: 0, rial: 0 };
|
||||
w.gold += toNumber(r.remain);
|
||||
w.rial += toNumber(r.rial_remain);
|
||||
want.set(id, w);
|
||||
}
|
||||
const targets = await ctx.db.customer.findMany({
|
||||
where: { id: { in: [...want.keys()] } },
|
||||
select: { id: true, goldDebtGrams: true, fiatDebtRial: true },
|
||||
});
|
||||
// Matched customers may carry target-native entries too, so only the
|
||||
// customers the import created are held to legacy's number.
|
||||
const created = new Set(
|
||||
(await ctx.db.$queryRawUnsafe<{ target_id: string }[]>(
|
||||
`SELECT DISTINCT target_id FROM legacy_import.id_map WHERE entity = 'customer' AND how = 'created'`,
|
||||
)).map((r) => r.target_id),
|
||||
);
|
||||
|
||||
let goldOk = 0, goldBad = 0, rialOk = 0, rialBad = 0;
|
||||
let legacyGold = new Prisma.Decimal(0), targetGold = new Prisma.Decimal(0);
|
||||
let legacyRial = new Prisma.Decimal(0), targetRial = new Prisma.Decimal(0);
|
||||
for (const t of targets) {
|
||||
if (!created.has(t.id)) continue;
|
||||
const w = want.get(t.id)!;
|
||||
const g = new Prisma.Decimal(w.gold.toFixed(4));
|
||||
const r = new Prisma.Decimal(w.rial.toFixed(2));
|
||||
legacyGold = legacyGold.add(g); targetGold = targetGold.add(t.goldDebtGrams);
|
||||
legacyRial = legacyRial.add(r); targetRial = targetRial.add(t.fiatDebtRial);
|
||||
if (g.sub(t.goldDebtGrams).abs().lte(TOLERANCE)) goldOk++;
|
||||
else { goldBad++; ctx.report.note(S, `⚠ gold balance differs for customer ${t.id}: legacy ${g.toString()} / target ${t.goldDebtGrams.toString()}`); }
|
||||
if (r.sub(t.fiatDebtRial).abs().lt(1)) rialOk++;
|
||||
else { rialBad++; ctx.report.note(S, `⚠ rial balance differs for customer ${t.id}: legacy ${r.toString()} / target ${t.fiatDebtRial.toString()}`); }
|
||||
}
|
||||
ctx.report.count(S, 'created customers — gold balance matches legacy (±0.0001 g)', goldOk);
|
||||
ctx.report.count(S, 'created customers — gold balance DIFFERS', goldBad);
|
||||
ctx.report.count(S, 'created customers — rial balance matches legacy (±1 rial)', rialOk);
|
||||
ctx.report.count(S, 'created customers — rial balance DIFFERS', rialBad);
|
||||
ctx.report.note(S, `Total gold debt (created customers): legacy ${legacyGold.toFixed(4)} g · target ${targetGold.toFixed(4)} g`);
|
||||
ctx.report.note(S, `Total rial debt (created customers): legacy ${legacyRial.toFixed(2)} · target ${targetRial.toFixed(2)}`);
|
||||
ctx.report.note(S, `Matched (pre-existing) customers are not held to legacy's number: they may carry target-native ledger entries. ${targets.length - created.size} of them; see the "balances" section for whose cached balance changed.`);
|
||||
|
||||
/* protected columns: the import must never have written them */
|
||||
const [{ n: imageIds }] = await ctx.db.$queryRawUnsafe<{ n: bigint }[]>(
|
||||
`SELECT COUNT(*) AS n FROM "ProductVariant" v
|
||||
JOIN legacy_import.id_map m ON m.entity = 'variant' AND m.target_id = v.id AND m.how = 'created'
|
||||
WHERE v."imageId" IS NOT NULL`,
|
||||
);
|
||||
ctx.report.note(S, `Imported variants with an imageId: ${String(imageIds)} (must be 0 — PROTECTED.md §B).`);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "../..",
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["./**/*.ts"]
|
||||
}
|
||||
@@ -116,7 +116,7 @@ async function main() {
|
||||
const customer = await prisma.customer.upsert({
|
||||
where: { mobile },
|
||||
update: {},
|
||||
create: { fullName: 'gold-bank smoke', firstName: 'gold-bank', lastName: 'smoke', mobile, nationalCode: mobile, passwordHash: '' },
|
||||
create: { fullName: 'gold-bank smoke', firstName: 'gold-bank', lastName: 'smoke', mobile, nationalCode: null, passwordHash: '!OTP_ONLY_NO_PASSWORD_LOGIN' },
|
||||
});
|
||||
await prisma.customer.update({ where: { id: customer.id }, data: { verificationStep: VerificationStep.STEP_TWO_SUBMITTED } });
|
||||
await customersAdmin.verify({ customer_id: customer.id, sts_verify_step_two: 2 });
|
||||
@@ -138,7 +138,7 @@ async function main() {
|
||||
const imported = await prisma.accountingLink.findFirst({ where: { origin: 'IMPORTED' } });
|
||||
if (imported) {
|
||||
const c = await prisma.customer.findUnique({ where: { id: imported.entityId } });
|
||||
chk(c?.mobile?.startsWith('09') && c.passwordHash === '' && c.goldCreditLimitGrams.eq(0), 'imported customer keyed by mobile, OTP-only, credit 0');
|
||||
chk(c?.mobile?.startsWith('09') && c.passwordHash === '!OTP_ONLY_NO_PASSWORD_LOGIN' && c.goldCreditLimitGrams.eq(0), 'imported customer keyed by mobile, OTP-only, credit 0');
|
||||
}
|
||||
|
||||
// ── 5 ──
|
||||
|
||||
@@ -90,7 +90,7 @@ const uniq = String(Date.now()).slice(-7);
|
||||
lastName: name.split(' ').slice(1).join(' '),
|
||||
mobile: `0917${uniq.slice(0, 3)}${suffix}`,
|
||||
nationalCode: `nc${uniq}${suffix}`,
|
||||
passwordHash: '', kind: 'APP_SHOPKEEPER', isActive: true,
|
||||
passwordHash: '!OTP_ONLY_NO_PASSWORD_LOGIN', kind: 'APP_SHOPKEEPER', isActive: true,
|
||||
goldCreditLimitGrams: '100',
|
||||
verificationStep: 'UNVERIFIED',
|
||||
},
|
||||
@@ -106,7 +106,7 @@ const uniq = String(Date.now()).slice(-7);
|
||||
data: {
|
||||
fullName: 'کارشناس مدارک', firstName: 'کارشناس', lastName: 'مدارک',
|
||||
mobile: `0918${uniq.slice(0, 3)}22`,
|
||||
passwordHash: '', role: 'SALES_EXPERT', isActive: true, wagePercent: '3',
|
||||
passwordHash: '!NO_PASSWORD_SET_YET', role: 'SALES_EXPERT', isActive: true, wagePercent: '3',
|
||||
},
|
||||
});
|
||||
await prisma.salesExpertProfile.create({
|
||||
|
||||
@@ -71,7 +71,7 @@ const uniq = String(Date.now()).slice(-7);
|
||||
lastName: name.split(' ').slice(1).join(' '),
|
||||
mobile: `0919${uniq.slice(0, 3)}${suffix}`,
|
||||
nationalCode: `nc${uniq}${suffix}`,
|
||||
passwordHash: '', kind: 'APP_SHOPKEEPER', isActive: true,
|
||||
passwordHash: '!OTP_ONLY_NO_PASSWORD_LOGIN', kind: 'APP_SHOPKEEPER', isActive: true,
|
||||
goldCreditLimitGrams: '500',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -60,7 +60,7 @@ const uniq = String(Date.now()).slice(-7);
|
||||
data: {
|
||||
fullName: `${first} ${last}`, firstName: first, lastName: last,
|
||||
mobile: `0915${uniq.slice(0, 3)}${suffix}`,
|
||||
passwordHash: '', role: 'SALES_EXPERT', isActive: true,
|
||||
passwordHash: '!NO_PASSWORD_SET_YET', role: 'SALES_EXPERT', isActive: true,
|
||||
wagePercent: '4.5',
|
||||
},
|
||||
});
|
||||
@@ -82,7 +82,7 @@ const uniq = String(Date.now()).slice(-7);
|
||||
fullName: name, firstName: name.split(' ')[0], lastName: name.split(' ').slice(1).join(' '),
|
||||
mobile: `0916${uniq.slice(0, 3)}${suffix}`,
|
||||
nationalCode: `nc${uniq}${suffix}`,
|
||||
passwordHash: '', kind: 'APP_SHOPKEEPER', isActive: true,
|
||||
passwordHash: '!OTP_ONLY_NO_PASSWORD_LOGIN', kind: 'APP_SHOPKEEPER', isActive: true,
|
||||
referredByAgentId: agentId, goldCreditLimitGrams: '100',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { AccountingOutbox, Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { OTP_ONLY_PASSWORD_HASH } from '../auth/password-hash';
|
||||
import { ActiveProvider, AccountingConfigService } from './accounting-config.service';
|
||||
import { AccountingConfig } from './accounting-config';
|
||||
import { JalaliDate, parseJalali, toJalali } from './jalali';
|
||||
@@ -181,21 +182,17 @@ export class AccountingSyncService {
|
||||
* An account that exists only in the accounting software becomes an app
|
||||
* customer, keyed by mobile (owner: «اولویت با شماره هست نه کد ملی»). The
|
||||
* national code is the account's own when it is a real one and still free,
|
||||
* else the mobile — the fallback admin-customers and customer-auth already use.
|
||||
* else none (the column is optional since 2026-10-07 and holds national
|
||||
* codes only — never the mobile or a made-up key).
|
||||
* Credit limit 0 and UNVERIFIED: everything beyond identity is the app's.
|
||||
* OTP-only: an imported account has no app password.
|
||||
*/
|
||||
private async importCustomer(provider: ProviderName, ext: ExternalCustomer): Promise<string> {
|
||||
const mobile = ext.mobile as string;
|
||||
const candidates = [validNationalCode(ext.nationalCode), mobile, `${mobile}-${provider}-${ext.code}`].filter(
|
||||
(v): v is string => !!v,
|
||||
);
|
||||
let nationalCode = candidates[candidates.length - 1];
|
||||
for (const c of candidates) {
|
||||
const taken = await this.prisma.customer.findUnique({ where: { nationalCode: c }, select: { id: true } });
|
||||
if (!taken) {
|
||||
nationalCode = c;
|
||||
break;
|
||||
}
|
||||
let nationalCode = validNationalCode(ext.nationalCode);
|
||||
if (nationalCode) {
|
||||
const taken = await this.prisma.customer.findUnique({ where: { nationalCode }, select: { id: true } });
|
||||
if (taken) nationalCode = null;
|
||||
}
|
||||
const { firstName, lastName } = splitName(ext.name || mobile);
|
||||
|
||||
@@ -208,7 +205,7 @@ export class AccountingSyncService {
|
||||
lastName: lastName || null,
|
||||
mobile,
|
||||
nationalCode,
|
||||
passwordHash: '',
|
||||
passwordHash: OTP_ONLY_PASSWORD_HASH,
|
||||
phone: ext.phone,
|
||||
address: ext.address,
|
||||
},
|
||||
@@ -230,7 +227,11 @@ export class AccountingSyncService {
|
||||
}
|
||||
|
||||
private customerPayload(
|
||||
c: { firstName: string | null; lastName: string | null; fullName: string; mobile: string; phone: string | null; address: string | null; nationalCode: string },
|
||||
// nationalCode is nullable since 2026-10-07 (no legacy customer has one —
|
||||
// docs/DATA-MIGRATION-MAP.md §10.4). validNationalCode() already takes
|
||||
// `string | null` and maps empty/invalid to null, so the providers below
|
||||
// keep receiving exactly what they received before.
|
||||
c: { firstName: string | null; lastName: string | null; fullName: string; mobile: string; phone: string | null; address: string | null; nationalCode: string | null },
|
||||
group: ExternalGroup | null,
|
||||
): CustomerPayload {
|
||||
const parts = c.firstName || c.lastName ? { firstName: c.firstName ?? '', lastName: c.lastName ?? '' } : splitName(c.fullName);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AdminRole, Prisma } from '@prisma/client';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { TableService } from '../admin-table/table.service';
|
||||
import { NO_PASSWORD_YET_HASH } from '../auth/password-hash';
|
||||
import type { TableQueryDto } from '../admin-table/table-query.dto';
|
||||
|
||||
/**
|
||||
@@ -327,7 +328,7 @@ export class AdminBranchesService {
|
||||
fullName,
|
||||
mobile: phone,
|
||||
// No password is set: the supervisor cannot sign in until one is issued.
|
||||
passwordHash: '',
|
||||
passwordHash: NO_PASSWORD_YET_HASH,
|
||||
role: AdminRole.WORKSHOP_SUPERVISOR,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -171,7 +171,13 @@ export class AdminCustomersController {
|
||||
@RequirePermission('persons.list.client.omde.edit')
|
||||
verify(
|
||||
@Body()
|
||||
body: { customer_id: string; sts_verify_step_one?: number; sts_verify_step_two?: number },
|
||||
body: {
|
||||
customer_id: string;
|
||||
sts_verify_step_one?: number;
|
||||
sts_verify_step_two?: number;
|
||||
/** Optional, only read on a reject. */
|
||||
reason?: string | null;
|
||||
},
|
||||
) {
|
||||
return this.customers.verify(body);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { VerificationStep } from '@prisma/client';
|
||||
import { OTP_ONLY_PASSWORD_HASH } from '../auth/password-hash';
|
||||
import { AdminCustomersService } from './admin-customers.service';
|
||||
|
||||
/**
|
||||
* Owner rulings 2026-10-07:
|
||||
* - a reject stores REJECTED with an optional reason (it used to fall back to
|
||||
* UNVERIFIED / STEP_ONE_SUBMITTED and leave no trace);
|
||||
* - every value sits in its own column: no mobile in nationalCode, no ''
|
||||
* password — an absent national code is NULL, an absent password is the
|
||||
* explicit OTP-only marker.
|
||||
*/
|
||||
describe('AdminCustomersService', () => {
|
||||
function build(current: Record<string, unknown> = { id: 'c1', verificationStep: VerificationStep.STEP_ONE_SUBMITTED }) {
|
||||
const writes: Record<string, unknown>[] = [];
|
||||
const tx = {
|
||||
customer: {
|
||||
update: jest.fn(async ({ data }: { data: Record<string, unknown> }) => {
|
||||
writes.push(data);
|
||||
return { ...current, ...data };
|
||||
}),
|
||||
create: jest.fn(async ({ data }: { data: Record<string, unknown> }) => {
|
||||
writes.push(data);
|
||||
return { id: 'new', ...data };
|
||||
}),
|
||||
findUnique: jest.fn(async () => current),
|
||||
},
|
||||
};
|
||||
const prisma = { ...tx, $transaction: jest.fn(async (fn: (t: typeof tx) => unknown) => fn(tx)) };
|
||||
const accounting = { customerVerified: jest.fn(), customerChanged: jest.fn() };
|
||||
const sms = { send: jest.fn(async () => undefined) };
|
||||
const service = new AdminCustomersService(prisma as never, {} as never, sms as never, accounting as never);
|
||||
return { service, writes, accounting };
|
||||
}
|
||||
|
||||
describe('verify()', () => {
|
||||
it('a step-one reject stores REJECTED with the reason and time', async () => {
|
||||
const { service, writes } = build();
|
||||
await service.verify({ customer_id: 'c1', sts_verify_step_one: 3, reason: ' کارت ملی خوانا نیست ' });
|
||||
expect(writes[0]).toMatchObject({
|
||||
verificationStep: VerificationStep.REJECTED,
|
||||
verificationRejectionReason: 'کارت ملی خوانا نیست',
|
||||
});
|
||||
expect(writes[0].verificationRejectedAt).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('a step-two reject is REJECTED too, and the reason is optional', async () => {
|
||||
const { service, writes } = build({ id: 'c1', verificationStep: VerificationStep.STEP_TWO_SUBMITTED });
|
||||
await service.verify({ customer_id: 'c1', sts_verify_step_two: 3 });
|
||||
expect(writes[0]).toMatchObject({ verificationStep: VerificationStep.REJECTED, verificationRejectionReason: null });
|
||||
});
|
||||
|
||||
it('accepting a rejected customer clears the reason', async () => {
|
||||
const { service, writes } = build({ id: 'c1', verificationStep: VerificationStep.REJECTED });
|
||||
await service.verify({ customer_id: 'c1', sts_verify_step_one: 2 });
|
||||
expect(writes[0]).toEqual({
|
||||
verificationStep: VerificationStep.STEP_TWO_SUBMITTED,
|
||||
verificationRejectionReason: null,
|
||||
verificationRejectedAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('step-two accept verifies and tells accounting once', async () => {
|
||||
const { service, writes, accounting } = build({ id: 'c1', verificationStep: VerificationStep.STEP_TWO_SUBMITTED });
|
||||
await service.verify({ customer_id: 'c1', sts_verify_step_two: 2 });
|
||||
expect(writes[0].verificationStep).toBe(VerificationStep.VERIFIED);
|
||||
expect(accounting.customerVerified).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('a reject never tells accounting', async () => {
|
||||
const { service, accounting } = build({ id: 'c1', verificationStep: VerificationStep.STEP_TWO_SUBMITTED });
|
||||
await service.verify({ customer_id: 'c1', sts_verify_step_two: 3 });
|
||||
expect(accounting.customerVerified).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('national code and password', () => {
|
||||
it('create() without a national code or password stores NULL and the OTP-only marker', async () => {
|
||||
const { service, writes } = build();
|
||||
await service.create({ fname: 'علی', lname: 'رضایی', mobile: '09120000000', percent: '3' });
|
||||
expect(writes[0].nationalCode).toBeNull();
|
||||
expect(writes[0].mobile).toBe('09120000000');
|
||||
expect(writes[0].passwordHash).toBe(OTP_ONLY_PASSWORD_HASH);
|
||||
});
|
||||
|
||||
it('create() keeps a typed national code, digits normalised', async () => {
|
||||
const { service, writes } = build();
|
||||
await service.create({ fname: 'علی', mobile: '09120000000', percent: '3', national_code: ' ۰۰۱۲۳۴۵۶۷۸ ' });
|
||||
expect(writes[0].nationalCode).toBe('0012345678');
|
||||
});
|
||||
|
||||
it('createSingle() never copies the mobile into nationalCode', async () => {
|
||||
const { service, writes } = build();
|
||||
await service.createSingle({ fname: 'علی', mobile: '09120000000' });
|
||||
expect(writes[0].nationalCode).toBeNull();
|
||||
expect(writes[0].passwordHash).toBe(OTP_ONLY_PASSWORD_HASH);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { TableService } from '../admin-table/table.service';
|
||||
import type { TableQueryDto } from '../admin-table/table-query.dto';
|
||||
import { faToEn } from '../customer-auth/digits';
|
||||
import { OTP_ONLY_PASSWORD_HASH } from '../auth/password-hash';
|
||||
import { SmsService } from '../sms/sms.service';
|
||||
import { AccountingHooksService } from '../accounting-sync/accounting-hooks.service';
|
||||
|
||||
@@ -67,14 +68,31 @@ export type OmdeScope = 'all' | 'banker' | 'shopkeeper' | 'non_verified' | 'arch
|
||||
* `sts_verify_step_one !== 2`, i.e. only an ACCEPTED first step unlocks them.
|
||||
* The new schema models one ordered enum, so these numbers are derived from it.
|
||||
*/
|
||||
/**
|
||||
* A national code as the operator typed it, digits normalised; empty -> null.
|
||||
* The column is optional and unique (2026-10-07): an absent code is NULL,
|
||||
* never the mobile or '' — two customers without one must not collide, and
|
||||
* the column must only ever hold a national code.
|
||||
*/
|
||||
function nationalCodeOrNull(raw: unknown): string | null {
|
||||
return faToEn(String(raw ?? '').trim()) || null;
|
||||
}
|
||||
|
||||
function verifyStepOne(step: VerificationStep): number {
|
||||
switch (step) {
|
||||
case VerificationStep.UNVERIFIED:
|
||||
return 3; // rejected / not yet submitted
|
||||
case VerificationStep.STEP_ONE_SUBMITTED:
|
||||
return 1; // pending review
|
||||
default:
|
||||
// STEP_TWO_SUBMITTED and VERIFIED both imply step one was accepted
|
||||
case VerificationStep.REJECTED:
|
||||
// Must be explicit: falling into `default` would report 2 (accepted),
|
||||
// and the view unlocks the order/account switches on step one === 2.
|
||||
// Rejected customers keep them locked — legacy's step-one reject also
|
||||
// set active = -1 (MajorCustomerController.php:116-117).
|
||||
return 3;
|
||||
case VerificationStep.STEP_TWO_SUBMITTED:
|
||||
case VerificationStep.VERIFIED:
|
||||
// both imply step one was accepted
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
@@ -85,7 +103,9 @@ function verifyStepTwo(step: VerificationStep): number {
|
||||
return 1; // pending review
|
||||
case VerificationStep.VERIFIED:
|
||||
return 2; // accepted
|
||||
default:
|
||||
case VerificationStep.UNVERIFIED:
|
||||
case VerificationStep.STEP_ONE_SUBMITTED:
|
||||
case VerificationStep.REJECTED:
|
||||
return 3; // rejected / not reached
|
||||
}
|
||||
}
|
||||
@@ -305,6 +325,8 @@ export class AdminCustomersService {
|
||||
sts_verify_step_one: verifyStepOne(c.verificationStep),
|
||||
sts_verify_step_two: verifyStepTwo(c.verificationStep),
|
||||
verificationStep: c.verificationStep,
|
||||
verification_rejection_reason: c.verificationRejectionReason,
|
||||
verification_rejected_at: c.verificationRejectedAt,
|
||||
national_id_image: c.nationalIdImageUrl,
|
||||
business_license: c.businessLicenseUrl,
|
||||
shop_image: c.shopImageUrl,
|
||||
@@ -622,8 +644,9 @@ export class AdminCustomersService {
|
||||
firstName: firstName || null,
|
||||
lastName: lastName || null,
|
||||
mobile,
|
||||
nationalCode: mobile, // schema requires it and it is unique; singleCustomer.vue collects no ncode
|
||||
passwordHash: '',
|
||||
// singleCustomer.vue collects no national code.
|
||||
nationalCode: null,
|
||||
passwordHash: OTP_ONLY_PASSWORD_HASH,
|
||||
cityId: (data.city_id as string) || null,
|
||||
kind: CustomerKind.RETAIL,
|
||||
},
|
||||
@@ -651,7 +674,7 @@ export class AdminCustomersService {
|
||||
// can never log in: the app's own faToEn turns the typed number into ASCII
|
||||
// and the lookup misses.
|
||||
const mobile = faToEn(String(data.mobile ?? '').trim());
|
||||
const nationalCode = String(data.national_code ?? data.nationalCode ?? '').trim();
|
||||
const nationalCode = nationalCodeOrNull(data.national_code ?? data.nationalCode);
|
||||
|
||||
if (!fullName || !mobile) {
|
||||
throw new BadRequestException('نام و موبایل الزامی است');
|
||||
@@ -682,12 +705,12 @@ export class AdminCustomersService {
|
||||
// (AdminController.php:338) and is applied client-side.
|
||||
makingChargeOffsetPercent: new Prisma.Decimal(String(data.percent)),
|
||||
mobile,
|
||||
nationalCode: nationalCode || mobile, // schema requires it and it is unique
|
||||
nationalCode,
|
||||
// The form collects a password (bulkCustomer.vue / ReagentCustomer.vue).
|
||||
// It used to be discarded and '' stored, so the operator typed a password
|
||||
// that silently did nothing. Hashed here when supplied; '' still means
|
||||
// "no password yet", which no bcrypt hash can ever match.
|
||||
passwordHash: data.password ? await bcrypt.hash(String(data.password), 10) : '',
|
||||
// that silently did nothing. Hashed here when supplied; otherwise the
|
||||
// account signs in by OTP only.
|
||||
passwordHash: data.password ? await bcrypt.hash(String(data.password), 10) : OTP_ONLY_PASSWORD_HASH,
|
||||
cityId: (data.city_id as string) ?? null,
|
||||
goldCreditLimitGrams: data.gram_level
|
||||
? new Prisma.Decimal(String(data.gram_level))
|
||||
@@ -752,7 +775,7 @@ export class AdminCustomersService {
|
||||
// that lock NOT ported, so the field stays editable here and is normalised
|
||||
// instead. Logged in ISSUES as PERS-01.
|
||||
if (data.mobile !== undefined) patch.mobile = faToEn(String(data.mobile));
|
||||
if (data.national_code !== undefined) patch.nationalCode = String(data.national_code);
|
||||
if (data.national_code !== undefined) patch.nationalCode = nationalCodeOrNull(data.national_code);
|
||||
if (data.city_id !== undefined) {
|
||||
patch.city = data.city_id ? { connect: { id: String(data.city_id) } } : { disconnect: true };
|
||||
}
|
||||
@@ -941,35 +964,50 @@ export class AdminCustomersService {
|
||||
* Legacy's payload is `{ customer_id, sts_verify_step_one }` or
|
||||
* `{ customer_id, sts_verify_step_two }`, where the value is 2 (accept) or
|
||||
* 3 (reject) — see OmdeList.vue acceptStepOne/rejectStepOne. Accepted here in
|
||||
* exactly that shape so the ported view posts unchanged.
|
||||
* exactly that shape so the ported view posts unchanged, plus an optional
|
||||
* `reason` on a reject.
|
||||
*
|
||||
* A reject at either step records REJECTED with its reason and time (owner
|
||||
* ruling 2026-10-07). It used to send the customer back to UNVERIFIED /
|
||||
* STEP_ONE_SUBMITTED, so a rejection left no trace and looked like a
|
||||
* customer who had simply not finished. Same rule as the legacy import:
|
||||
* a rejected first OR second step is REJECTED (DATA-MIGRATION-MAP §5.5).
|
||||
* Accepting again clears the reason.
|
||||
*/
|
||||
async verify(payload: {
|
||||
customer_id: string;
|
||||
sts_verify_step_one?: number;
|
||||
sts_verify_step_two?: number;
|
||||
reason?: string | null;
|
||||
}) {
|
||||
const id = payload.customer_id;
|
||||
const c = await this.prisma.customer.findUnique({ where: { id } });
|
||||
if (!c) throw new NotFoundException('مشتری یافت نشد');
|
||||
|
||||
let next: VerificationStep;
|
||||
const step = payload.sts_verify_step_one ?? payload.sts_verify_step_two;
|
||||
if (step === undefined) throw new BadRequestException('مرحلهی تایید مشخص نشده است');
|
||||
|
||||
if (payload.sts_verify_step_one !== undefined) {
|
||||
next =
|
||||
payload.sts_verify_step_one === 2
|
||||
? VerificationStep.STEP_TWO_SUBMITTED // step one accepted -> step two pending
|
||||
: VerificationStep.UNVERIFIED; // rejected
|
||||
} else if (payload.sts_verify_step_two !== undefined) {
|
||||
next =
|
||||
payload.sts_verify_step_two === 2
|
||||
? VerificationStep.VERIFIED
|
||||
: VerificationStep.STEP_ONE_SUBMITTED; // rejected -> back to step one accepted
|
||||
let data: Prisma.CustomerUpdateInput;
|
||||
if (step === 2) {
|
||||
data = {
|
||||
verificationStep:
|
||||
payload.sts_verify_step_one !== undefined
|
||||
? VerificationStep.STEP_TWO_SUBMITTED // step one accepted -> step two pending
|
||||
: VerificationStep.VERIFIED,
|
||||
verificationRejectionReason: null,
|
||||
verificationRejectedAt: null,
|
||||
};
|
||||
} else {
|
||||
throw new BadRequestException('مرحلهی تایید مشخص نشده است');
|
||||
data = {
|
||||
verificationStep: VerificationStep.REJECTED,
|
||||
verificationRejectionReason: String(payload.reason ?? '').trim() || null,
|
||||
verificationRejectedAt: new Date(),
|
||||
};
|
||||
}
|
||||
const next = data.verificationStep;
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const updated = await tx.customer.update({ where: { id }, data: { verificationStep: next } });
|
||||
const updated = await tx.customer.update({ where: { id }, data });
|
||||
// D27 — a verified customer gets an account in the accounting software
|
||||
// (queued; searched by mobile first, so an existing account is linked).
|
||||
if (next === VerificationStep.VERIFIED && c.verificationStep !== VerificationStep.VERIFIED) {
|
||||
|
||||
@@ -9,7 +9,18 @@ import * as bcrypt from 'bcryptjs';
|
||||
*/
|
||||
jest.mock('@nestjs/jwt', () => ({ JwtService: class JwtService {} }));
|
||||
|
||||
import { AuthService } from './auth.service';
|
||||
/**
|
||||
* The real bcryptjs, with `compare` wrapped so a test can assert it was never
|
||||
* reached. It calls straight through, so every other test still runs against
|
||||
* the real implementation. (A namespace import's properties cannot be
|
||||
* re-defined, so jest.spyOn is not an option here.)
|
||||
*/
|
||||
jest.mock('bcryptjs', () => {
|
||||
const actual = jest.requireActual('bcryptjs');
|
||||
return { ...actual, compare: jest.fn(actual.compare) };
|
||||
});
|
||||
|
||||
import { AuthService, compareLocalHash, OTP_ONLY_PASSWORD_HASH } from './auth.service';
|
||||
import type { AdminSessionService } from '../sessions/admin-session.service';
|
||||
import {
|
||||
IamInvalidCredentialsError,
|
||||
@@ -258,6 +269,58 @@ describe('AuthService login', () => {
|
||||
);
|
||||
});
|
||||
|
||||
/* ─────────────── accounts with no usable password ─────────────── */
|
||||
|
||||
describe('accounts with no usable password', () => {
|
||||
const noPassword = ['', OTP_ONLY_PASSWORD_HASH];
|
||||
|
||||
it.each(noPassword)('refuses login for hash %j, whatever is typed', async (hash) => {
|
||||
const { service } = build(disabledIam(), { ...adminRow(), passwordHash: hash });
|
||||
|
||||
// Including the empty string and the sentinel itself: neither may open it
|
||||
for (const typed of ['', 'x', OTP_ONLY_PASSWORD_HASH]) {
|
||||
await expect(
|
||||
service.login({ phone: '09120000000', password: typed }),
|
||||
).rejects.toThrow('نام کاربری یا رمز عبور اشتباه است');
|
||||
}
|
||||
});
|
||||
|
||||
it.each(noPassword)('refuses hash %j on the IAM fallback path too', async (hash) => {
|
||||
const verifyCredentials = jest.fn().mockRejectedValue(new IamUnavailableError('down'));
|
||||
const { service } = build(
|
||||
{ enabled: true, allowsLocalFallback: true, verifyCredentials },
|
||||
{ ...adminRow(), passwordHash: hash },
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.login({ phone: '09120000000', password: '' }),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
|
||||
it('never hands a malformed hash to bcrypt', async () => {
|
||||
const compare = bcrypt.compare as unknown as jest.Mock;
|
||||
compare.mockClear();
|
||||
|
||||
expect(await compareLocalHash('x', OTP_ONLY_PASSWORD_HASH)).toBe(false);
|
||||
expect(await compareLocalHash('x', '')).toBe(false);
|
||||
expect(await compareLocalHash('x', null)).toBe(false);
|
||||
expect(compare).not.toHaveBeenCalled();
|
||||
|
||||
// …while a real hash still goes through it
|
||||
await compareLocalHash(PASSWORD, passwordHash);
|
||||
expect(compare).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("still accepts the legacy server's PHP $2y$ hashes", async () => {
|
||||
// PHP's $2y$ is the same algorithm as $2b$; the legacy passwords
|
||||
// (customers and the sales experts moving to AdminUser) use it.
|
||||
const legacy = '$2y$' + (await bcrypt.hash(PASSWORD, 4)).slice(4);
|
||||
|
||||
expect(await compareLocalHash(PASSWORD, legacy)).toBe(true);
|
||||
expect(await compareLocalHash('wrong', legacy)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/* ─────────────── two-factor ─────────────── */
|
||||
|
||||
it('explains that a two-factor account cannot log in through this path', async () => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import {
|
||||
IamInvalidCredentialsError,
|
||||
@@ -10,6 +9,9 @@ import {
|
||||
} from '../iam/iam.service';
|
||||
import { AdminSessionService } from '../sessions/admin-session.service';
|
||||
import type { LoginDto } from './dto/login.dto';
|
||||
import { compareLocalHash } from './password-hash';
|
||||
|
||||
export { compareLocalHash, OTP_ONLY_PASSWORD_HASH } from './password-hash';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
@@ -100,7 +102,7 @@ export class AuthService {
|
||||
clientIp?: string,
|
||||
): Promise<{ ok: boolean; identity?: IamIdentity }> {
|
||||
if (!this.iam.enabled) {
|
||||
return { ok: await bcrypt.compare(dto.password, passwordHash) };
|
||||
return { ok: await compareLocalHash(dto.password, passwordHash) };
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -132,7 +134,7 @@ export class AuthService {
|
||||
}
|
||||
|
||||
// fallback mode: the account may not have been migrated to the IAM yet
|
||||
return { ok: await bcrypt.compare(dto.password, passwordHash) };
|
||||
return { ok: await compareLocalHash(dto.password, passwordHash) };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
|
||||
/**
|
||||
* Value written into `passwordHash` for accounts that must never log in with a
|
||||
* password — the ~1,590 legacy customers who only ever used OTP
|
||||
* (docs/DATA-MIGRATION-MAP.md §10.4). The `!` prefix is the Django/Rails
|
||||
* "unusable password" convention: readable by anyone looking at the row, and
|
||||
* matched by no password.
|
||||
*
|
||||
* Kept in this dependency-free module (bcryptjs only) so the data-import
|
||||
* script can use it without loading NestJS.
|
||||
*/
|
||||
export const OTP_ONLY_PASSWORD_HASH = '!OTP_ONLY_NO_PASSWORD_LOGIN';
|
||||
|
||||
/**
|
||||
* Same idea for an admin account created before anyone has issued it a
|
||||
* password (e.g. a workshop supervisor added from the branch form): it cannot
|
||||
* sign in until a password is set through the users screen.
|
||||
*/
|
||||
export const NO_PASSWORD_YET_HASH = '!NO_PASSWORD_SET_YET';
|
||||
|
||||
/**
|
||||
* A real bcrypt hash always starts with `$2` ($2a$, $2b$, or PHP's $2y$ from
|
||||
* the legacy server — all three verify with bcryptjs). Anything else is not a
|
||||
* password: '' on accounts created without one, or OTP_ONLY_PASSWORD_HASH.
|
||||
*
|
||||
* Such hashes are refused here, BEFORE bcrypt is called, so the outcome never
|
||||
* depends on how a particular bcrypt build treats a malformed hash. bcryptjs 3
|
||||
* happens to return false today; a future version or a native binding might
|
||||
* throw and turn a wrong password into a 500 (owner ruling 2026-10-07).
|
||||
*/
|
||||
export async function compareLocalHash(password: string, passwordHash: string | null | undefined) {
|
||||
if (typeof passwordHash !== 'string' || !passwordHash.startsWith('$2')) return false;
|
||||
return bcrypt.compare(password, passwordHash);
|
||||
}
|
||||
|
||||
/** True when a stored legacy hash can be carried over as a working password. */
|
||||
export function isPasswordHash(hash: unknown): hash is string {
|
||||
return typeof hash === 'string' && hash.startsWith('$2');
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type IamIdentity,
|
||||
} from '../iam/iam.service';
|
||||
import { AppSessionService } from '../sessions/app-session.service';
|
||||
import { OTP_ONLY_PASSWORD_HASH } from '../auth/password-hash';
|
||||
import { envOr, envOrNull } from '../../common/env';
|
||||
import { CUSTOMER_TOKEN_TYPE, EXPERT_TOKEN_TYPE, type CustomerJwtPayload } from './customer-jwt.strategy';
|
||||
import { faToEn } from './digits';
|
||||
@@ -185,6 +186,13 @@ export class CustomerAuthService {
|
||||
* Returns null for any mobile that is not an active sales expert, so an
|
||||
* ordinary customer's login is completely unaffected.
|
||||
*/
|
||||
/** `code` when it is set and no customer holds it yet, else null. */
|
||||
private async freeNationalCode(code: string | null): Promise<string | null> {
|
||||
if (!code) return null;
|
||||
const taken = await this.prisma.customer.findUnique({ where: { nationalCode: code }, select: { id: true } });
|
||||
return taken ? null : code;
|
||||
}
|
||||
|
||||
private async resolveExpertTradingAccount(mobile: string): Promise<{ id: string } | null> {
|
||||
const admin = await this.prisma.adminUser.findFirst({
|
||||
where: { mobile, isActive: true, role: AdminRole.SALES_EXPERT },
|
||||
@@ -252,13 +260,13 @@ export class CustomerAuthService {
|
||||
firstName: admin.firstName,
|
||||
lastName: admin.lastName,
|
||||
mobile: admin.mobile,
|
||||
// Customer.nationalCode is required and unique. The expert's own code
|
||||
// when they have one, else the mobile — the same fallback
|
||||
// admin-customers.service.ts uses when a form omits it.
|
||||
nationalCode: admin.salesExpertProfile.nationalCode || admin.mobile,
|
||||
// The expert's own national code when they have one and no other
|
||||
// customer holds it (the column is unique); else none. Never the
|
||||
// mobile — the column holds national codes only.
|
||||
nationalCode: await this.freeNationalCode(admin.salesExpertProfile.nationalCode),
|
||||
// No app password: this account is reached only through the expert's
|
||||
// AdminUser session, never by a password login of its own.
|
||||
passwordHash: '',
|
||||
passwordHash: OTP_ONLY_PASSWORD_HASH,
|
||||
kind: CustomerKind.APP_SHOPKEEPER,
|
||||
goldCreditLimitGrams: admin.salesExpertProfile.gramLevel,
|
||||
makingChargeOffsetPercent: admin.wagePercent ?? new Prisma.Decimal(0),
|
||||
|
||||
@@ -150,7 +150,7 @@ export interface CustomerDetail {
|
||||
id: string;
|
||||
fullName: string;
|
||||
mobile: string;
|
||||
nationalCode: string;
|
||||
nationalCode: string | null;
|
||||
cityId: string | null;
|
||||
goldCreditLimitGrams: string;
|
||||
goldDebtGrams: string;
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
</div>
|
||||
<div class="prof__spec">
|
||||
<dt>کد ملی</dt>
|
||||
<dd>{{ customer.nationalCode }}</dd>
|
||||
<dd>{{ customer.nationalCode || '-' }}</dd>
|
||||
</div>
|
||||
<div class="prof__spec">
|
||||
<dt>وضعیت احراز هویت</dt>
|
||||
@@ -111,6 +111,7 @@ const VERIFICATION_LABELS: Record<string, string> = {
|
||||
STEP_ONE_SUBMITTED: 'مرحله اول ثبت شده',
|
||||
STEP_TWO_SUBMITTED: 'مرحله دوم ثبت شده',
|
||||
VERIFIED: 'تایید شده',
|
||||
REJECTED: 'رد شده',
|
||||
}
|
||||
|
||||
const session = useSessionStore()
|
||||
|
||||
@@ -165,7 +165,7 @@ export interface CustomerDetail {
|
||||
id: string;
|
||||
fullName: string;
|
||||
mobile: string;
|
||||
nationalCode: string;
|
||||
nationalCode: string | null;
|
||||
cityId: string | null;
|
||||
goldCreditLimitGrams: string;
|
||||
goldDebtGrams: string;
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
</div>
|
||||
<div class="prof__spec">
|
||||
<dt>کد ملی</dt>
|
||||
<dd>{{ customer.nationalCode }}</dd>
|
||||
<dd>{{ customer.nationalCode || '-' }}</dd>
|
||||
</div>
|
||||
<div class="prof__spec">
|
||||
<dt>وضعیت احراز هویت</dt>
|
||||
@@ -111,6 +111,7 @@ const VERIFICATION_LABELS: Record<string, string> = {
|
||||
STEP_ONE_SUBMITTED: 'مرحله اول ثبت شده',
|
||||
STEP_TWO_SUBMITTED: 'مرحله دوم ثبت شده',
|
||||
VERIFIED: 'تایید شده',
|
||||
REJECTED: 'رد شده',
|
||||
}
|
||||
|
||||
const session = useSessionStore()
|
||||
|
||||
+654
-36
@@ -3,9 +3,10 @@
|
||||
> سند **نگاشت**، نه پلن اجرا. هیچ کدی بر اساس این سند نوشته نشده.
|
||||
> پیشنیاز ابزار مهاجرت دادهی [`GO-LIVE-PLAN.md`](./GO-LIVE-PLAN.md) §۷.
|
||||
|
||||
**منبع:** `oapi-struncture.sql` — دامپ Navicat، تاریخ ۰۵/۱۰/۲۰۲۶
|
||||
**منبع اول:** `oapi-struncture.sql` — دامپ Navicat فقط ساختار، تاریخ ۰۵/۱۰/۲۰۲۶
|
||||
**منبع دوم:** `oapi.sql` — دامپ کامل با داده، تاریخ ۰۴/۱۰/۲۰۲۶، **۲۷۴٬۷۷۳ سطر**
|
||||
**مقصد:** `apps/api/prisma/schema.prisma` — ۴۳ مدل، ۴۷۷ فیلد
|
||||
**تاریخ نگارش:** ۱۴ مهر ۱۴۰۵ (۲۰۲۶-۱۰-۰۶)
|
||||
**تاریخ نگارش:** ۱۴ مهر ۱۴۰۵ (۲۰۲۶-۱۰-۰۶) · بهروز ۱۵ مهر ۱۴۰۵ (دیتای واقعی)
|
||||
|
||||
---
|
||||
|
||||
@@ -19,7 +20,22 @@
|
||||
| جداول | **۸۰** |
|
||||
| ستونها | **۱٬۰۸۷** |
|
||||
| Engine | `InnoDB` (هر ۸۰ جدول) |
|
||||
| محتوا | **فقط ساختار — صفر `INSERT`** |
|
||||
| محتوا | **دامپ کامل — `oapi.sql` دارد `INSERT`** |
|
||||
|
||||
### ۰.۱ شمارش ردیفهای کلیدی (از `oapi.sql`)
|
||||
|
||||
| جدول | ردیف | یادداشت |
|
||||
|---|---|---|
|
||||
| `customers` | **۱٬۶۱۲** | `AUTO_INCREMENT=1720` — ۱۰۸ شکاف |
|
||||
| `cashes` | **۶۴۸** | اسناد دفتر مالی |
|
||||
| `products_productvarient` | **۷٬۴۴۳** | شامل حذفشدهها |
|
||||
| `product` | **۳٬۲۷۲** | محصولات |
|
||||
| `image` | **۱۷٬۹۵۵** | فایلهای فیزیکی: ۱۷٬۸۲۶ (در `storage/`) |
|
||||
| `products_productimage` | **۵٬۴۱۷** | رابطه product→image |
|
||||
| `users` | **۲۲** | ادمین/کارشناسان |
|
||||
| `orders_orders` | **۵۲۰** | سفارشها (به تأخیر افتاد §۷.۲) |
|
||||
| `wallets` | **۸۰** | کیفپول خردهفروشی |
|
||||
| `fav` | **۲۵۱** | مورد علاقه (migration شد §۱۰) |
|
||||
|
||||
این فایل شکافی را پر کرد که قبلاً باز بود: جداول دوران Django
|
||||
(`product`، `products_productvarient`، `category_collection` و …) هیچ migration
|
||||
@@ -307,11 +323,33 @@ Prisma فقط `remain` را بهعنوان ستون دارد. در مدل ج
|
||||
محاسبهشان کند** — وگرنه عدد صفر نشان داده میشود.
|
||||
|
||||
**ج) دادهی واقعیِ غیرقابلبازسازی** — `birth_date`, `marriage_date`,
|
||||
`token_mobile`, `new_city`. **اینها اگر منتقل نشوند، برای همیشه از بین
|
||||
میروند.** `token_mobile` در ۱۰ فایل استفاده میشود؛ بدون آن، اعلان push به
|
||||
گوشیهای موجود قطع میشود.
|
||||
`token_mobile`, `new_city`.
|
||||
|
||||
🔶 **تصمیم مالک لازم است برای گروه (ج).**
|
||||
### ✅ تصمیم مالک ۲۰۲۶-۱۰-۰۷ — دو منتقل، دو حذف
|
||||
|
||||
| ستون | ردیف | تصمیم | دلیل مالک |
|
||||
|---|---|---|---|
|
||||
| `birth_date` | **۹۱۷** | ✅ **منتقل** | «نرخ پرشدگی بالای ۵۵٪ · کمپینهای وفاداری و پیامکی» |
|
||||
| `new_city` | **۱۷۶** | ✅ **منتقل** | «خالی ماندن شهر ۱۷۶ مشتری نقص دیتا ایجاد میکند» |
|
||||
| `token_mobile` | ۹۹ | ❌ **حذف** | «توکنها اغلب منقضی شدهاند · زباله دیتایی» |
|
||||
| `marriage_date` | ۵ | ❌ **حذف** | «۵ ردیف توجیه معماری ندارد» |
|
||||
|
||||
**هر دو حذف قابلدفاعاند.** توکن push با تغییر کلید FCM/APNs بیاثر
|
||||
میشود، و ۵ ردیف ارزش یک ستون دائمی را ندارد.
|
||||
|
||||
migration افزایشی لازم:
|
||||
|
||||
```prisma
|
||||
model Customer {
|
||||
birthDate DateTime? // legacy birth_date
|
||||
// new_city → §۵.۹
|
||||
}
|
||||
```
|
||||
|
||||
### 🔶 `new_city` — «کدام فیلد» هنوز باز است
|
||||
|
||||
مالک گفت «یا در فیلد شهر بنشیند یا در یک فیلد آدرس متنی مپ شود». کدامیک،
|
||||
به داده بستگی دارد — §۵.۹.
|
||||
|
||||
`api_token`, `send_password`, `rnd` نیازی نیست منتقل شوند — سامانهی auth
|
||||
جدید JWT است.
|
||||
@@ -388,14 +426,144 @@ Prisma فقط `remain` را بهعنوان ستون دارد. در مدل ج
|
||||
جایی برای رفتن ندارند و اگر `UNVERIFIED` شوند، **از «ردشده» به
|
||||
«بررسینشده» برمیگردند** — یعنی دوباره در صف بررسی ظاهر میشوند.
|
||||
|
||||
🔶 **تصمیم مالک — دو گزینه:**
|
||||
1. افزودن `REJECTED` به enum (additive، با §G تضاد ندارد) — ۱۴ ردیف درست
|
||||
منتقل میشوند
|
||||
2. نگاشت ردشدهها به `UNVERIFIED` و پذیرفتن اینکه در صف برمیگردند
|
||||
### ✅ تصمیم مالک ۲۰۲۶-۱۰-۰۷ — `REJECTED` + علت رد
|
||||
|
||||
و **۱۰ ردیف ناسازگار** (`1,2` و `3,2`) هر تصمیمی بگیرید، نیاز به قاعدهی
|
||||
صریح دارند: گام دوم تأیید شده ولی گام اول نه. در legacy این حالت ممکن بود
|
||||
چون دو ستون مستقلاند و هیچ محدودیتی بینشان نیست.
|
||||
> «رویکرد شما ناقص است؛ حالت «رد شد» باید همراه با فیلد «علت رد» اضافه شود.
|
||||
> انتقال این افراد به حالت «در انتظار» کاملاً مردود است چون بار عملیاتی و
|
||||
> خطای انسانی ایجاد میکند.»
|
||||
|
||||
**پذیرفته شد.** انتقال به `UNVERIFIED` رد شد.
|
||||
|
||||
**دو تغییر افزایشی روی مقصد:**
|
||||
|
||||
```prisma
|
||||
enum VerificationStep {
|
||||
UNVERIFIED
|
||||
STEP_ONE_SUBMITTED
|
||||
STEP_TWO_SUBMITTED
|
||||
VERIFIED
|
||||
REJECTED // ← افزوده
|
||||
}
|
||||
|
||||
model Customer {
|
||||
// ...
|
||||
verificationRejectionReason String? // ← افزوده
|
||||
verificationRejectedAt DateTime? // ← افزوده
|
||||
}
|
||||
```
|
||||
|
||||
### 🔴 ولی legacy علت رد را ذخیره نمیکند
|
||||
|
||||
مالک خواست «در صورت وجود در سیستم قدیم» علت هم منتقل شود. **بررسی شد:
|
||||
وجود ندارد.**
|
||||
|
||||
هر ۴۹ ستون `customers` خوانده شد — **هیچ ستون `reason`, `note`,
|
||||
`description`, `comment` یا مشابهی ندارد.** جستوجوی کل دامپ هم نشان داد
|
||||
`canceled_reason` فقط روی `orders_orders` است و `reason` روی یک جدول
|
||||
`transactions_*`.
|
||||
|
||||
و در `MajorCustomerController.php:129-134`، هنگام رد، legacy **فقط یک
|
||||
پیامک ثابت** میفرستد:
|
||||
|
||||
```
|
||||
'اطلاعات شما تایید نشده است.'
|
||||
'لطفا با پیشتیبانی تماس حاصل فرمایید، تا مشکل برطرف شده و ثبتنام شما تکمیل شود.'
|
||||
```
|
||||
|
||||
متن ثابت است — **هیچ علتی در آن نیست و هیچجا ذخیره نمیشود.** یعنی در
|
||||
سیستم قدیم هم پشتیبان علت را نمیدانست؛ مشتری باید تلفن میزد.
|
||||
|
||||
### پس نتیجهی عملی
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| ستون `verificationRejectionReason` | ✅ **ساخته میشود** (خواست مالک · برای آینده) |
|
||||
| مقدارش در مهاجرت **۷ ردیف** | متن ثابت مالک (پایین) — علت واقعی در مبدأ نیست |
|
||||
| `verificationRejectedAt` | **`NULL`** — legacy زمان رد را هم ثبت نمیکرد |
|
||||
|
||||
⚠️ **این یک شکاف دادهی ذاتی است، نه نقص ابزار مهاجرت.** علت رد آن ۷
|
||||
مشتری در سیستم قدیم هرگز ذخیره نشده بود و **قابل بازیابی نیست**. ستون
|
||||
ساخته میشود تا از این پس پر شود.
|
||||
|
||||
### ✅ تصمیم مالک ۲۰۲۶-۱۰-۰۷ — یادداشت خودکار درج شود
|
||||
|
||||
> «فیلد علت برای این ۱۴ ردیف نباید کامپلت NULL رها شود.»
|
||||
|
||||
(عدد درست **۷** است: ۲ رد در گام دو، ۳ در گام یک، ۲ در هر دو. عدد ۱۴ را
|
||||
من اشتباه جمع کرده بودم و مالک بر اساس آن نوشت؛ تصمیم تغییری نمیکند.)
|
||||
|
||||
مقدار دقیق که ابزار درج میکند:
|
||||
|
||||
```
|
||||
رد شده در سیستم قدیم — فاقد شرح علت ثبتشده
|
||||
```
|
||||
|
||||
| ستون | مقدار |
|
||||
|---|---|
|
||||
| `verificationStep` | `REJECTED` |
|
||||
| `verificationRejectionReason` | **متن بالا** (نه `NULL`) |
|
||||
| `verificationRejectedAt` | `NULL` — legacy زمان رد را ثبت نمیکرد |
|
||||
|
||||
⚠️ **قاعدهی ابزار:** این متن **فقط** روی ردیفهایی درج شود که مهاجرت
|
||||
`REJECTED`شان میکند. اگر ابزار دوباره اجرا شود، نباید روی مشتریای که
|
||||
**در سیستم جدید** رد شده و علت واقعی دارد بازنویسی کند. شرط:
|
||||
`WHERE verificationRejectionReason IS NULL` — یا طبق §۱۰.۵، این ستون
|
||||
هم در allow-list فقط برای ردیفهای تازه نوشته شود.
|
||||
|
||||
### ۱۰ ردیف ناسازگار
|
||||
|
||||
`1,2` (۷ ردیف) و `3,2` (۳ ردیف) — گام دوم تأیید شده ولی گام اول نه.
|
||||
در legacy ممکن بود چون دو ستون مستقلاند و هیچ محدودیتی بینشان نیست.
|
||||
|
||||
**قاعدهی پیشنهادی: گام اول حاکم است.**
|
||||
- `1,2` → `STEP_ONE_SUBMITTED` (گام اول هنوز بررسی نشده)
|
||||
- `3,2` → `REJECTED` (گام اول رد شده، پس کل پرونده رد است)
|
||||
|
||||
دلیل: در legacy `step_one=3` ستون `active` را `-1` میکرد، یعنی مشتری
|
||||
**غیرفعال** میشد. پس رد گام اول واقعاً پرونده را میبست.
|
||||
|
||||
### ۵.۹ — `new_city` چیست و کجا بنشیند
|
||||
|
||||
`new_city` یک **نام شهر بهصورت متن آزاد** است، مستقل از `city_id`.
|
||||
`AdminController.php:296-298` و `Major/CustomerController.php:36` نشان
|
||||
میدهند هرگاه فرم فیلد `city` را پر بفرستد، عیناً در `new_city` ذخیره
|
||||
میشود — **بدون هیچ تطبیقی با جدول `cities`**.
|
||||
|
||||
و `MajorCustomerController.php:36` ثابت میکند **خوانده میشود**:
|
||||
داشبورد مشتری `new_city` را در `select` دارد. پس ستون زنده است، نه
|
||||
بازمانده.
|
||||
|
||||
**چرا ۱۷۶ ردیف دارد:** جدول `cities` فقط **۱۵ ردیف** دارد (§۱۰.۴). پس
|
||||
بسیاری از شهرهای واقعی در آن نیستند و اپراتور نام را دستی تایپ میکرده.
|
||||
|
||||
### دو حالت ممکن، دو راهحل متفاوت
|
||||
|
||||
| اگر | یعنی | راهحل |
|
||||
|---|---|---|
|
||||
| اکثر ۱۷۶ ردیف `city_id` **تهی** دارند | شهرشان در `cities` نیست | **ستون متنی لازم است** |
|
||||
| اکثرشان `city_id` **هم** دارند | `new_city` تکراری است | میتوان رهایش کرد |
|
||||
| متنشان با عنوان یک شهر موجود یکی است | قابل تبدیل به `city_id` | نگاشت به `cityId` |
|
||||
|
||||
🔶 **یک کوئری لازم است** —
|
||||
[`migration-precheck-3.sql`](./migration-precheck-3.sql). تا جوابش نیاید،
|
||||
نمیدانم ستون تازه بسازم یا به `cityId` نگاشت کنم. ساختن ستونی که لازم
|
||||
نیست، همانقدر بد است که نساختن ستونی که لازم است.
|
||||
|
||||
⚠️ **اگر ستون متنی لازم شد، اسمش `cityNameRaw` پیشنهاد میشود**، نه
|
||||
`newCity` — چون «new» در legacy معنای تاریخی داشت (ستون بعداً اضافه شده)
|
||||
و در مقصد گمراهکننده است.
|
||||
|
||||
### `birth_date` — یک بررسی سلامت
|
||||
|
||||
`birth_date` نوعش `timestamp` است. ولی چون legacy تاریخها را جاهای دیگر
|
||||
**بهصورت رشتهی جلالی** ذخیره میکرد (§۸ — `recive_date`)، احتمال دارد
|
||||
اینجا هم تاریخ جلالی بهاشتباه بهعنوان میلادی وارد شده باشد.
|
||||
|
||||
اگر سالها در بازهی ۱۳۰۰–۱۴۰۰ باشند، یعنی **جلالی در ستون میلادی** و
|
||||
تبدیل لازم است. اگر ۱۹۳۰–۲۰۱۰ باشند، سالماند.
|
||||
کوئریاش در همان فایل سوم است.
|
||||
|
||||
---
|
||||
|
||||
### ۵.۷ — 🔴 `reagent_id` به `customers` اشاره میکند، نه `users`
|
||||
|
||||
@@ -792,10 +960,16 @@ legacy شش ستون برای نسخههای تغییراندازهیاف
|
||||
| `request_fashions` | `name`, `mobile` | درخواست «مد» — فرم تماس | ❌ ندارد |
|
||||
| `request_logs` | `customer_id`, `ip`, `device`, `data`, `user_agent`, `route` | لاگ درخواست | تقریباً `CustomerActivityLog` |
|
||||
|
||||
### ✅ تصمیم مالک ۲۰۲۶-۱۰-۰۶ — `fav` لازم است
|
||||
### ✅ تصمیم مالک ۲۰۲۶-۱۰-۰۶ — علاقهمندیها لازماند
|
||||
|
||||
> «بله» — علاقهمندیها مهماند.
|
||||
|
||||
🔴 **تصحیح ۲۰۲۶-۱۰-۰۷: منبع درست `fav` نیست.** `fav` مال فروشگاه خرده است
|
||||
(`Customer\FavController`، guard `api-singleCustomer`). اپ عمده
|
||||
**`major_favorites`** (۳٬۳۰۵ ردیف) را میخواند — §۱۰.۷. متن زیر دربارهی
|
||||
`fav` نوشته شده؛ تصمیم مالک و مدل `CustomerFavorite` همان میمانند، فقط منبع
|
||||
عوض شد.
|
||||
|
||||
**یک migration افزایشی لازم است.** چون additive است، با `PROTECTED.md` §G
|
||||
تضادی ندارد و قابلیت موجودی را لمس نمیکند.
|
||||
|
||||
@@ -891,8 +1065,23 @@ nationalCode String @unique // ← NOT NULL
|
||||
🔴 **مهاجرت روی اولین ردیف میشکند.** و `@unique` روی رشتهی خالی یعنی
|
||||
فقط **یک** ردیف میتواند `''` باشد.
|
||||
|
||||
🔶 **تصمیم فوری لازم:** `nationalCode` باید `String?` شود (nullable). این
|
||||
یک migration افزایشی روی مقصد است. بدون آن مهاجرت مشتری **غیرممکن** است.
|
||||
### ✅ تصمیم مالک ۲۰۲۶-۱۰-۰۷ — nullable شود
|
||||
|
||||
> «وقتی دیتاست مبدا فاقد این داده است، هیچ گزینه دیگری جز Nullable کردن
|
||||
> فیلد وجود ندارد. ساختن کد ملی فیک تخلف دیتایی است و مانع از
|
||||
> احراز هویتهای قانونی بعدی میشود.»
|
||||
|
||||
```prisma
|
||||
nationalCode String? @unique // بود: String @unique
|
||||
```
|
||||
|
||||
⚠️ **نکتهی فنی که به نفع این تصمیم است:** در Postgres مقدار `NULL` در
|
||||
ایندکس `@unique` **تکراری حساب نمیشود**. پس هزار ردیف با
|
||||
`nationalCode = NULL` بیمشکل کنار هم مینشینند — ولی اگر بهجای `NULL`
|
||||
رشتهی خالی `''` بگذاریم، **فقط یکی جا میشود**.
|
||||
|
||||
🔴 **قاعدهی اجباری ابزار: `''` را به `NULL` تبدیل کند، نه اینکه خالی
|
||||
بفرستد.**
|
||||
|
||||
**۳. گِردکردن رخ میدهد — ۲۴ + ۳۲ ردیف.**
|
||||
`gold_needs_rounding = 24` و `order_weight_needs_rounding = 32`. یعنی §۴
|
||||
@@ -942,12 +1131,116 @@ pw_bcrypt 5 pw_other 0 pw_empty 1590
|
||||
```prisma
|
||||
passwordHash String // ← NOT NULL
|
||||
```
|
||||
🔴 **مهاجرت میشکند.** دو راه: `passwordHash` nullable شود، یا مهاجرت یک
|
||||
hash تصادفیِ غیرقابلاستفاده بگذارد. **گزینهی دوم امنتر است** — ستون
|
||||
اجباری میماند و هیچکس نمیتواند با رمز خالی وارد شود.
|
||||
### ✅ تصمیم مالک ۲۰۲۶-۱۰-۰۷ — hash غیرقابلورود، nullable نشود
|
||||
|
||||
> «برداشتن اجبار رمز (Nullable کردن پسورد) یک ضدالگوی امنیتی است و احتمال
|
||||
> بایپس شدن احراز هویت در باگهای آینده را بالا میبرد. نباید صرفاً یک
|
||||
> رشته تصادفی پلین یا هش ضعیف بگذارید.»
|
||||
|
||||
**`passwordHash` اجباری میماند.** مقدارش برای ۱٬۵۹۰ ردیف یک hash
|
||||
**عامدانه غیرقابلورود** میشود.
|
||||
|
||||
🔴 **تفکیک مهمی که مالک درست روی آن تأکید کرد:** «رمز تصادفی» و «hash
|
||||
غیرقابلورود» یکی نیستند.
|
||||
|
||||
| روش | نتیجه |
|
||||
|---|---|
|
||||
| ❌ رشتهی تصادفیِ خام در ستون | `bcrypt.compare()` همیشه `false` میدهد — **ولی** قالبش نامعتبر است و بعضی کتابخانهها در این حالت throw میکنند یا رفتار نامعین دارند |
|
||||
| ❌ hash یک رمز تصادفی | یک رمز **واقعی** وجود دارد که کار میکند؛ اگر جایی لاگ شده باشد، در دسترس است |
|
||||
| ✅ **قالب نامعتبرِ عامدانه** | هیچ رمزی به آن نمیخورد، **و** قالبش صریحاً «غیرفعال» را اعلام میکند |
|
||||
|
||||
**روش پیشنهادی — پیشوند `!` که در Django و Rails قرارداد است:**
|
||||
|
||||
```
|
||||
!OTP_ONLY_NO_PASSWORD_LOGIN
|
||||
```
|
||||
|
||||
چرا کار میکند: `bcrypt.compare(anyPassword, "!OTP_ONLY...")` هرگز `true`
|
||||
نمیدهد چون رشته با `$2a$`/`$2b$`/`$2y$` شروع نمیشود، پس **هیچ رمزی
|
||||
نمیتواند با آن مطابقت کند**. و برخلاف رشتهی تصادفی، **خواندنی است** —
|
||||
هر کسی که ستون را ببیند میفهمد این کاربر فقط OTP دارد.
|
||||
|
||||
### ⚠️ بررسی کد مقصد — نگرانی باریکتر از آن است که بهنظر میرسد
|
||||
|
||||
مالک نگران «بایپس شدن احراز هویت در باگهای آینده» بود. کد مقصد خوانده
|
||||
شد و دو واقعیت پیدا شد:
|
||||
|
||||
**۱. مشتری اصلاً مسیر ورود با رمز ندارد.**
|
||||
`grep` روی کل `apps/api/src` نشان داد تنها دو جای `bcrypt.compare` روی
|
||||
رمز اینهاست: `auth.service.ts:103` و `:135` — و هر دو داخل
|
||||
`AuthService.login()` هستند که `prisma.adminUser.findUnique()` میخواند
|
||||
(`auth.service.ts:40`)، **نه `customer`**.
|
||||
|
||||
ورود مشتری در `customer-auth.service.ts` است و تنها `bcrypt.compare`
|
||||
آن روی `challenge.codeHash` است (خط ۳۶۱) — **کد OTP، نه رمز**.
|
||||
`Customer.passwordHash` در هیچ مسیر احراز هویتی خوانده نمیشود.
|
||||
|
||||
**۲. مقصد از قبل `passwordHash: ''` مینویسد.**
|
||||
در **پنج جا**: `customer-auth.service.ts:261`,
|
||||
`admin-customers.service.ts:626,690`, `accounting-sync.service.ts:211`,
|
||||
`admin-branches.service.ts:330`.
|
||||
|
||||
یعنی مشتریهایی که **همین حالا** از طریق OTP یا پنل ادمین ساخته میشوند،
|
||||
رشتهی خالی دارند. **این وضع موجود است، نه چیزی که مهاجرت معرفی کند.**
|
||||
|
||||
### پس نتیجه
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| مقدار پیشنهادی مهاجرت | `!OTP_ONLY_NO_PASSWORD_LOGIN` |
|
||||
| ریسک بایپس | **صفر** — مشتری مسیر ورود با رمز ندارد |
|
||||
| چرا با این حال انجام شود | **دفاع در عمق** (خواست مالک) + خوانا بودن |
|
||||
|
||||
✅ **و یک سود جانبی:** چون مقصد الان `''` مینویسد، این روش **بهتر** از
|
||||
وضع موجود است. پیشنهاد میکنم آن پنج جا هم به همین مقدار تغییر کنند تا
|
||||
یکدست شود — ولی **این تغییر کد است، نه مهاجرت**، و اجازهی جداگانه
|
||||
میخواهد.
|
||||
|
||||
### ✅ تصمیم مالک ۲۰۲۶-۱۰-۰۷ — محافظ در لایهی سرویس
|
||||
|
||||
> «تست واحد الزامی است؛ اگر متد کرش کند، باید در لایه سرویس مقصد چک شود
|
||||
> که اگر فرمت هش نامعتبر یا پیشوند `!` بود، مستقیماً بدون فراخوانی bcrypt
|
||||
> خروجی false برگردد.»
|
||||
|
||||
**پذیرفته شد — و این روش از تستکردن تنها بهتر است**، چون به رفتار
|
||||
کتابخانه وابسته نمیماند:
|
||||
|
||||
```ts
|
||||
// قبل از هر فراخوانی bcrypt
|
||||
if (!passwordHash || !passwordHash.startsWith('$2')) {
|
||||
return { ok: false }; // اکانت فقط-OTP یا هش نامعتبر
|
||||
}
|
||||
return { ok: await bcrypt.compare(dto.password, passwordHash) };
|
||||
```
|
||||
|
||||
جای اعمال: `auth.service.ts:103` و `:135` (هر دو مسیر `verifyPassword`).
|
||||
|
||||
⚠️ **این محافظ از `''` فعلی هم محافظت میکند** — یعنی باگی را میبندد
|
||||
که همین حالا وجود دارد، مستقل از مهاجرت.
|
||||
|
||||
🔶 **تست واحد همچنان لازم است** (خواست مالک)، ولی نقشش عوض شد: دیگر
|
||||
«آیا bcrypt کرش میکند؟» نیست، بلکه «آیا محافظ قبل از bcrypt جلو را
|
||||
میگیرد؟». در این محیط نتوانستم اجرا کنم (بررسیکنندهی سمت سرور خطا
|
||||
داد)، پس **ادعا نمیکنم تست شده است**.
|
||||
|
||||
### 🔶 تسک رفکتور جداگانه — ثبت شد
|
||||
|
||||
> «تغییر آن پنج جا در اسکوپ پایپلاین مهاجرت نیست، اما به عنوان یک تسک
|
||||
> رفکتور ثبت شود تا در یک مرج ریکوئست جداگانه اصلاح گردد.»
|
||||
|
||||
**ثبت شد.** پنج جایی که `passwordHash: ''` مینویسند:
|
||||
|
||||
| فایل | خط |
|
||||
|---|---|
|
||||
| `customer-auth.service.ts` | ۲۶۱ |
|
||||
| `admin-customers.service.ts` | ۶۲۶ · ۶۹۰ |
|
||||
| `accounting-sync.service.ts` | ۲۱۱ |
|
||||
| `admin-branches.service.ts` | ۳۳۰ |
|
||||
|
||||
**خارج از اسکوپ مهاجرت.** PR جداگانه، بعد از مهاجرت.
|
||||
|
||||
⚠️ آن ۵ رمز `$2y$` (bcrypt) هستند و مقصد هم bcrypt است، پس **بدون
|
||||
تغییر منتقل میشوند**.
|
||||
تغییر منتقل میشوند** و همانطور کار میکنند.
|
||||
|
||||
### enum ها — دو نکته
|
||||
|
||||
@@ -1064,6 +1357,136 @@ orders_orders 520 live retail_sts: 7 → ۳ ردیف
|
||||
|
||||
---
|
||||
|
||||
## ۱۰.۵.۵ — فهرست کامل تغییرات افزایشی مقصد
|
||||
|
||||
همهی تصمیمهای مالک تا ۲۰۲۶-۱۰-۰۷، در یک migration جمع میشوند.
|
||||
**همه افزایشیاند** — هیچ ستونی حذف یا تغییر نوع نمیدهد، پس با
|
||||
`PROTECTED.md` §G و قابلیتهای حسابداری/تصویر واریانت/پیامک **تضادی
|
||||
ندارند**.
|
||||
|
||||
```prisma
|
||||
model Customer {
|
||||
nationalCode String? @unique // بود: String — §۱۰.۴
|
||||
birthDate DateTime? // legacy birth_date — §۵.۲
|
||||
verificationRejectionReason String? // §۵.۵
|
||||
verificationRejectedAt DateTime?
|
||||
// cityNameRaw String? // §۵.۹ — منتظر جواب کوئری سوم
|
||||
favorites CustomerFavorite[] // §۱۰
|
||||
}
|
||||
|
||||
enum VerificationStep {
|
||||
UNVERIFIED
|
||||
STEP_ONE_SUBMITTED
|
||||
STEP_TWO_SUBMITTED
|
||||
VERIFIED
|
||||
REJECTED // §۵.۵
|
||||
}
|
||||
|
||||
model CustomerFavorite { // §۱۰ — legacy fav
|
||||
customerId String
|
||||
customer Customer @relation(fields: [customerId], references: [id])
|
||||
productId String
|
||||
product Product @relation(fields: [productId], references: [id])
|
||||
createdAt DateTime @default(now())
|
||||
@@id([customerId, productId])
|
||||
}
|
||||
```
|
||||
|
||||
و یک تغییر کد (نه schema) در `auth.service.ts:103,135` — محافظ پیشوند
|
||||
`$2` قبل از `bcrypt.compare` (§۱۰.۴).
|
||||
|
||||
⚠️ طبق D14: `migrate dev` در توسعه، و SQL **idempotent**
|
||||
(`IF NOT EXISTS`) چون کانتینر مهاجرتها را خودش اجرا میکند (D15).
|
||||
|
||||
### ✅ وضعیت اجرا — ۲۰۲۶-۱۰-۰۷
|
||||
|
||||
شاخه: `migration/legacy-data` (از `19d490e`؛ `release/delivery` دست نخورد).
|
||||
|
||||
| مورد | وضعیت | تأیید |
|
||||
|---|---|---|
|
||||
| migration `20261007120000_migration_prep_additive` | ✅ اعمال شد | `migrate diff` دیتابیس زنده ↔ schema: **خالی** |
|
||||
| ۴ ستون `Customer` | ✅ همه nullable | `information_schema` |
|
||||
| `CustomerFavorite` | ✅ ساخته شد | `to_regclass` |
|
||||
| `VerificationStep.REJECTED` | ✅ | `pg_enum` · Postgres 15.19 |
|
||||
| نوع پارامتر `accounting-sync.service.ts:233` | ✅ `string \| null` | رفتار درگاهها صفر تغییر |
|
||||
| محافظ `$2` در `auth.service.ts` | ✅ `compareLocalHash()` | ۴ تست تازه |
|
||||
| ممیزی مصرفکنندگان `REJECTED` | ✅ | پایین |
|
||||
| تستها | ✅ **۱۷۸ از ۱۷۸** | ۱ suite از قبل خراب — پایین |
|
||||
| API زنده | ✅ | عمومی ۲۰۰ · ادمین بیتوکن ۴۰۱ · رمز غلط ۴۰۱ · رمز درست ۲۰۰ |
|
||||
|
||||
### 🔴 خطر فرایندی کشفشده — فایل migration = اعمال خودکار
|
||||
|
||||
**migration بدون تأیید اعمال شد — نه توسط من.** زنجیره:
|
||||
|
||||
1. سرور توسعه با `nest start --watch` اجرا میشود
|
||||
2. ویرایش هر فایلی زیر `src/` سرور را ریاستارت میکند
|
||||
3. در boot، [`bootstrap.ts:35`](../apps/api/src/prisma/bootstrap.ts) تابع
|
||||
`runMigrations()` را صدا میزند که **هر فایل معلق در `prisma/migrations`
|
||||
را اعمال میکند** (D15)
|
||||
|
||||
ویرایش `accounting-sync.service.ts` (برای رفع خطای نوع) ریاستارت را زد و
|
||||
migration در `13:42:36` در `_goldbank_migrations` ثبت شد — پیش از تأیید
|
||||
مالک. نتیجه درست و تأییدشده است، ولی **روال «اول نشان بده، بعد اجرا کن»
|
||||
(D0) روی این ماشین کار نمیکند**.
|
||||
|
||||
**قاعده از این پس:** تا تأیید نشده، migration **بیرون از
|
||||
`prisma/migrations`** نوشته شود (مثلاً `docs/` یا scratchpad)، یا سرور
|
||||
توسعه متوقف باشد. فقط پس از تأیید به پوشه منتقل شود.
|
||||
|
||||
### ⚠️ دفتر CLI پریزما ۹ migration عقب است (از قبل)
|
||||
|
||||
`prisma migrate status` نُه migration را «اعمالنشده» میداند، از
|
||||
`20260922000000_customer_otp` تا همین تازه — چون این ماشین migration ها را
|
||||
از مسیر runner خود اپ (`_goldbank_migrations`) گرفته، نه CLI. دیتابیس
|
||||
کامل است (diff خالی). **پیامد:** روی این ماشین `prisma migrate dev` اجرا
|
||||
نشود — میخواهد ۹ فایل را دوباره اجرا کند. همگامسازی با
|
||||
`prisma migrate resolve --applied <name>` برای هر ۹ مورد ممکن است، ولی در
|
||||
`_prisma_migrations` مینویسد و **تأیید مالک میخواهد** (D14).
|
||||
|
||||
### ممیزی مصرفکنندگان `REJECTED`
|
||||
|
||||
| جا | پیش از رفع | وضعیت |
|
||||
|---|---|---|
|
||||
| `admin-customers.service.ts` `verifyStepOne()` | 🔴 `default` → `2` (**پذیرفته**). نما سوییچهای سفارش/حساب را روی `step_one === 2` باز میکند → **مشتری ردشده سوییچ باز میگرفت** | ✅ صریحاً `3` |
|
||||
| همان، `verifyStepTwo()` | `default` → `3` (درست، تصادفی) | ✅ صریح |
|
||||
| `ProfileView.vue` هر دو اپ | برچسب نداشت → کلمهی انگلیسی `REJECTED` نمایش داده میشد | ✅ «رد شده» |
|
||||
| فیلتر «تاییدنشدهها» (`:221`) | فقط `STEP_ONE/TWO_SUBMITTED` | ✅ بدون تغییر — ردشدهها **در صف برنمیگردند** (خواست مالک) |
|
||||
| روتر هر دو اپ · دکمهی تکمیل پروفایل | ردشده مثل `UNVERIFIED` رفتار میشود | ✅ مطابق legacy — پایین |
|
||||
|
||||
`default` در هر دو تابع **حذف شد** تا switch جامع باشد: اگر روزی مقدار
|
||||
ششمی به enum اضافه شود، TypeScript خطا میدهد و همین باگ بیصدا تکرار
|
||||
نمیشود.
|
||||
|
||||
### 🔶 دو سؤال برای مالک — از ممیزی
|
||||
|
||||
**۱. رد در سیستم جدید `REJECTED` نمینویسد.**
|
||||
`verify()` در `admin-customers.service.ts:955-969` هنگام رد:
|
||||
گام ۱ → `UNVERIFIED`، گام ۲ → `STEP_ONE_SUBMITTED`. یعنی ۷ مشتری مهاجر
|
||||
`REJECTED` میشوند، ولی **هر ردِ تازه در پنل همان کاری را میکند که مالک
|
||||
برای مهاجرت «کاملاً مردود» خواند** (برگشت به صف). و
|
||||
`verificationRejectionReason` که مالک «برای نیازمندیهای آتی» خواست، از
|
||||
هیچ مسیری پر نمیشود — فرم ادمین فیلد علت ندارد.
|
||||
پیشنهاد: `verify()` هنگام رد `REJECTED` + `verificationRejectedAt`
|
||||
بنویسد، و یک فیلد اختیاری علت به دکمهی رد اضافه شود. **تغییر رفتار یک
|
||||
جریان زنده است — تأیید لازم.**
|
||||
|
||||
**۲. مشتری ردشده با ارسال دوبارهی مدارک خودکار تأیید میشود.**
|
||||
legacy دکمهی تکمیل پروفایل را فقط وقتی `sts_verify_step_two` برابر ۱ یا
|
||||
۲ بود پنهان میکرد (طبق کامنت پورت در `ProfileView.vue:122-126`)، پس ردشده (۳) آن را
|
||||
میدید؛ و ارسال، بیدرنگ `VERIFIED` میکند چون legacy خط «منتظر
|
||||
کارشناس» را کامنت کرده بود (`customer-profile.service.ts:16-19`). پورت
|
||||
همین است. **نتیجه: «رد» در عمل یک «دوباره بفرست» است، نه بستن پرونده.**
|
||||
اگر مالک میخواهد رد واقعاً ببندد، این تصمیم محصولی است، نه پورت.
|
||||
|
||||
### ⚠️ `sms.service.spec.ts` از قبل خراب است
|
||||
|
||||
دو خطای `TS2339: Property 'platform' does not exist` (خطوط ۸۳، ۱۰۲). این
|
||||
فایل و `sms.service.ts` در این شاخه **دست نخوردهاند** — خرابی در commit
|
||||
`19d490e` است. به همین دلیل آن suite کامپایل نمیشود؛ ۱۷۸ تست بقیه سبزند.
|
||||
خارج از اسکوپ این کار، ثبت میشود.
|
||||
|
||||
---
|
||||
|
||||
## ۱۰.۶ — پرسش دوم از دیتابیس
|
||||
|
||||
📄 **[`migration-precheck-2.sql`](./migration-precheck-2.sql)** — چهار سؤالی
|
||||
@@ -1073,13 +1496,202 @@ orders_orders 520 live retail_sts: 7 → ۳ ردیف
|
||||
|
||||
| # | سؤال | چرا مسدودکننده است |
|
||||
|---|---|---|
|
||||
| ۱ | **مبلغ سند مالی در کدام ستون است؟** | `remain`/`rial_remain` همه `NULL`اند. بدون جواب، `LedgerEntry.amount` خالی میماند و **کل دفتر مالی بیمبلغ منتقل میشود** |
|
||||
| ۱ | ~~مبلغ سند مالی در کدام ستون است؟~~ | ✅ **حل — §۱۰.۷** |
|
||||
| ۲ | آیا «مسئول فروش برنده» برای ۲۷ گروه تکراری کافی است؟ | اگر گروهی کارشناس نداشته باشد، قاعده بیاثر است |
|
||||
| ۳ | سه ستون تصویر → چهار نقش `ProductImageRole` | نگاشت غلط = تصویر غلط روی محصول |
|
||||
| ۴ | تأیید §۵.۷ — `reagent_id` به `customers` اشاره میکند؟ | اگر غلط باشد، رابطهی کارشناس معرف از بین میرود |
|
||||
|
||||
---
|
||||
|
||||
## ۱۰.۷ — یافتههای دامپ کامل (`oapi.sql` — ۲۰۲۶-۱۰-۰۷)
|
||||
|
||||
`oapi.sql` (دامپ Navicat با داده، تاریخ ۰۴/۱۰/۲۰۲۶، ۶۳ مگابایت) در یک MySQL
|
||||
محلی روی Docker بارگذاری و هر ادعا با کوئری روی همان داده بررسی شد. این
|
||||
بخش ابتدا توسط نشست موازی `gold-bank-79` نوشته شد. **چند ادعای آن نسخه
|
||||
غلط بود و اینجا تصحیح شده است** (جدول پایین).
|
||||
|
||||
⚠️ دامپ **دو روز قدیمیتر** از اجرای پیشبررسی روی سرور زنده است (مثلاً
|
||||
۷٬۴۴۳ تنوع اینجا در برابر ۷٬۴۷۴ زنده). برای ساخت و آزمون کافی است.
|
||||
**برای مهاجرت واقعی دامپ تازه گرفته شود.**
|
||||
|
||||
`oapi.sql` دادهی شخصی مشتریان است: در `.gitignore` قرار گرفت و هرگز commit
|
||||
نشده است.
|
||||
|
||||
### تصحیح ادعاهای نسخهی قبلی این بخش
|
||||
|
||||
| ادعای قبلی | واقعیت (کوئری روی داده) |
|
||||
|---|---|
|
||||
| `remain`/`rial_remain` صفرند | **NULL** هستند — در هر ۳۸۳ ردیف زنده؛ ساختار `DEFAULT NULL` دارد |
|
||||
| `new_city` شناسهی عددی `cities5` است | **هر ۱۷۲ مقدار نام شهرِ تایپشده است؛ صفر مقدار عددی** — §۵.۹ |
|
||||
| `birth_date` همه بین ۱۹۵۰ و ۲۰۱۰، بدون نیاز به پالایش | **۳۵۷ مورد بعد از ۲۰۱۰ تا ۲۰۳۱؛ ۱۹۰ مورد برابر تاریخ ثبتنام** |
|
||||
| `type` ۳ و ۴ و ۵ نامعلوم، نیاز به تأیید مالک | در `Customer::$TYPES` (Customer.php:85-92) تعریف شدهاند — §۵.۳ |
|
||||
| `LedgerEntry.goldGrams = value`، `rialAmount = price` | این فیلدها وجود ندارند؛ مدل `amount` + `currency` + `direction` است |
|
||||
| شمارش انواع سند: ۹ → ۴۸۲، ۲ → ۶۳، … | شامل حذفشدهها بود؛ زنده: ۹ → ۲۸۰، ۲ → ۳۷، ۱ → ۳۳، ۴ → ۳۲، ۳ → ۱ |
|
||||
| علاقهمندی = `fav` (۲۵۱) | `fav` مال فروشگاه خرده است (guard `api-singleCustomer`)؛ اپ عمده **`major_favorites`** (۳٬۳۰۵) — پایین |
|
||||
|
||||
**درست بود:** مبلغ سند در `value` (گرم) و `price` (ریال) است؛ پوشهی تصاویر
|
||||
`F:\New folder (2)\storage` با **۱۷٬۸۳۲ فایل (۱.۸ گیگابایت)** وجود دارد.
|
||||
|
||||
### 🔴 فرمول بدهی legacy — با داده تأیید شد
|
||||
|
||||
`CustomerController::updateRemain` (Api/CustomerController.php:42-51):
|
||||
|
||||
```
|
||||
remain = Σ orders.input (sts > 4) − Σ cashes.value (confirmed = 1, type 1–4)
|
||||
rial_remain = Σ orders.rial_input (sts > 4)
|
||||
```
|
||||
|
||||
هر دو مدل `SoftDeletes` دارند، پس حذفشدهها بیروناند. بازمحاسبه روی
|
||||
دامپ: **طلا ۱٬۵۹۰ از ۱٬۵۹۱ مشتری، ریال ۱٬۵۹۱ از ۱٬۵۹۱** با ماندهی ذخیرهشده
|
||||
برابر است. جمع کل ۴۲۷٫۵۰۴۲ گرم — همان عدد پیشبررسی روی سرور زنده.
|
||||
|
||||
سه پیامد که قبلاً دیده نشده بود:
|
||||
|
||||
1. **سند نوع ۹ («سفارش») در بدهی نیست.** بدهی از جدول `orders` میآید؛ نوع ۹
|
||||
فقط آینهی آن در فهرست است. انتقال هر دو = **دوبار شمردن بدهی هر سفارش**.
|
||||
2. **ریال هرگز بدهی ریالی را کم نمیکند.** پرداخت پولی (نوع ۴) با قیمت روز به
|
||||
گرم تبدیل میشود (`price ÷ (price_per_gram ÷ 4.331802)` — قیمت هر مثقال)
|
||||
و بدهی **طلا** را کم میکند.
|
||||
3. **چک (نوع ۳) اثری در مانده ندارد** — مقدار گرمیاش صفر است.
|
||||
|
||||
**تنها استثنا — مشتری `#125`:** ماندهی ذخیرهشده −۹٫۸۹۵۱ گرم، بازمحاسبه صفر.
|
||||
تنها سندش (۴۸٫۳۴ گرم آبشده) در ۲۰۲۱ حذف شده و مشتری در ۲۰۲۲ دوباره
|
||||
ویرایش شده — مانده بهاحتمال زیاد **دستی** وارد شده (ستون در `$fillable`
|
||||
بود، SEC-14). ✅ **تصمیم مالک ۲۰۲۶-۱۰-۰۷:** همان −۹٫۸۹۵۱ منتقل شود، بهصورت
|
||||
یک سند صریح «تراز انتقالی».
|
||||
|
||||
### ✅ تاریخ تولد — پالایش (تصمیم مالک ۲۰۲۶-۱۰-۰۷)
|
||||
|
||||
از ۹۱۵ تاریخ ثبتشده فقط **۵۴۱** واقعی است:
|
||||
|
||||
| دسته | تعداد | چرا کنار گذاشته شد |
|
||||
|---|---|---|
|
||||
| برابر روز ثبتنام | ۱۹۰ | پیشفرض فرم — در سال ۲۰۲۵ از ۱۷۶ مورد، ۱۶۵ |
|
||||
| ساعت دارد یا سال بعد از ۲۰۰۸ | ۱۸۴ | تاریخ تولد نمیتواند باشد |
|
||||
| **نگه داشته شد** | **۵۴۱** | |
|
||||
|
||||
### ✅ شهر — نگاشت دوگانه (تصمیم مالک ۲۰۲۶-۱۰-۰۷)
|
||||
|
||||
ثبتنام اپ روی **همه** `city_id = 5` (تهران) میگذاشت
|
||||
(Major/CustomerController.php:21) و شهر واقعی را در `new_city` بهصورت
|
||||
متن. از ۹۲ مشتری که هر دو را دارند، ۹۱ همان تهرانِ اجباریاند.
|
||||
|
||||
- متن تایپشده هست → عیناً در `Customer.cityNameRaw`؛ `cityId` فقط با تطابق
|
||||
دقیق نام (پس از یکسانسازی «ي/ك») — تهرانِ اجباری نادیده گرفته میشود
|
||||
- متن نیست → همان `city_id` قدیم
|
||||
|
||||
یکسانسازی «ي/ك» اهمیت داشت: تطابق با جدول ۱۵تایی از ۳۲ به ۷۲ رسید.
|
||||
|
||||
### نقشها — تداخل شماره (`config_statics`)
|
||||
|
||||
نوع کاربر در legacy یک ردیف `config_statics` است (UserController.php:26).
|
||||
عناوین: ۸۵ مدیر · ۸۶ **حسابدار** · ۱۰۲ ویرایشگر · ۱۰۴ مدیر اصلی · ۱۰۵ مدیران
|
||||
· ۱۰۸ انباردار · ۱۳۲ بیکار · ۱۳۵ سئو · ۱۳۹ مدیر شعبه.
|
||||
|
||||
🔴 در مقصد (seed) **۸۶ = کارشناس فروش**. کپی شمارهبهشماره دسترسی ۷۱ گانهی
|
||||
حسابدار را به همهی کارشناسان میداد. ابزار **با عنوان** نگاشت میکند
|
||||
(۸۶ حسابدار → ۸۷ حسابدار)؛ فقط ۸۵ با ۸۵ برابر گرفته شده (هر دو نقش
|
||||
تمامدسترسیاند).
|
||||
|
||||
۷ کارشناس فروش با موبایل یک کاربر ادمین مشترکاند — ۳ تا مدیر ارشد.
|
||||
قاعدهی «کارشناس برنده» روی آنها **مدیر ارشد را به کارشناس تنزل میداد و از
|
||||
پنل بیرون میکرد**. ابزار نقش ادمین را نگه میدارد و معرفیها به همان ادمین
|
||||
وصل میشوند.
|
||||
|
||||
### علاقهمندیها — جدول درست `major_favorites` است
|
||||
|
||||
`fav` (۲۵۱) را `Customer\FavController` زیر guard `api-singleCustomer`
|
||||
(ورود مشتری خرده) مینویسد؛ `customer_id` آن به جدول دیگری اشاره دارد. اپ
|
||||
عمده `Major\Favorite` = **`major_favorites`** (۳٬۳۰۵ ردیف) را میخواند
|
||||
(ApiMobileController.php:73-465). ساختار `CustomerFavorite` بیتغییر جواب
|
||||
میدهد؛ فقط منبع عوض شد. کامنت جدول در دیتابیس هنوز «legacy fav» میگوید —
|
||||
در migration بعدی اصلاح شود.
|
||||
|
||||
### سایر یافتهها
|
||||
|
||||
- **زمانها ساعت تهراناند** (`config/app.php:70` → `Asia/Tehran`). ابزار
|
||||
با قواعد ICU تبدیل میکند، با ساعت تابستانی ایران تا ۲۰۲۲.
|
||||
- **۴۷۳ از ۶۱۰ ردیف سفارش زنده** به تنوعِ حذفشده اشاره دارند → تنوع و محصول
|
||||
حذفشدهی ارجاعشده با `isActive = false` منتقل میشوند.
|
||||
- **همهی ۱٬۲۵۰ محصولِ چنددسته** هم در درخت سایت (نوع ۱) هم اپ (نوع ۲)
|
||||
هستند؛ مقصد یک `categoryId` دارد که اپ نشان میدهد → **دستهی اپ** نگه
|
||||
داشته میشود.
|
||||
- **۲۷ گروه موبایل تکراری: در هیچکدام بیش از یک ردیف پول ندارد** و هیچ
|
||||
کارشناسی درگیر نیست → ادغام از نظر مالی بیخطر است.
|
||||
- **سرپرست کارگاه** در legacy مشتری است (`belongsTo(Customer)`)، در مقصد
|
||||
ادمین → پیوند ساخته نمیشود.
|
||||
- **مشتری `#594`** بهجای موبایل کلمهی «تست» دارد؛ با یک سفارش (`#666`،
|
||||
وضعیت ۱، بدون بدهی) کنار گذاشته میشود.
|
||||
- **۶ تنوع** اجرت ریالی (`rial_pay`) دارند؛ مقصد فیلدی برایش ندارد.
|
||||
- **عدد ردشدهها ۷ است، نه ۱۴** (۲ گام دو، ۳ گام یک، ۲ هر دو). عدد ۱۴ در
|
||||
گزارش قبلی اشتباه جمع شده بود.
|
||||
|
||||
---
|
||||
|
||||
## ۱۰.۸ — ابزار انتقال (`apps/api/scripts/legacy-import/`)
|
||||
|
||||
### اجرا
|
||||
|
||||
```
|
||||
cd apps/api
|
||||
npx ts-node --transpile-only scripts/legacy-import/index.ts \
|
||||
--source "mysql://USER:PASS@HOST:PORT/oapi" \
|
||||
--target "postgresql://USER:PASS@HOST:5432/goldbank_import_test" \
|
||||
--images "F:/New folder (2)/storage" --upload-dir "<UPLOAD_DIR مقصد>" \
|
||||
--report ./legacy-import-report.md --yes
|
||||
```
|
||||
|
||||
بدون `--yes` فقط پیشبررسی میکند و چیزی نمینویسد. `--target` هرگز از
|
||||
`.env` خوانده نمیشود. اگر نام دیتابیس مقصد `import` یا `staging` نداشته
|
||||
باشد، `--confirm-db=<همان نام>` هم لازم است.
|
||||
|
||||
### قواعد ایمنی (همه در کد)
|
||||
|
||||
- منبع فقط خوانده میشود.
|
||||
- قبل از اجرا وجود ستونهای migration های آمادهسازی چک میشود.
|
||||
- هرگز نمینویسد: `accounting*` مشتری و محصول، `ProductVariant.imageId`،
|
||||
جداول `Accounting*`. هیچ `ProductImage`ی حذف نمیشود.
|
||||
- ردیفی که از قبل در مقصد بوده (`matched`) فقط فیلدهای **خالیاش** پر میشود.
|
||||
- مستقیم از Prisma مینویسد، نه از سرویسها: **نه پیامکی میرود، نه چیزی به
|
||||
نرمافزار حسابداری صف میشود.**
|
||||
- نگاشت شناسهها در schema جدای `legacy_import.id_map` در مقصد است (بیرون از
|
||||
`public`، پس تغییر schema اپ نیست). اجرای دوباره بهروزرسانی میکند، تکرار
|
||||
نمیسازد؛ اجرایی که نیمهکاره ماند با اجرای بعدی تمام میشود. بعد از
|
||||
جابهجایی: `DROP SCHEMA legacy_import CASCADE` — یا نگه داشته شود برای
|
||||
redirect لینکهای قدیمی محصول.
|
||||
|
||||
### نتیجهی آزمون — ۲۰۲۶-۱۰-۰۷
|
||||
|
||||
مقصد: `goldbank_import_test`، کپی دیتابیس توسعه با ۵۹ مشتری و ۲۸ محصول
|
||||
واقعی (تا ادغام هم آزموده شود). سه اجرای پیاپی:
|
||||
|
||||
| | نتیجه |
|
||||
|---|---|
|
||||
| مشتری ساختهشده | ۱٬۵۰۳ · ادغام با موجود ۱۳ · ادغام تکراری ۳۲ |
|
||||
| بدهی طلا، مشتریهای ساختهشده | **۱٬۵۰۳ از ۱٬۵۰۳ برابر legacy (±۰٫۰۰۰۱ گرم)** |
|
||||
| بدهی ریال | **۱٬۵۰۳ از ۱٬۵۰۳** |
|
||||
| جمع بدهی طلا | legacy ۴۲۷٫۵۰۳۹ · مقصد ۴۲۷٫۵۰۴۱ (دو گِرد ۰٫۰۰۰۱) |
|
||||
| سند تراز انتقالی | فقط مشتری `#125`: بستانکار ۹٫۸۹۵۱ |
|
||||
| دادهی حسابداری (۵۱ مشتری، ۱۸ محصول، ۷۴ پیوند) | **بایتبهبایت یکسان** با دیتابیس توسعه |
|
||||
| `imageId` روی تنوع وارداتی | **۰** |
|
||||
| کارشناس | ۴۹ ساخته شد با پروفایل · ۸ حساب معاملاتی · ۷ ادمین تنزل **نیافت** |
|
||||
| محصول / تنوع | ۱٬۴۷۳ / ۱٬۶۱۲ (شامل ۲۱۵ / ۳۴۷ حذفشدهی غیرفعال برای تاریخچه) |
|
||||
| سفارش / ردیف | ۲۹۹ از ۳۰۰ (`#666` مشتری تست) / ۶۰۸ |
|
||||
| سند مالی | ۸۶ بدهی سفارش + ۹۵ پرداخت تأییدشده + ۸ تأییدنشده |
|
||||
| علاقهمندی | ۸۷۴ (۵۳۴ به محصول حذفشده و ۵۹ به مشتری منتقلنشده کنار رفت) |
|
||||
| سفارش ساختنی | ۲۰ از ۲۰ |
|
||||
| تصویر | ۶٬۱۹۶ فایل (۵۱۸ مگابایت) کپی شد · ۳ فایل در storage قدیم نبود |
|
||||
| اجرای دوم و سوم | **صفر ردیف تکراری** |
|
||||
|
||||
### آنچه این ابزار عمداً منتقل نمیکند
|
||||
|
||||
خردهفروشی (`orders_orders`، `login`، `fav`، `wallets`، `transactions*` —
|
||||
D13 و §۷.۲)، تاریخچهی وضعیت سفارش (`order_activity`)، تخفیفها
|
||||
(`major_promotion*`)، اعلانها، تاریخچهی پیامک (`messages`)، لاگها،
|
||||
نظرات، `cinies`. هرکدام لازم شد، قدم جدا اضافه میشود.
|
||||
|
||||
---
|
||||
|
||||
## ۱۱. جمعبندی — کارهای لازم قبل از نوشتن ابزار
|
||||
|
||||
### 🔴 مسدودکننده (بدون اینها ابزار در میانه میشکند یا داده خراب میکند)
|
||||
@@ -1087,26 +1699,32 @@ orders_orders 520 live retail_sts: 7 → ۳ ردیف
|
||||
| # | مورد | § |
|
||||
|---|---|---|
|
||||
| ۱ | ~~شمارش تکرار~~ | ✅ **انجام شد** — ۲۷ گروه موبایل، ۰ کد ملی (§۱۰.۴) |
|
||||
| ۱.۱ | 🔴 **`nationalCode` باید nullable شود** — هر ۱٬۵۹۵ ردیف تهی است | ۱۰.۴ |
|
||||
| ۱.۲ | 🔴 **`passwordHash`** — ۱٬۵۹۰ تهی؛ hash تصادفی یا nullable | ۱۰.۴ |
|
||||
| ۱.۳ | 🔴 **مبلغ سند مالی کجاست؟** `cashes.remain` همه `NULL` | ۱۰.۶ |
|
||||
| ۱.۴ | 🔴 **`VerificationStep` حالت `REJECTED` ندارد** — ۱۴ ردیف | ۵.۵ |
|
||||
| ۱.۵ | 🔴 **ترتیب دومرحلهای** — کارشناسان قبل از مشتریان | ۵.۷ |
|
||||
| ۲ | آستانهی تطبیق عددی جای «صفر اختلاف» — **تأیید شد: ۵۶ ردیف گِرد میشوند** | ۴ · ۱۰.۴ |
|
||||
| ۳ | قاعدهی `WHERE deleted_at IS NULL` — **حیاتیتر از انتظار: ۴۵٪ واریانتها** | ۵.۸ · ۱۰.۴ |
|
||||
| ۱.۱ | ~~`nationalCode`~~ | ✅ **حل — nullable شود** (§۱۰.۴) |
|
||||
| ۱.۲ | ~~`passwordHash`~~ | ✅ **حل — hash غیرقابلورود** (§۱۰.۴) |
|
||||
| ۱.۳ | ~~مبلغ سند کجاست~~ | ✅ **حل — فرمول بدهی legacy با داده تأیید شد** (§۱۰.۷) |
|
||||
| ۱.۴ | ~~`REJECTED`~~ | ✅ **حل — enum + دو ستون علت** (§۵.۵) |
|
||||
| ۱.۵ | ~~ترتیب دومرحلهای~~ | ✅ **در ابزار** — کارشناسان قبل از مشتریان (§۱۰.۸) |
|
||||
| ۱.۶ | ~~`birth_date`~~ | ✅ **حل — پالایش، ۵۴۱ از ۹۱۵** (§۱۰.۷) |
|
||||
| ۱.۷ | ~~`customers.type` ۳/۴/۵~~ | ✅ **سؤال لازم نبود** — در `Customer::$TYPES` تعریف شدهاند (§۵.۳) |
|
||||
| ۲ | ~~آستانهی تطبیق~~ | ✅ **در ابزار** — ±۰٫۰۰۰۱ گرم، ±۱ ریال (§۱۰.۸) |
|
||||
| ۳ | ~~قاعدهی `deleted_at`~~ | ✅ **در ابزار** — بهجز حذفشدههای ارجاعشده در سفارش (§۱۰.۷) |
|
||||
| ۴ | ~~تصمیم `orders_orders`~~ | ✅ **حل — به تأخیر افتاد** (§۷.۲) |
|
||||
| ۵ | تصحیح D0: `fname`/`lname` مستقیم، تجزیه نشود | ۲ |
|
||||
| ۶ | **allow-list ستونهای نوشتنی** — ۷ ستون مقصد-تنها لمس نشوند | **۱۰.۵** |
|
||||
| ۷ | **کلید تطبیق ردیفهای موجود مقصد** | **۱۰.۵** |
|
||||
| ۵ | ~~تصحیح D0~~ | ✅ **در ابزار** — `fname`/`lname` مستقیم |
|
||||
| ۶ | ~~allow-list ستونها~~ | ✅ **در ابزار** — حسابداری بایتبهبایت یکسان ماند (§۱۰.۸) |
|
||||
| ۷ | ~~کلید تطبیق~~ | ✅ **موبایل** (مالک) — ادمین تنزل نمییابد (§۱۰.۷) |
|
||||
|
||||
### 🔶 تصمیم مالک
|
||||
|
||||
| # | مورد | § |
|
||||
|---|---|---|
|
||||
| ۱ | ۴ ستون دادهی غیرقابلبازسازی (`birth_date`, `marriage_date`, `token_mobile`, `new_city`) | ۵.۲ |
|
||||
| ۲ | `verificationStep` — تفکیک `STEP_TWO_SUBMITTED` از `VERIFIED` | ۵.۵ |
|
||||
| ۳ | `type IS NULL` چه `CustomerKind` شود | ۵.۳ |
|
||||
| ۴ | ~~`fav`~~ | ✅ **حل — لازم است، migration افزایشی** (§۱۰) |
|
||||
| ۱ | ~~۴ ستون دادهی غیرقابلبازسازی~~ | ✅ **حل — تولد و شهر منتقل، توکن و سالگرد حذف** (§۵.۲) |
|
||||
| ۱.۱ | ~~`new_city`~~ | ✅ **حل — نگاشت دوگانه: متن در `cityNameRaw` + `cityId` با تطابق دقیق** (مالک · §۱۰.۷) |
|
||||
| ۲ | ~~تفکیک `STEP_TWO_SUBMITTED` از `VERIFIED`~~ | ✅ **حل** (§۵.۵) |
|
||||
| ۳ | ~~`type IS NULL`~~ | ✅ **`APP_SHOPKEEPER`** — ثبتنام اپ `type = 2` میگذارد (Major/CustomerController.php:44)؛ NULL قدیمیتر از آن است |
|
||||
| ۴ | ~~علاقهمندی~~ | ✅ **حل — از `major_favorites`، نه `fav`** (§۱۰.۷) |
|
||||
| ۴.۲ | ~~مشتری `#125`~~ | ✅ **همان −۹٫۸۹۵۱ با سند تراز انتقالی** (مالک · §۱۰.۷) |
|
||||
| ۴.۳ | 🔶 **رد در پنل جدید `REJECTED` نمینویسد** و مشتری ردشده با ارسال دوباره خودکار تأیید میشود | §۱۰.۵.۵ |
|
||||
| ۴.۴ | 🔶 **مدیر ارشدی که کارشناس هم بود** — نقش ادمین نگه داشته شد؛ آیا حساب کارشناسی هم لازم است؟ | §۱۰.۷ |
|
||||
| ۴.۱ | `cinies`/`ciny_products` — چیدمان نمایشی | ۱۰ |
|
||||
| ۵ | شمارندههای denormalized محاسبه شوند یا صفر بمانند | ۵.۲ |
|
||||
| ۶ | نسخههای تغییراندازهیافتهی تصویر | ۹ |
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
-- ============================================================================
|
||||
-- پیشبررسی سوم — فقط دو سؤال باقیمانده
|
||||
-- ============================================================================
|
||||
--
|
||||
-- ⚠️ فقط SELECT COUNT. صفر INSERT/UPDATE/DELETE. هیچ ستون متنی در خروجی.
|
||||
--
|
||||
-- اجرا:
|
||||
-- mysql -u USER -p -h HOST -P 3305 oapi < migration-precheck-3.sql > out3.txt
|
||||
--
|
||||
-- مرجع: docs/DATA-MIGRATION-MAP.md §۵.۹
|
||||
-- ============================================================================
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- سؤال: new_city باید به cityId نگاشت شود یا ستون جدا بگیرد؟
|
||||
--
|
||||
-- تصمیم مالک: «یا در فیلد شهر بنشیند یا در یک فیلد آدرس متنی مپ شود».
|
||||
-- کدامیک، به این بستگی دارد که آیا این ۱۷۶ ردیف city_id هم دارند یا نه:
|
||||
--
|
||||
-- فقط new_city (city_id تهی) → ستون متنی لازم است، چون شهر در جدول cities نیست
|
||||
-- هر دو را دارند → new_city تکراری است، میتوان رهایش کرد
|
||||
-- ---------------------------------------------------------------------------
|
||||
SELECT '=== new_city vs city_id ===' AS section;
|
||||
|
||||
SELECT
|
||||
SUM(new_city IS NOT NULL AND new_city <> '' AND city_id IS NULL) AS only_new_city,
|
||||
SUM(new_city IS NOT NULL AND new_city <> '' AND city_id IS NOT NULL) AS both_set,
|
||||
SUM((new_city IS NULL OR new_city = '') AND city_id IS NOT NULL) AS only_city_id,
|
||||
SUM((new_city IS NULL OR new_city = '') AND city_id IS NULL) AS neither
|
||||
FROM customers WHERE deleted_at IS NULL;
|
||||
|
||||
-- از آن ۱۷۶ ردیف، چندتا متنیشان با عنوان یک شهر موجود در `cities` یکی است؟
|
||||
-- اگر بالا باشد، اکثرشان قابل تبدیل به city_id هستند و ستون متنی لازم نیست.
|
||||
SELECT 'new_city matches an existing cities.title' AS metric, COUNT(*) AS n
|
||||
FROM customers c
|
||||
-- The two columns have different collations (unicode_ci vs general_ci), so
|
||||
-- both sides are pinned to one; without it MySQL refuses the comparison.
|
||||
JOIN cities ci ON TRIM(ci.title) COLLATE utf8mb4_general_ci = TRIM(c.new_city) COLLATE utf8mb4_general_ci
|
||||
WHERE c.deleted_at IS NULL AND c.new_city IS NOT NULL AND c.new_city <> ''
|
||||
AND c.city_id IS NULL;
|
||||
|
||||
-- چند مقدار متمایز؟ (عدد است، نه متن — اگر کم باشد نگاشت دستی ممکن است)
|
||||
SELECT 'distinct_new_city_values' AS metric, COUNT(DISTINCT TRIM(new_city)) AS n
|
||||
FROM customers WHERE deleted_at IS NULL AND new_city IS NOT NULL AND new_city <> '';
|
||||
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- سؤال: birth_date — آیا تاریخها معتبرند؟
|
||||
--
|
||||
-- ستون timestamp است. ولی اگر تاریخ جلالی بهاشتباه بهعنوان میلادی
|
||||
-- ذخیره شده باشد، سالها ۱۳xx میشوند که در timestamp جا نمیشوند،
|
||||
-- یا به مقادیر عجیب تبدیل شدهاند.
|
||||
-- ---------------------------------------------------------------------------
|
||||
SELECT '=== birth_date sanity ===' AS section;
|
||||
|
||||
SELECT
|
||||
COUNT(birth_date) AS total_set,
|
||||
SUM(YEAR(birth_date) < 1900) AS year_before_1900,
|
||||
SUM(YEAR(birth_date) BETWEEN 1900 AND 1950) AS year_1900_1950,
|
||||
SUM(YEAR(birth_date) BETWEEN 1951 AND 2010) AS year_1951_2010,
|
||||
SUM(YEAR(birth_date) > 2010) AS year_after_2010,
|
||||
CAST(MIN(YEAR(birth_date)) AS CHAR) AS min_year,
|
||||
CAST(MAX(YEAR(birth_date)) AS CHAR) AS max_year
|
||||
FROM customers WHERE deleted_at IS NULL;
|
||||
|
||||
SELECT '=== END ===' AS section;
|
||||
@@ -11,6 +11,7 @@
|
||||
| `docs/GO-LIVE-PLAN.md` | Stack upgrade, release isolation, data migration and cutover from the live henza system. **§0 explains how to continue on another machine.** | Owner go-ahead per step |
|
||||
| `docs/PWA-PORT-PLAN.md` | Third user app `apps/user-app-classic`: a pixel-exact port of `henza_pwa@b171fff` onto the new API. | Owner rulings on its tensions 1–5 and Q1–Q9 |
|
||||
| `docs/ACCOUNTING-INTEGRATION-PLAN.md` | Tahesab / Zarrin integration, switchable in the admin panel (D27). **Implemented 2026-10-05**, off until switched on; progress in its §10. | Zarrin trial on a real install (ACC-01); ACC-03 ruling |
|
||||
| `docs/DATA-MIGRATION-MAP.md` | Column-by-column map of the live henza MySQL schema (`oapi-struncture.sql`, 80 tables) onto Prisma, checked against real row counts via the read-only `docs/migration-precheck*.sql`. Branch `migration/legacy-data`. **2026-10-07:** additive prep migration applied (nullable `nationalCode`, `birthDate`, rejection trail + `REJECTED`, `CustomerFavorite`), bcrypt guard, REJECTED consumer audit. ⚠ On this machine a file in `prisma/migrations` is applied by the watch-mode dev server on the next `src/` edit — see its §10.5.5. | `precheck-2` (where the ledger amount lives) and `precheck-3` output; two `verify()` rulings |
|
||||
|
||||
The "Current state" table below is the parity project's and was last updated 2026-09-22.
|
||||
|
||||
|
||||
Generated
+71
@@ -154,6 +154,9 @@ importers:
|
||||
jest:
|
||||
specifier: ^30.5.2
|
||||
version: 30.5.2(@types/node@20.19.43)(ts-node@10.9.2(@types/node@20.19.43)(typescript@5.9.3))
|
||||
mysql2:
|
||||
specifier: ^3.24.5
|
||||
version: 3.24.5(@types/node@20.19.43)
|
||||
prisma:
|
||||
specifier: ^5.19.0
|
||||
version: 5.22.0
|
||||
@@ -2425,6 +2428,10 @@ packages:
|
||||
resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
aws-ssl-profiles@1.1.2:
|
||||
resolution: {integrity: sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==}
|
||||
engines: {node: '>= 6.0.0'}
|
||||
|
||||
axios@1.20.0:
|
||||
resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==}
|
||||
|
||||
@@ -3171,6 +3178,9 @@ packages:
|
||||
functions-have-names@1.2.3:
|
||||
resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==}
|
||||
|
||||
generate-function@2.3.1:
|
||||
resolution: {integrity: sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==}
|
||||
|
||||
generator-function@2.0.1:
|
||||
resolution: {integrity: sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -3309,6 +3319,10 @@ packages:
|
||||
resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
iconv-lite@0.7.3:
|
||||
resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
idb@7.1.1:
|
||||
resolution: {integrity: sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==}
|
||||
|
||||
@@ -3445,6 +3459,9 @@ packages:
|
||||
resolution: {integrity: sha512-Xnpx182SBMrr/aBik8y+GuR4U1L9FqMSojwDQwPMmxyC6bvEqly9UBCxhauBF5vNh2gwWJNX6oDV7O+OM4z34g==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
is-property@1.0.2:
|
||||
resolution: {integrity: sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==}
|
||||
|
||||
is-regex@1.2.1:
|
||||
resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -3785,6 +3802,9 @@ packages:
|
||||
resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
long@5.3.2:
|
||||
resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==}
|
||||
|
||||
loose-envify@1.4.0:
|
||||
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
|
||||
hasBin: true
|
||||
@@ -3799,6 +3819,10 @@ packages:
|
||||
lru-cache@5.1.1:
|
||||
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
|
||||
|
||||
lru.min@1.1.5:
|
||||
resolution: {integrity: sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==}
|
||||
engines: {bun: '>=1.0.0', deno: '>=1.30.0', node: '>=8.0.0'}
|
||||
|
||||
magic-string@0.30.21:
|
||||
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
|
||||
|
||||
@@ -3924,6 +3948,16 @@ packages:
|
||||
resolution: {integrity: sha512-avsJQhyd+680gKXyG/sQc0nXaC6rBkPOfyHYcFb9+hdkqQkR9bdnkJ0AMZhke0oesPqIO+mFFJ+IdBc7mst4IA==}
|
||||
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
|
||||
|
||||
mysql2@3.24.5:
|
||||
resolution: {integrity: sha512-X6Ujsr2QSkkLpkQGjxzpKRAPn9nu4axpR63ntBzquFVEvPOArgbUQ1sJjFKI7hnaYtiVZxa17Z7q18KSubW0IQ==}
|
||||
engines: {node: '>= 8.0'}
|
||||
peerDependencies:
|
||||
'@types/node': '>= 8'
|
||||
|
||||
named-placeholders@1.1.6:
|
||||
resolution: {integrity: sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==}
|
||||
engines: {node: '>=8.0.0'}
|
||||
|
||||
nanoid@3.3.18:
|
||||
resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==}
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
@@ -4484,6 +4518,10 @@ packages:
|
||||
sprintf-js@1.0.3:
|
||||
resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==}
|
||||
|
||||
sql-escaper@1.5.2:
|
||||
resolution: {integrity: sha512-6CKD38c31SENivxOADeMNLdukOnUxUcflKtzVWzace7Riv1v7cAEym5Cx9Q7gYZ3ezIJI7ZpqecQq8cqNeSSFg==}
|
||||
engines: {bun: '>=1.0.0', deno: '>=2.0.0', node: '>=12.0.0'}
|
||||
|
||||
ssr-window@4.0.2:
|
||||
resolution: {integrity: sha512-ISv/Ch+ig7SOtw7G2+qkwfVASzazUnvlDTwypdLoPoySv+6MqlOV10VwPSE6EWkGjhW50lUmghPmpYZXMu/+AQ==}
|
||||
|
||||
@@ -7425,6 +7463,8 @@ snapshots:
|
||||
dependencies:
|
||||
possible-typed-array-names: 1.1.0
|
||||
|
||||
aws-ssl-profiles@1.1.2: {}
|
||||
|
||||
axios@1.20.0:
|
||||
dependencies:
|
||||
follow-redirects: 1.16.0
|
||||
@@ -8320,6 +8360,10 @@ snapshots:
|
||||
|
||||
functions-have-names@1.2.3: {}
|
||||
|
||||
generate-function@2.3.1:
|
||||
dependencies:
|
||||
is-property: 1.0.2
|
||||
|
||||
generator-function@2.0.1: {}
|
||||
|
||||
gensync@1.0.0-beta.2: {}
|
||||
@@ -8464,6 +8508,10 @@ snapshots:
|
||||
safer-buffer: 2.1.2
|
||||
optional: true
|
||||
|
||||
iconv-lite@0.7.3:
|
||||
dependencies:
|
||||
safer-buffer: 2.1.2
|
||||
|
||||
idb@7.1.1: {}
|
||||
|
||||
ieee754@1.2.1: {}
|
||||
@@ -8617,6 +8665,8 @@ snapshots:
|
||||
|
||||
is-plain-object@3.0.1: {}
|
||||
|
||||
is-property@1.0.2: {}
|
||||
|
||||
is-regex@1.2.1:
|
||||
dependencies:
|
||||
call-bound: 1.0.4
|
||||
@@ -9150,6 +9200,8 @@ snapshots:
|
||||
chalk: 4.1.2
|
||||
is-unicode-supported: 0.1.0
|
||||
|
||||
long@5.3.2: {}
|
||||
|
||||
loose-envify@1.4.0:
|
||||
dependencies:
|
||||
js-tokens: 4.0.0
|
||||
@@ -9162,6 +9214,8 @@ snapshots:
|
||||
dependencies:
|
||||
yallist: 3.1.1
|
||||
|
||||
lru.min@1.1.5: {}
|
||||
|
||||
magic-string@0.30.21:
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
@@ -9268,6 +9322,21 @@ snapshots:
|
||||
|
||||
mute-stream@1.0.0: {}
|
||||
|
||||
mysql2@3.24.5(@types/node@20.19.43):
|
||||
dependencies:
|
||||
'@types/node': 20.19.43
|
||||
aws-ssl-profiles: 1.1.2
|
||||
generate-function: 2.3.1
|
||||
iconv-lite: 0.7.3
|
||||
long: 5.3.2
|
||||
lru.min: 1.1.5
|
||||
named-placeholders: 1.1.6
|
||||
sql-escaper: 1.5.2
|
||||
|
||||
named-placeholders@1.1.6:
|
||||
dependencies:
|
||||
lru.min: 1.1.5
|
||||
|
||||
nanoid@3.3.18: {}
|
||||
|
||||
nanopop@2.4.2: {}
|
||||
@@ -9847,6 +9916,8 @@ snapshots:
|
||||
|
||||
sprintf-js@1.0.3: {}
|
||||
|
||||
sql-escaper@1.5.2: {}
|
||||
|
||||
ssr-window@4.0.2: {}
|
||||
|
||||
stack-utils@2.0.6:
|
||||
|
||||
Reference in New Issue
Block a user