Giao diện
Nhật ký quyết định kiến trúc
Trang sinh tự động
Nguồn: docs/technical/02-environment.md §2 — bảng nhật ký quyết định của dự án. Nội dung giữ nguyên văn, bộ sinh chỉ nhóm theo tháng và sắp mới nhất lên trước.
106 quyết định, từ 2026-08-25 đến 2026-11-11.
Đây là nơi đọc trước khi đề xuất thay đổi kiến trúc: nó ghi điều gì đã được quyết và điều gì đã bị thay thế. Một quyết định cũ không bị xoá — nó được đánh dấu là đã bị thay thế bởi quyết định mới hơn.
2026-11 (13)
2026-11-11 — Payments that need a person reach Finance; the intent recovery sweep is timed everywhere; the close waits at most one session + 15 minutes (#479 T6, owner decisions of the 10/11 payment audit). (1) payment.intent_recover runs every PAYMENT_INTENT_RECOVER_EVERY_MINUTES (1-60, default 1) in every environment, test mode or not (needs its budget and limits as before); supersedes "production keeps it ON_DEMAND" of the 2026-10-21 row. (2) paymentsNeedingAttention (Finance, F-01 payment.read): intents UNKNOWN for more than PAYMENT_ATTENTION_UNKNOWN_AFTER_MINUTES (default 30), intents NEEDS_REVIEW, deposit checkouts COMPENSATION_REJECTED, with counts. (3) A campaign close waits for a live deposit attempt started before closes_at at most PAYMENT_SESSION_TTL_MINUTES + PAYMENT_CLOSE_WAIT_GRACE_MINUTES (default 15) after closes_at, then fails the attempt and cancels the order as unpaid at the close; without a session TTL there is no cap (the 24 h deposit window still bounds it). An UNKNOWN attempt still holds the close (money may have moved). campaignOverview.closePaymentWait shows the wait. Migration 20261231030300.
2026-11-11 — The 24 h deposit expiry asks the provider first; no new deposit attempt shorter than one session (#479 T2). Before failing a live attempt the payment.order_expiry job queries the provider: SUCCEEDED is applied (the order is placed), still pending is cancelled (cancelPayment, MOCK no-op) and failed, no answer moves a PENDING attempt to UNKNOWN for the payment.intent_recover sweep (the order is not cancelled). With PAYMENT_SESSION_TTL_MINUTES set, startDepositCheckout refuses a new attempt (deposit_window_closing) when the order's window ends sooner than one session. Migration 20261231030400.
2026-11-11 — One row-lock order for a deposit: order → payment obligation → payment intent (#479 T10). The callback cores (payment.observe_core, payment.attempt_core) locked intent → order and then wrote the obligation, while the buyer cancel, the 24 h / close expiry and the 0 VND placement locked obligation → intents → order: a callback success racing a buyer cancel could deadlock (reproduced, 40P01). All five now take order → obligation → intent (migration 20261231030500, the order most order + obligation writers already use); the provider callback applies a verified observation once more on 40P01. shortage.order_cancel_gate keeps its NOWAIT locks (it never waits).
2026-11-11 — The MoMo session lasts 15 minutes unless configured (#479 item 1, FuncSpec). PAYMENT_SESSION_TTL_MINUTES defaults to 15 (1..1440; an invalid value is logged and the default kept). Supersedes "no default" of G2I-P3-01 (E8) and the "no TTL = no cap / no refusal" clauses of the two rows above: PaymentIntent.expiresAt, the close-wait cap (TTL + PAYMENT_CLOSE_WAIT_GRACE_MINUTES, 30 minutes with both defaults) and the deposit_window_closing refusal now run in every environment. No migration.
2026-11-11 — The online remaining payment start locks order → obligation → intent too (#479 item 3, follows T10). payment.buyer_open_remaining_intent locked the REMAINING obligation before the order (through the PAF-P1-25 resync), the reverse of the callback cores: a callback of an earlier attempt of the same Mua định kỳ order could deadlock with it. Migration 20261231040000. Checked and unchanged: ordering.drop_order_points (already order-first; a NEEDS_REVIEW deposit attempt still counts as payment_pending) and payment.refundable_points (does not subtract a CREDIT ADJUST; the FU-1822 fence refuses the second return, no double count).
2026-11-11 — At the close cap the provider is asked first, and an UNKNOWN attempt is capped too (#479 item 2). Before the close transaction, the Group outcome and the Recurring close jobs list the deposit attempts the close no longer waits for (payment.system_close_capped_intents: CREATED / PENDING started before closes_at and every UNKNOWN, once closes_at + TTL + grace has passed) and query the provider: SUCCEEDED / FAILED is applied like a callback, a pending session is cancelled (cancelPayment) and failed by the close as before, an UNKNOWN attempt the provider does not settle is failed CLOSE_WAIT_CAPPED (a later capture is a LATE_CAPTURE for Finance) and its deposit checkout advanced. Supersedes "an UNKNOWN attempt still holds the close" of the T6 row; a waiting close also reruns at the cap for an UNKNOWN attempt. Migration 20261231040100.
2026-11-11 — The provider contract is pinned on the MOCK; live and sandbox stay behind their own enable flag (#479 item 4, owner 10/11 "MoMo behind a flag"). A create answered DUPLICATE is UNKNOWN then queried (never FAILED); a retryable error leaves it CREATED, an unknown error UNKNOWN; one sender per intent (payment_intent_leases, SEND / CAPTURE held during the call, QUERY kept as the rate limit). UNKNOWN → PENDING is allowed when the provider says pending. The session (payUrl, deeplink, qrData, the provider's expiry) is stored once (payment_intent_sessions). A reused provider event id is compared on intent, type, status, transaction and amount: the same content is DUPLICATE, another content is recorded (payment_event_conflicts, Finance attention) and never applied. An observation in another currency, with a malformed amount or another request id is refused. Two-step AUTHORIZED is captured only outside the callback, under the CAPTURE lease, when the order is still payable (a live CAPTURE lease blocks the 24 h expiry), else the hold is cancelled. The buyer's cancelPaymentSession (T14) closes a session; the buyer's paymentStatus re-check asks the provider at most once per PAYMENT_STATUS_RECHECK_SECONDS (default 15) and never opens, captures or cancels. Supersedes wave 1's no-op mock cancelPayment and "DUPLICATE / ERROR create = FAILED". Migration 20261231040200.
2026-11-11 — A NEEDS_REVIEW attempt leaves the Finance attention list once its capture is resolved (#479 T6 follow-up). Listed only while a SUCCEEDED CAPTURE has allocations below its amount and no SUCCEEDED REFUND (the payment.unapplied_captures rule); each item carries the customer (name, masked phone) like the Admin order list. Migration 20261231040300.
2026-11-11 — A checkout follows its intent back to PENDING; the hold of a FAILED two-step attempt is released, never captured (#479, coordinator 11/11). CASH_UNKNOWN -> CASH_PENDING (table guard and TS machine) when the cash intent is PENDING again, so the expiry and the compensation run as for a pending session. The recovery sweep releases the provider hold (AUTHORIZED, nothing captured) of a FAILED intent with cancelPayment under the intent's CAPTURE lease row, records each attempt (payment_hold_releases), retries on its backoff and after PAYMENT_INTENT_RECOVER_HOLD_RELEASE_ATTEMPTS (default 6) lists it for Finance (HOLD_RELEASE_FAILED). Kept: the 30-day window of PROVIDER_EVENT_CONFLICT; a NEEDS_REVIEW capture with a refund in progress stays listed. Migrations 20261231040400, 20261231040500, 20261231040600.
2026-11-03 — Web Admin staff are STAFF accounts with a multi-step sign-in; Web Admin has no self sign-up and no OTP reset (#428, owner decisions 26/10 and 02/11/2026, round 2026-10-26-pipoint-integration: D-14, D-15, D-16, D-17, D-18, E-05, E-06, B-02, B-03, B-07; DEC-PPI-* in docs/decisions/decisions.csv). A Web Admin employee is a separate accounts row of kind STAFF (same phone as a customer allowed: unique (phone_e164, kind)), holding only WEB_ADMIN, with its own credential staff_credentials. Admins create staff (createStaffAccount + approval; since P7 the account is ACTIVE at once and only the role is approved, see the P7 row below) and issue a one-time temporary password (auth/staff/temporary-password, 72 h); sign-in answers CHALLENGE (password change, TOTP enroll or verify) before any session. /sign-up/* and /password-reset/* refuse WEB_ADMIN (self_registration_disabled). Lost access is the operator break-glass. Conflict-of-interest checks compare people (identity.same_person), not account ids. Old admins were moved to STAFF accounts by the operator script and the flag (WEB_ADMIN_STAFF_AUTH, removed by P7, see below) turned on: dev and staging on 2026-11-03 (MFA enrolled again). Supersedes in part the 2026-10-10 row ("one account, one phone, every app": a staff member now has a second account) and AUTH-01's Admin registration (decisions.csv AUTH-01, DEC-S-ADMIN-CREATED). Details: 03 §10.2, runbook 14.
2026-11-03 — User App can sign in through PiPoint; PIDEAL keeps the session; the password path stays until the mobile cutover (#428, D-03, D-04, D-05 / E-01, D-08 / E-03, D-09, D-10, D-22, D-23, B-06, B-08, GAP-PPI-01). POST auth/pipoint/exchange (behind PIPOINT_AUTH_ENABLED, APP_USER only) verifies a PiPoint ID token (RS256, project fixed per PI_ENVIRONMENT) and issues the usual PIDEAL session: link by uid, auto-link by phone to the CUSTOMER account, else a new account (phone or email); refresh then needs pipointIdToken. PIPOINT_AUTH_REQUIRED_APP_USER closes the User App password routes (use_pipoint); it is off (unset) everywhere. The exchange is on in dev and staging since 2026-11-03; uat and production off. Sale App is unchanged (paused). A PiPoint account.deleted closes the customer account and the same phone comes back as a new person (DEC-PPI-OWN03-PIPOINT-DELETED-NEW-PERSON, replacing the "delete nothing" part of D-19 / E-10). DEC-OWN22-ACCOUNT-MINIMAL (22/10) is no longer binding since 26/10 (D-22; superseded in decisions.csv). Details: 03 §10.1.
2026-11-03 — PiPoint server to server: one service account per environment, pipoint-events, an eKYC trust list; the live wallet runs on dev and staging (#428, D-01, D-02, D-06, D-07 / E-02, D-23, W-01..W-08, DEC-PPI-OWN03-DOC-ALIGN). Backend calls walletPlatform-ledger and ekycPlatform-review with a Google ID token minted from PIPOINT_SA_KEY_B64 (_shared/pipoint/; never read by auth); PiPoint pushes account events to the pipoint-events function (Pub/Sub OIDC, PIPOINT_EVENTS_AUDIENCE / PIPOINT_EVENTS_PUSH_SA), which records receipts for job pipoint.account_event. PIPOINT_EKYC_TRUSTED_VIA: local / dev auto,manual:*,dev, staging / uat / production auto,manual:* (prod re-checked at release, R-20 / L-01); a missing or wrong value stops boot. Pending points stay PIDEAL's (D-01: only RELEASE credits PiPoint); a debit beyond the balance is refused (D-02, no negative balance, W-07). The deploy preflight requires the four PiPoint names when PiPoint is on (18 §6.1). PIPOINT_MODE=live on dev (backend smoke: ledger read 200) and on staging (project pipointstg, daily reconciliation SUCCEEDED through the service account) since 2026-11-03: supersedes for dev and staging "no PiPoint provider" of DEC-377-PIPOINT-OPEN-PORTS (2026-10-22 row); the open ports still apply wherever PiPoint is off (uat, production). The staging push service account is an ASSUME until PiPoint confirms it (no pushed event received yet). Runbooks: 16 §7.
2026-11-03 — PPI phase P7: the round is simplified; the staff add flow is one step plus a role approval (#428, owner 03/11/2026: DEC-PPI-OWN03-SIMPLIFY and its children in docs/decisions/decisions.csv). (1) DEC-PPI-OWN03-STAFF-ADD-FLOW: createStaffAccount opens the WEB_ADMIN membership ACTIVE and files the role request; the temporary password is shown once to the creator; the new person signs in (password change, MFA) and waits on "Chưa có quyền" until another person approves the role (super_admin only by a super_admin); reject = role request REJECTED + account locked; approveMembership is no longer a staff step (@deprecated). (2) DEC-PPI-OWN03-DROP-STAFF-LINK: the staff ↔ customer link (SCL-01..03) and the 13 identity.distinct_person_guard triggers are gone; "same person" = same account or same phone (L1 noSelf, L2 identity.same_person in SQL, L3 CHECKs stay); supersedes DEC-PPI-OWN03-STAFF-LINK-LOOKUP and DEC-PPI-OWN02-STAFF-LINK-SCOPE. (3) DEC-PPI-OWN03-DROP-STAFF-FLAG: WEB_ADMIN_STAFF_AUTH, the old WEB_ADMIN sign-in and rollback-legacy-admins.sql are removed; supersedes the flag parts of the row above and of DEC-PPI-OWN02-WEBADMIN-SIGNUP-CLOSED (the closure itself stays); uat and production must run migrate-legacy-admins.sql before they get an auth build without the flag (14 "No rollback"). (4) DEC-PPI-OWN03-UNLINK-OPERATOR: the Admin maker/checker PiPoint unlink tool (PPL-01..03) is replaced by the operator script scripts/operator/pipoint-unlink.sql (runbook 16 §7.6); re-link is automatic (REBIND_AFTER_UNLINK); supersedes DEC-PPI-GAP-05. (5) DEC-PPI-OWN03-POINT-FORMS-SIMPLE: point slips and rank-only debits carry no evidence and no typed reason code; a return recall is written PENDING (no DRAFT, no submitPointAdjustDraft); a rank-only debit is made only from a slip PiPoint refused for insufficient points; forms open from context and lists show name + masked phone. (6) DEC-PPI-OWN03-SETTLE-OPEN-LINES: open discrepancy lines no longer block the monthly settle (shown, kept on the settled row); a REDEEM debit reads the stored eKYC snapshot instead of calling PiPoint. Kept: the "Chưa có quyền" screen, the per-IP exchange limit, the 7 PiPoint tuning env names, the point recipient role (2 options, default customer). Migrations 20261230060000..060400.
2026-10 (34)
2026-10-28 — pi_ui may draw the design's colour illustrations with flutter_svg (#412, owner decision 28/10/2026). The User App design 27/10 draws its illustrations (G1-01 steps, gift, people; later G1-06/G1-09) as SVG inside the frame HTML. They are lifted as drawn into packages/app-ui/assets/illustrations/ and shown through PiIllustration; flutter_svg is a dependency of pi_ui only, apps keep importing the kit barrel. The artwork keeps its own palette (not PiTokens).
2026-10-28 — Product attribute order is per product, not per category (#411, owner decision 28/10/2026, round 2026-10-28-product-specs-order-table, DEC-OWN28-SPECS-ORDER). Reverses Q3/L2 of DEC-PSW-SPECS-MODULE (2026-10-26 row): the Admin drags a product's attribute rows on the product form, the saved order is the display order in Admin, export, import (order inside the cell, as the Word 23/10 says) and campaign.public_highlighted_specs; the category's configured order only seeds required attributes added up front and the backfill. The rest of the attribute module stands. Thông số and Phụ kiện kèm theo render as tables (form and view), Phụ kiện reorderable too (no API change).
2026-10-27 — User App Mua chung follows the FuncSpec Mua hàng 27/10, which replaces the older Word rules where they differ (#407, owner decisions 27/10/2026, round 2026-10-27-user-app-group1-funcspec). For the User App group-buy flow, business logic and constraints come from 20261027_AppUserMuahang_FuncSpec.pdf (formulas, rounding, states, mandatory consent, reward timing, order-then-pay sequence, notifications); the design snapshot 27/10 keeps its UI/UX improvements only where no rule is lost. This replaces the 22/10 rule "User App: design wins over documents". Where the FuncSpec and the older Word Đơn hàng/Chiến dịch differ, the FuncSpec wins: the deposit rounds up to 1đ, with existing orders keeping half-up through a marker column (DEC-OWN27-DEPOSIT-CEIL), and Mua chung rewards become available on delivery (DEC-OWN27-MC-REWARD-TIMING). The order is written before the price check, and a price change or a dropped Pi-Point hold updates the same order, keeping its code and due time (DEC-OWN27-QUOTE-UPDATES-ORDER, DEC-OWN27-ORDER-FIRST, DEC-OWN27-POINTS-DROP-SAME-ORDER). Web Admin items without a Product document are seeded, not built: home stats in system_settings (DEC-OWN27-HOME-STATS-SETTINGS, replaces DEC-OWN26-HOME-SAMPLE-STATS) and deal terms through an operator script (DEC-OWN27-TERMS-OPS-SCRIPT). Every verdict is a DEC-OWN27-* row in decisions.csv.
2026-10-26 — Product attributes (Thông số sản phẩm) are a category-scoped catalog module, not free text on the product; units gain conversion (#397, owner decisions 24–26/10/2026, round 2026-10-26-product-specs-word-2310, ADR 0006). Product's Word 23/10 (quan-ly-san-pham-nganh-hang-thuong-hieu-v2.docx, story 01-quan-ly-san-pham-v2.md) is the requirement source for Products, except where the owner replaced it: an attribute belongs to at most one category (null = Chung), inherits down the tree, is typed (TEXT/NUMBER/BOOLEAN/SELECT/MULTI_SELECT) and uses product_units with an optional base unit + factor and a separate for_sale flag, nothing seeded (DEC-PSW-SPECS-MODULE, DEC-PSW-UNIT-CONVERSION; Product confirmed the deviation, Q9). A parent move is not blocked by attributes (DEC-PSW-CATEGORY-MOVE); import maps a merged attribute name to its target with a warning (DEC-PSW-IMPORT-MERGED); User App and campaign.public_product_json are out of this round (DEC-PSW-SCOPE). The 08/10 story 01-quan-ly-san-pham.md stays unchanged as history (hash-pinned by the U6/U12 rounds).
2026-10-22 — Superseded CI runs are cancelled before their point of no return (#384, owner request 22/10/2026: many PRs, shared Mac mini runners). code/scripts/ci/supersede-runs.mjs: in deploy-supabase.yml a newer push to the same branch cancels older runs still in resolve / verify, waiting, or in deploy before the Migrations (dry run, then apply) step; the deploy job re-checks right before that step and cancels itself when a newer push is queued, running or deployed. db push is the point of no return: a run past it always finishes. In quality-gate.yml the blind cancel-in-progress per PR is replaced by job supersede: an older run of the PR is cancelled while guards run or its step-estimated progress is below 80%, kept when nearly done or only the final gate is left; draft PRs run nothing; the gate job no longer runs in a cancelled run. Manual runs (rollback re-runs) never cancel and are never cancelled; an API error only warns. Trade-off: when the newest push fails verify, nothing deploys until a fix is pushed (latest wins). Docs: 18-ci-cd-supabase.md (Concurrency), docs/contracts/ci-quality-gate.md (Superseded runs).
2026-10-22 — DEC-377-DEPOSIT-RETRY-SAME-ORDER: a failed deposit attempt is retried on the same order (#377, owner decision 22/10/2026, D1(a)). Word 09-quan-ly-don-hang-v2.1.md:107,111,120: the order waits 24 h in Khởi tạo / Chưa thanh toán, and Đã hủy is a closed list without "payment failed". It supersedes "deposit failure = DEPOSIT_FAILED" (P3-02 / P3-04). payment.fail_deposit_order is a no-op: the order stays DEPOSIT_PENDING, the DEPOSIT obligation stays OPEN and no order.deposit_failed is written. deposit_checkouts keeps one live checkout per order with numbered attempts, and a new requestId retries the same order with the same points. The PI_POINT tender is REVERSED after compensation and settled again by the next REDEEM. The 24 h expiry (governing window) and the campaign close are the only cancellations; the expiry ignores reversed REDEEMs, and money in flight still blocks it. Legacy DEPOSIT_FAILED rows are not rewritten. Migration 20261224010000_deposit_retry_same_order.sql; details in 13.
2026-10-22 — DEC-377-PIPOINT-OPEN-PORTS: PiPoint is an open port while G-PP is open (#377, owner decision 22/10/2026). Dev and production have no provider, and no Mua chung step may throw because of that. Each touchpoint degrades to an explicit state that is replayed once a provider exists: the quote offers 0 points with pointsUnavailableReason; the checkout ends the attempt REDEEM_REJECTED PIPOINT_NOT_CONFIGURED; a reversal waits; reward and spin rows stay QUEUED; the refund point leg is parked. Behaviour with a provider (tests) is unchanged. Table in 13. Superseded for dev and staging 2026-11-03 (live PiPoint wallet there, row of that date); still in force wherever PiPoint is off (uat, production).
2026-10-22 — DEC-377-ORDER-DUE-CANCEL-REASON / DEC-377-CANCEL-REASON-OPTIONAL (#377, owner decisions D2 / D3, 22/10/2026). D2: the buyer Order gains depositDueAt, which is createdAt + the governing payment window (payment.deposit_due_at, the version the expiry applies), null once the order no longer waits. It also gains cancelReason, with the same values as AdminOrder.cancelReason (OrderAxisCancelReason, the Word closed list; an order unpaid at the close reads DEPOSIT_TIMEOUT). D3: RequestOrderCancellationInput.reason is optional (0..500, still sanitized). The required rule came only from the archived AI story UA-20. There is no password (DEC-U-CANCEL-PASSWORD), and only a deposited order may be cancelled before the close (Word l.107; this last part is superseded by DEC-388-CANCEL-UNPAID-REASON-CODE below).
2026-10-22 — DEC-388-CANCEL-UNPAID-REASON-CODE: an unpaid order is cancelled free; one cancel sheet with a reason code (#388, owner decisions O3 / O5, 22/10/2026; supersedes the "cancel only after the deposit" part of DEC-377 / #371 D3). O3: the buyer may cancel a Mua chung order that is still unpaid (Khởi tạo + Chưa thanh toán, state DEPOSIT_PENDING) before the cutoff, free of charge (ordering.cancel_order, migration 20261224020000): the order becomes Đã hủy with cause CUSTOMER_CANCEL, the payment stays Chưa thanh toán (no Chờ yêu cầu hoàn, no refund request: settlement NONE, handoff NOTHING_TO_REFUND), the open deposit obligation is cancelled, nothing counts toward community power and no Pi-Point moves (a REVERSED tender already gave the points back). While a deposit attempt is in flight (an intent CREATED/PENDING/UNKNOWN, a running checkout, captured cash or a REDEEM not yet rejected or reversed) the read answers PAYMENT_PENDING and the command conflict / payment_pending: an unknown outcome is never cancelled under the buyer. DEPOSIT_NOT_CONFIRMED is deprecated (never returned); a legacy DEPOSIT_FAILED order reads ALREADY_CANCELLED. Deposited orders keep the refund path. O5: one cancel sheet on the app with a required reason (chips + "Lý do khác" text), no password; the API takes an optional RequestOrderCancellationInput.reasonCode (CHANGED_MIND, WRONG_ORDER, CHANGE_SCHEDULE, OTHER; reason text stays optional, 0..500) so older app builds keep working. The code is stored in the order's change reason (buyer_pre_close_cancel [<CODE>]: <text>) and staff read it as OrderEvent.cancelReasonCode / OrderHistoryEntry.cancelReasonCode. payment.cancel_decide now also matches the bare and coded buyer reasons (a paid cancel without text was left CAUSE_UNRECORDED since #377 D3).
2026-10-22 — Recurring skip: a fixed lock at the buyer's window start, no per-environment cutoff; no skip past the package limit (#388, owner decisions 22/10/2026, round 2026-10-22-user-app-group2-integration). Skip and cancel-skip are allowed only before 00:00 Asia/Ho_Chi_Minh of the first day of the delivery window the buyer chose for that cycle (DEC-OWN22-SKIP-WINDOW-LOCK). The rule is the same in every environment: there is no cutoff configuration, no Operations seed (supabase/ops/seed-skip-cutoff.sql, 72 h, DEC-CP-SKIP-CUTOFF superseded) and no policy_undecided for a missing row. This replaces "skip cutoff per environment" in the 2026-10-16 row. A press past the package's "Được bỏ qua tối đa" is refused with conflict / limit_reached and no longer stops the order (DEC-OWN22-SKIP-LIMIT-REFUSED). Other owner decisions of 22/10 are rows DEC-OWN22-* in docs/decisions/decisions.csv and ADR 0003 "Update 2026-10-22".
2026-10-21 — DEC-U19-CRON-IN-DEPLOY: the pi-jobs-tick cron is registered by CI on every deploy (owner decision 21/10/2026, OWN-21-04, round 2026-10-19-word-v2-campaign-order-shipment, remediation R-38). Replaces the operator step of D-ARCH-01 ("the cron job is registered per environment by register-jobs-cron.ts"); the rest of D-ARCH-01 stands. deploy-supabase.yml runs apps/api/scripts/operator/register-jobs-cron.ts --env <env> --ensure --yes after the Edge Functions deploy and smoke tests, always, with no on/off switch. Before, the preflight requires JOBS_TRIGGER_SECRET and REFUND_PII_KEY (>= 32 chars) in the environment's FUNCTION_ENV. --ensure then: installs pg_cron / pg_net when missing (what CI can fix); fails when supabase_vault is missing; posts {"mode":"check"} to the deployed jobs function (same x-pi-job-secret; runs no job, takes no lease, touches no database, answers configured / unconfigured / unset key names, never a value) and fails on 401 (secret differs), no answer (boot failed: secret or PI_WORKER_DB_URL missing) or any unconfigured job other than those waiting for a provider (pipoint.reward.dispatch G-PP, payment.refund.execute G-FIN); upserts the Vault secret + cron.schedule (idempotent) and checks cron.job is active on * * * * * for that URL. Every failure stops the deploy and names what is missing. Env and secrets are set by the operator in FUNCTION_ENV (job limits: exact key or JOBS_DEFAULT_<GROUP>_*, OWN-21-03); CI never generates them. The manual modes (plan / --apply / --unschedule) stay for operators. Amended 2026-10-21 (OWN-21-06, R-40): the function env is set by the operator directly in the project's Supabase Edge Function secrets, not in FUNCTION_ENV (now optional again; it must not hold SUPABASE_* or JOBS_TRIGGER_SECRET). CI cannot read values: before db push it lists the secret names (supabase secrets list -o json) and fails when REFUND_PII_KEY or PI_WORKER_DB_URL is missing (no length check). JOBS_TRIGGER_SECRET is CI-managed: Vault pi_jobs_trigger_secret is its source of truth (generated, 32 random bytes hex, when absent); when the function lacks the name or jobs check answers 401, CI sets it with supabase secrets set --env-file (temp file, mode 600, removed; masked) and re-checks with backoff for about 2 minutes, then fails. The preflight FUNCTION_ENV requirement above is superseded.
2026-10-21 — A campaign product with MOQ below its Mốc 1 threshold is bad data, not a Product gap (#324, owner decision 21/10/2026). Word B006.R06 requires MOQ ≥ Mốc 1 and B006.R07 prices an order below Mốc 1 at Mốc 1 (already in orderTier / ordering.order_tier / tierAt), which supersedes GAP-CP-TIER-START. The API refused MOQ < Mốc 1 (moq_below_tier1); migration 20261223020000_campaign_ready_moq_tier1.sql adds the same rule to campaign.assert_ready when a campaign leaves DRAFT (both types). Rows from before are found with code/apps/api/scripts/operator/audit-moq-below-tier1.sql (read-only) and corrected per campaign; the close logic is not changed for them (a met MOQ below Mốc 1 still parks the close as NO_TIER).
2026-10-21 — DEC-U19-FUNCTION-STRIP-DEPLOY: Edge Functions are deployed from a stripped copy (owner decision 21/10/2026, OWN-21-05, round 2026-10-19-word-v2-campaign-order-shipment R-39). The dev deploy of 21/10 failed with 413 Function source code exceeds the maximum deployment size (5 MB) on graphql (4.39 MiB of local files; it had deployed at 4.07) after db push had run. deploy-supabase.yml now builds a copy of supabase/functions where each .ts file is stripped on its own by a pinned esbuild (types, comments, whitespace; no renaming, no bundling, same files and imports; graphql 2.39 MiB) and deploys it with --workdir; the repo is unchanged. Required with it: the unit tests run on the stripped copy in verify; a 4 MiB per-function size gate (what the CLI uploads) and a load check run before link and db push; external source maps are a 30-day CI artifact. Not chosen: Docker/eszip, splitting graphql, deno bundle. Trade-offs and responses: 23.
2026-10-21 — MoMo MOCK simulator: local, dev and staging only; optional auto-settle (#323, owner decision 21/10/2026). PAYMENT_TEST_MODE=simulator is honoured only with PI_ENVIRONMENT local, dev or staging (SIMULATOR_ENVIRONMENTS); uat now behaves like production for payments (introspection keeps its own list). With PAYMENT_SIMULATOR_AUTO_SETTLE_MS set (below the session TTL) the simulated payer pays every unscripted deposit/remaining session that long after it opened; PIDEAL applies it through the normal status lookup (the buyer's re-check with the same requestId) - no new GraphQL operation, no QA role, no manual step (UW-PAY-06 EC01 unchanged). In test mode only, PAYMENT_INTENT_RECOVER_EVERY_MINUTES turns payment.intent_recover into a timed sweep so a payment also lands when the buyer has left the app; production keeps it ON_DEMAND (cadence GAP-1561). Unset = the previous harness-only behaviour.
2026-10-20 — DEC-U19-MIGRATION-CONSOLIDATION: the U19 migrations are squashed before release (owner decision 20/10/2026, round 2026-10-19-word-v2-campaign-order-shipment). After every U19 task is merged and before the P5-04 full regression, the 124 U19 migration files (everything after base 47921edd, never applied to any environment — owner confirmed) are concatenated, in their original order and with their bodies unchanged, into 8 contiguous files with new valid UTC stamps 20261223…; the 545 files already on dev/staging/master are never touched. Equivalence is proven on scratch PG17 only (pg_dump --schema-only + reference rows diff = empty, fresh-db smoke, registry); no copy of real data is used. P5-04 then runs on the squashed chain. This is a one-time exception to "forward-only, one migration per change" for unreleased files only; once a file reaches an environment branch the forward-only rule applies again. Plan: docs/implementation-plans/2026-10-19-word-v2-campaign-order-shipment/execution/migration-consolidation.md. Thực hiện ở U19-P5-05, 317fb3c02d176895e57244ae55ce47eeaa604df0: 136 file (20261220010000 … 20261222160000) → 20261223000000 … 20261223000700; map stamp cũ → file § section ở execution/migration-consolidation-map.json; migration mới dùng stamp > 20261223000700.
2026-10-19 — D-ARCH-01: periodic jobs run in the jobs Edge Function, called every minute by Supabase Cron (owner decision 19/10/2026, round 2026-10-19-word-v2-campaign-order-shipment, task U19-P0-03). pg_cron + pg_net post {"mode":"tick"} to POST /functions/v1/jobs (verify_jwt = false; header x-pi-job-secret = JOBS_TRIGGER_SECRET, compared in constant time, else 401). Each tick runs the P1-16 scheduler (enqueueDue + runDue) over the pi_worker login (PI_WORKER_DB_URL) for the jobs in functions/jobs/job-registry.ts; a job whose limits are not configured is left out and named in the tick log. New schedule kind EVERY_N_MINUTES (N 1..60, UTC buckets, no catch-up); the DH timed jobs use N = [X] - 1 = 4 so a due task waits at most [X] = 5 minutes (ASSUME-07, GAP-W-DH-12, provisional). The cron job is registered per environment by apps/api/scripts/operator/register-jobs-cron.ts (secret in Supabase Vault), not by a migration: native PG17 has no pg_cron and the secret stays out of Git. No local runner: locally a job runs only when a test calls the handler / tick() on a scratch DB (owner: decided later). The outbox relay pass is off unless JOBS_RELAY_ENABLED=true, because a relayed event is DISPATCHED for every consumer, registered or not. Supersedes the "no host process" gap of P1-16 / FU-DEF149 (GAP-1624 daily expiry cadence).
2026-10-16 — Recurring is open; gate G-CP and its go-live switch are retired (#286, team decision). The FU-FORFEIT maker/checker go-live flow (proposeRecurringGoLive / decideRecurringGoLive, GLV-01..03, ops/recurring-go-live.sql) was an interim invention: migration 20261215040000 drops it and campaign.recurring_gate_open() is always true. Recurring baskets are published from the Admin web (activateCampaign) and read by the User App (publicRecurringCampaigns). Flows beyond create-and-read stay gaps until decided (save basket/deposit GAP-373, period selection, skip cutoff per environment (superseded 2026-10-22: fixed lock, see that row), partial close, refund text, Sale App): decisions.csv DEC-CP-GATE-RETIRED.
2026-10-16 — Every order has an order code; its format is TEMPORARY (issue #298, user decision). public.orders.code (migration 20261216010000_order_code.sql) is PO + 8 random characters of A-Z0-9, unique (case-insensitive) and immutable, generated by the database (ordering.new_order_code() as column default + an insert trigger that redraws a code already in use; existing orders were filled by the migration). The Product format is still open (NEW-SL-12, docs/implementation-plans/2026-10-09-update-6-prd/owner-questions.md) and will replace this one soon, so the format lives in that one function and the web search shape in one constant (ORDER_CODE_SHAPE, web-admin order-shared/values.ts), and there is NO format CHECK in the database: only uniqueness is enforced. Shown instead of the short order id in the Admin order list/detail, cancel dialog, Group Buy participants/close-out, Recurring registrations and the customer purchase history; adminOrders searches it with searchBy: ORDER_CODE (exact, any letter case), and the Sale "Danh sách liên kết" tab returns it as orderCode (the 8-character orderRef stays as a fallback). API: code: String! on Order, AdminOrder, CustomerOrder.
2026-10-15 — The release branch is master, not main (issue #280). Doc 11, doc 18 and CLAUDE.md said main, which never existed on GitHub; they now say master, and deploy-supabase.yml maps only master to uat (the main alias is gone). The remote develop branch was deleted (its last commit, 5058101, is contained in master and dev). Supersedes the master/main alternatives of the 2026-10-05 row.
2026-10-15 — Quality gate made runnable and cheaper (issue #280). It had never run on dev (it watched develop) and was red since round U6. A full run costs 2.5+ runner hours and the first one exhausted the Actions quota, so the gate is now automatic only for PRs into master (the release gate: guards + the jobs of the changed areas); a manual run checks the areas ticked in the run form (macOS goldens opt-in); PRs into dev and pushes run nothing here. Checks owned by a closed plan round run on that round's own range (auth-flow 11e10efa..f181ca32, U6 up to ff51ddf49, U12 sources at its baseline commit) instead of the tip, so later rounds no longer read as violations. The 75 GoTrue references left by the U6 Admin-created Sale (sale-admin/provision-port.ts calls /auth/v1/admin/users at runtime) are listed in no-gotrue-pending.json as FU-280-SALE-GOTRUE and still need a fix. Contract: docs/contracts/ci-quality-gate.md.
2026-10-15 — Scratch DBs are copies of one migrated template DB (issue #293, round #300, GAP-QG-02; AC 4 of #293 rewritten with owner approval). Node DB suites no longer re-apply 538 migrations each (~29 s, one psql per file): the first suite builds pi_p003_tpl_<hash of stubs + migrations> with one psql call under pg_advisory_lock, publishes it read-only (IS_TEMPLATE, ALLOW_CONNECTIONS false), and every other scratch DB is CREATE DATABASE … TEMPLATE it. Scratch DBs are still created and dropped by their own process; the template is a shared cache dropped when the migration set changes or on demand (db-reset.sh, scripts/schema/drop-scratch-templates.mjs); never pideal_dev, never Docker. Suites that test migration application keep the full apply. Deno DB tests are spawned with --no-check; db-integration keeps DENO_DIR outside the workspace (tool cache; actions/cache only on GitHub-hosted), runs both db steps with --test-concurrency=2 on the self-hosted cluster runner (default on GitHub-hosted) and sets PI_PGCONNECT_TIMEOUT=30 for every harness connect (#305 load). Contract: docs/contracts/ci-quality-gate.md → "db-integration: template DB and runners".
2026-10-15 — A customer is labelled "Sale" only when their Sale account is ACTIVE or LOCKED (issue #299, user decision; supersedes K-14 / DEV-SL-01 of round 2026-10-09-update-6-prd for the customer label, which counted a sale_codes row in any Sale status, so a customer with a pending Sale application showed as "Sale" in the Admin customer list, detail and export). customer.directory() (migration 20261215020000_customer_directory_sale_status.sql) now sets is_sale / sale_id / sale_code only for an APP_SALE account status ACTIVE ("Đang hoạt động") or LOCKED ("Khóa"), i.e. sale_admin.derive_account_status(membership); INITIATED ("Khởi tạo": PENDING or REJECTED application) and INACTIVE ("Dừng hoạt động", SUSPENDED) give no label, code or link. The Product story 05-quan-ly-khach-hang.md does not define these statuses. Unchanged: Sale codes are still issued at application time, and the Sale-admin "already a Sale" check of an existing account still counts any Sale status.
2026-10-15 — app-sale paused in the quality gate (#294). Development of app-sale is paused, so the gate no longer analyzes or tests it (job mobile: --exclude app-sale), leaves out the sale-tagged widgetbook suites (app-widgetbook:test:ci) and the Sale goldens (job mobile-goldens), and a PR touching only code/apps/app-sale/ no longer starts the mobile job (scripts/ci/changed-areas.mjs). The P0-12 Sale DS gate keeps running in guards. Every exclusion in code/ and .github/ carries the app-sale PAUSED marker; nothing is deleted. Re-enable checklist: docs/contracts/ci-quality-gate.md → Paused scopes; when the pause ends, add a row here.
2026-10-15 — API unit tests in CI: one shared runner, coverage only on manual runs (issue #295, round 2026-10-15-improve-quality-gate-speed). quality-gate.yml (api-unit) and deploy-supabase.yml (verify) both run code/apps/api/scripts/ci/unit-tests.ts: one type-check of every source, deno test --parallel --no-check except SERIAL_TESTS, then the env-changing files serially; the list and its "no unlisted env-changing test" check exist only there (deploy's argv and file lists unchanged). The P1-18 / P2-23 re-run steps are removed; their cases are asserted on the main step's TAP output. Coverage is no longer collected on PRs into master: it is report-only (no threshold), so it runs only on a manual workflow_dispatch run, which is the NFR-MNT-006 "CI evidence" path (summary + api-unit-coverage lcov artifact). Contract: docs/contracts/ci-quality-gate.md → "api-unit"; doc 18 §2.
2026-10-15 — Mobile tests in the quality gate: one compile per package, coverage only on manual runs (#297). Job mobile runs each package's test target with -c ci: scripts/ci/one-compile-tests.mjs generates one entry importing every test file and runs it in one flutter test call, with the files that need their own isolate (isolation list, each with a reason) as separate suites in the same call; nothing is skipped (GAP-QG-05) and check-one-compile.mjs fails when a test file is in neither. --coverage only on workflow_dispatch (the NFR-MNT-006 coverage evidence path); PRs into master run without it. run-many --parallel=2 for the 2-vCPU runner. Local nx test is unchanged. Contract: docs/contracts/ci-quality-gate.md → Mobile tests.
2026-10-15 — User App sign-up grants the role user again (#285). The 2026-08-26 rule "app-user → ACTIVE + user" was lost when sign-up moved to identity_flow.sign_up_link (2026-10-10): the account got an ACTIVE APP_USER membership but no role, so every User App command answered forbidden. sign_up_link now writes the user assignment in the same transaction, only for a membership it creates. It is a system grant, not a maker/checker role change: granted_by = the account itself, grant_reason = 'auth.sign_up', no checker. role_assignments_no_self_grant and its insert guard allow that one self grant (APP_USER role user) and still refuse every other. Accounts registered before the fix are not backfilled by migration (owner). Sale and Admin sign-up are unchanged (PENDING, no role).
2026-10-15 — Quality gate runs only affected Nx projects and caches results (issue #296). The web job runs Nx typecheck/test targets instead of pnpm -r --if-present (which typechecked only 3 of the 7 web projects; all 7 now do): on a PR into master only the projects nx affected reports from the merge base with origin/master (dependents included); on a manual run, a change to the workflow, or a PR that changes a doc outside code/ that the tests read (scripts/ci/nx-external-inputs.mjs), every web project. Results are cached by content (code/nx.json inputs, including those external docs and the API files web-admin tests read) and kept between runs through a loopback Nx self-hosted cache server (scripts/ci/nx-cache-server.mjs; Nx 21's own .nx/cache is keyed by machine ID and is never hit on a new runner) whose directory actions/cache keeps per branch, restoring from master. The mobile job uses the same affected/run-many switch without a persistent cache yet. The guards areas filter starts web for those externally read files too (changed-areas.mjs), and after every release merge the release owner runs the gate once on master (web + mobile) to save the master cache entry PRs restore. nx.json defaultBase is master. Contract: docs/contracts/ci-quality-gate.md → "Affected and cache".
2026-10-10 — PIDEAL identity replaces Supabase Auth (GoTrue) — round docs/implementation-plans/2026-10-09-update-auth-flow (user decisions U-01..U-19 in its requirements-record.md, approved 10/10/2026). Credentials (PBKDF2, public.password_credentials), sessions (public.account_sessions) and tokens are ours: the auth function issues ES256 access tokens (15 min, kid, iss, aud = pideal-api, sub = account_id, sid, app) and opaque rotating refresh tokens; graphql verifies the signature with the public keys of AUTH_TRUSTED_ISSUERS and checks the session in the same statement that loads the actor — no HTTP call per request. Supersedes 2026-08-26 "Edge Functions verify the caller by calling Supabase Auth /auth/v1/user" and the "Auth stays in the cloud" / "Data local, auth cloud" notes of §6: local now runs the whole flow on native PG. Old entries stay as history. Details: 03-authentication §9, keys and rotation: 18-ci-cd-supabase §6. Supabase secrets are project-wide, so the private key is kept to the auth function by code + the signing-key-scope gate, not by the platform. Passwords are not migrated: accounts from before sign in again after "Quên mật khẩu" (R-10).
2026-10-09 — develop is retired; dev is the integration branch (U-12 of round 2026-10-09-update-auth-flow). Feature branches are cut from master and merged --no-ff into dev (→ pideal-dev), staging (→ pideal-staging) and master (→ pideal-uat); quality-gate.yml runs on PRs (guards only into dev, the full gate into master, since 2026-10-15), and deploy-supabase.yml deploys dev only from dev. Supersedes the develop mentions in the 2026-09-07, 2026-10-05 and 2026-10-06 rows: the pi-deal-demo GitHub integration was bound to develop, so nothing merged now reaches it.
2026-10-07 — iOS team is PITEK M6LM7NN35F, the team holding the PiDeal App Store Connect records and App IDs. The scaffold had inherited picity-apps' team 75DY258D9S in every Xcode project (app-user, app-sale, app-widgetbook) and as the CI export default; both now use M6LM7NN35F. pi-deal signs with its own Apple Distribution certificate in that team. Doc 19 §3.3.
2026-10-06 — Current deploy setup: pushes to dev or develop with API/workflow changes target pideal-dev; merges trigger via the resulting push. Backend deploy credentials use dedicated GitHub Environments supabase-local, supabase-dev, supabase-staging, supabase-uat, separate from the mobile build Environments. FUNCTION_ENV is optional; Supabase injects the SUPABASE_* values. See doc 18 for the checks that run before a deploy.
2026-10-06 — Android builds go to Google Play internal testing, not Firebase App Distribution. CI also builds a release-signed AAB and uploads it with the Play Developer API (PLAY_SERVICE_ACCOUNT_JSON, track: internal); the APK stays a run artifact for sideloading. One store path per platform (Play / TestFlight), no Firebase project needed for distribution. Each app needs its Play Console record and a first AAB uploaded by hand. Supersedes the "Firebase" part of the 2026-10-05 entry. Doc 19 §2–§3.
2026-10-05 — Supabase auto-deploy via GitHub Actions (deploy-supabase.yml, design in 18-ci-cd-supabase.md): develop → dev, staging → staging, master/main → uat (reviewers), manual → local; migrations before functions, all function directories under supabase/functions/ unless enabled = false in config.toml, secrets from the GitHub Environment (FUNCTION_ENV). quality-gate.yml stays verification-only. pi-deal-demo keeps the GitHub-integration exception — the workflow refuses its ref.
2026-10-05 — Mobile native flavors dev / staging per app, ids from the existing store records — Android com.pideal_<env>.<app>, iOS com.pideal-<env>.<app> (- is not allowed in an Android id); local/mock run on dev; no uat/prod flavor. Builds run on demand from GitHub Actions (mobile-build.yml: branch · env · app · platform · runner), self-contained rather than the shared pigroupdev/devops pipeline, whose assumptions (app names, <package>.<env> ids, root .fvmrc, no env-file hook) this repo does not meet. Signing and Firebase / TestFlight upload switch on as secrets are added. Supersedes doc 12's "no native flavors for now". Doc 19.
2026-09 (21)
2026-09-30 — AUTH-01 supersedes historical authentication decisions. All three apps register with phone + password/confirmation then purpose-bound SIGN_UP OTP; they sign in only with phone + password; password reset is phone + PASSWORD_RESET OTP + new password, then a separate sign-in. Disable/migrate OTP sign-in, email/social/username sign-in and automatic unknown-phone account creation. Admin self-registration is allowed but creates only WEB_ADMIN/PENDING/no-role; privileged MFA remains post-credential. Existing verified-phone passwordless identities establish a password through reset; identities without verified phone use an approved support recovery path. Replace email-based bootstrap provisioning with a phone-aware operator/provisioning process before release. See 03-authentication.md and SOW AUTH-01.
2026-09-29 — Audit log of web-admin mutations. withAudit() wraps every Mutation resolver when the schema is composed; a call from WEB_ADMIN leaves one append-only row in public.audit_logs (trigger rejects UPDATE/DELETE) with actor snapshot, action, masked input, result SUCCESS · FAILED · DENIED, IP. Services add entity + before/after for sensitive actions through auditNote() (AsyncLocalStorage, no signature change). Written after the resolver settles, outside the business transaction, and a failed write never fails the mutation. PII (phone, email, DOB, referral code, ID-document paths, phone/email in free text) is masked before insert. Every mutation must have an entry in domains/audit/registry.ts (test fails otherwise). Queries, APP_USER/APP_SALE and sign-in are not logged; no retention limit yet. Read with audit.read (super_admin only). Plan (current): docs/implementation-plans/2026-10-01-all-flows/detailed/01-platform.md P1-08, owner section docs/contracts/schema-ownership.md §5q (table is now audit_events).
2026-09-28 — CMS articles get their own tables (article_categories tree via parent_id, articles, keywords, article_keywords) instead of the ERD's generic cms_contents; banner/page will be separate tables later. Permissions are three-segment under one resource: cms.article.*, cms.category.*, cms.keyword.* (roles admin and marketing hold all, bi_viewer reads). Plan (current): docs/implementation-plans/2026-10-01-all-flows/detailed/04-engagement.md P4-17, owner section docs/contracts/schema-ownership.md §5ab.
2026-09-28 — Article body is stored twice: body_json (Tiptap document the client sends, validated by the API against an allow-list of nodes/marks/attrs) and body_html (rendered server-side with @tiptap/html, the same extension set as the web editor). Clients never send HTML — that is the XSS baseline for #188. @tiptap/html runs under Deno via npm: (spike 2026-09-28).
2026-09-28 — Scheduled publishing without cron: an article is live when status = 'PUBLISHED' and (publish_at is null or publish_at <= now()); readers apply the condition, the admin shows a derived SCHEDULED state. Editing a live article edits it in place (no parallel draft yet).
2026-09-28 — CMS media uploads go straight to Storage: the API signs a one-shot upload URL (createMediaUploadUrl, needs SUPABASE_SERVICE_ROLE_KEY in the Edge Function) for a random key in the public bucket public-media; the browser PUTs the file itself. The bucket is created per project by hand (Dashboard), not by migration — local PG has no Storage, so uploads are only testable against a cloud project. Superseded 2026-09-28: buckets by migration.
2026-09-28 — Web kit gains the data-management set — Table, Pagination, DataTable, Command, Combobox, TagInput, ConfirmDialog, DateTimePicker, ImageUpload, RichTextEditor (Tiptap) — plus @tailwindcss/typography (prose) in the shared preset. git conventions of doc 11 are waived for branch feature/t9-content-management by the product owner.
2026-09-28 — Media: media table (bigint id → 000/000/001/<slug>.<ext> object path), buckets public-media / private-files created by migration, uploads via signed upload URL minted by the graphql function with SUPABASE_SERVICE_ROLE_KEY (a function secret, per project). Design (current): docs/contracts/schema-ownership.md §5d (P1-11).
2026-09-28 — Phone OTP is backend-owned. The OTP is generated, delivered and verified by the phone-otp Edge Function (public.phone_otps, OtpProvider adapter for a Vietnamese SMS/OTP provider; OTP_PROVIDER=mock accepts 123456 for every number, never on production); Supabase Auth only issues the session: admin/generate_link type=magiclink → client verifyOtp({ token_hash, type: 'magiclink' }). Phone-only accounts get a placeholder email <digits>@phone.pideal.space (GoTrue cannot mint a session for a user without an email); the API strips it, and Secure email change is OFF per project. web-admin gets an OTP sign-in mode (shouldCreateUser: false, unknown number → userNotFound) — extends the 2026-09-08 "password only" note for T9. Follow-ups: phone forgot-password (still Supabase SMS), the real provider adapter. The phone-otp function and OTP sign-in were removed by the 2026-10-01 reset (AUTH-01, docs/sow/12-baseline-reconciliation.md); the plan document of this entry no longer exists.
2026-09-28 — Sale management (AP-16..19) keeps two states apart. Trạng thái tài khoản lives on sale_profiles.status (INITIATED · ACTIVE · INACTIVE · LOCKED); trạng thái phiếu is the status of the latest sale_applications row (ONBOARDING on sign-up / admin create, PROFILE_CHANGE for a later edit that needs review). user_app_memberships(APP_SALE) stays the gate effective_permissions() reads and the API mirrors the account status into it. ensure_app_membership(APP_SALE) now also creates the sale profile + onboarding application, so app-sale sign-ups and admin-created sales share one path. Approval is only approveSaleApplication / rejectSaleApplication; approveMembership(APP_SALE) is refused. New WEB_ADMIN role sale_admin ("Quản lý Sale") holds sale.* (the APP_SALE role sale_manager cannot open the portal). Plan (current): docs/implementation-plans/2026-10-01-all-flows/detailed/01-platform.md P1-12/P1-13, owner sections docs/contracts/schema-ownership.md §5g/§5r.
2026-09-28 — Private bucket sale-documents (10 MiB, PDF/DOC/DOCX/JPG/PNG) for hồ sơ / hợp đồng of sales; writes through createSaleUploadUrl(DOCUMENT), reads through 60-second signed URLs (saleDocumentDownloadUrl). Sale avatars reuse public-media under sales/avatars/. MediaUploadTicket gained bucket so one uploadToSignedUrl helper serves both. Created per cloud project by hand / SQL like public-media.
2026-09-11 — pi_services client folders are named for the call shape, not the destination. functions/ → rpc/, PiFunctions → PiRpc (+ PiRpcTransport, FixtureRpcTransport, defaultRpcFixtures()). Both folders are Edge Function clients, so "functions" named what they share; graphql/ names a protocol and rpc/ names the other shape — a function called by name with a JSON body. FUNCTIONS_URL keeps its name: it is Supabase's /functions/v1 base, not ours.
2026-09-10 — Mobile packages have no lib/src/ — lib/ is the root (packages/app-core/lib/failure.dart, packages/app-features/lib/auth/…). The barrel (lib/pi_core.dart, lib/<feature>.dart) is still the public surface and the only thing other packages import; the extra folder bought nothing but longer paths.
2026-09-10 — PiRpc (pi_services) is the client for non-GraphQL Edge Functions — the escape hatch for what a graph field cannot do (upload signing, a webhook's client leg, health), not a second API style; GraphQL (2026-08-26) stays the default. Same shape as PiApi: one run(), Result<T>, x-pi-app + bearer from PiSession.accessToken(), a fixture transport for mock; the one difference is that it also sends apikey (what the web client and Supabase's own SDKs send), harmless with verify_jwt = false and required if a function is left at the gateway default. Error contract for such a function: { error: { code, message, details } } with the graph's codes (errorResponse() in _shared/errors.ts). Base URL FUNCTIONS_URL, defaulting to <SUPABASE_URL>/functions/v1. Plain http, not the SDK's FunctionsClient, so the token is refreshed on demand exactly as for the graph.
2026-09-10 — Mobile: Edge Functions only, schemas mirrored. Reaffirmed by the team lead: every mobile data call goes through our Edge Functions (PiApi / PiRpc), never a table, PostgREST or Storage; supabase_flutter stays auth-only. The GraphQL schema and every generated Dart file in pi_services are produced from the backend SDL by deno task schema:export + nx gen app-services and are never hand-written — a type the app needs is a backend change first. Doc 12 §5 "API" carries the rule.
2026-09-10 — Bootstrap admins are explicit. bootstrap_admins(email) (its migration was removed by the 2026-10-01 reset; the operator-run rbac.bootstrap_first_admins of 20261002050600_rbac_operator_bootstrap.sql now covers this) replaces "first account ever becomes super_admin": with app-user and app-sale signing up against the same project, the first auth.users row could be a shopper, and a trigger cannot see x-pi-app. An operator inserts the admin's email before that person signs in (SQL editor on cloud, seed.sql locally). Supersedes the 2026-08-26 rule; existing environments keep their current super admin.
2026-09-08 — Mobile sign-up is phone + OTP only, no password (product decision, reverses 2026-09-07): signInWithOtp({phone, shouldCreateUser: true}) → verifyOtp — the same call serves "Log in with phone number", so an unknown number is created silently. The SMS per sign-in is accepted (the number is needed at checkout anyway); email, username and a password are set later in the profile. Sign-in offers two modes with a switch link: OTP (default) and password. Google stays on both screens. Open question: username as a sign-in identity (needs a backend resolver). Doc 03 §2.2/§2.3 updated.
2026-09-08 — SSO dropped for web-admin — admin signs in with password only; web-admin is frozen for now, so the Google button/callback are removed when it is next touched. The Supabase Google provider stays (mobile uses it). Note: the only current admin account is Google-only and needs a password (forgot-password) before that cut.
2026-09-07 — Shared mobile features are one package, pi_features at packages/app-features/ (Nx app-features), with one library per feature (package:pi_features/auth.dart, /profile.dart → lib/src/<feature>/). Supersedes the pi_feature_<name> package-per-feature layout: one pubspec.yaml carries every feature's dependencies, so pub resolves them once and adding a feature needs no new pubspec, project.json, or workspace entry.
2026-09-07 — Interim dev project pi-deal-demo (gapvzwcricxdbqwtptgp, ap-southeast-1, personal free org) while the company Supabase account is pending. It plays the dev role for the mobile auth/profile work and is the auth project for Phi's local runs. Deploys go through the Supabase GitHub integration, not a GitHub Actions job: repo pigroupdev/pi-deal, working directory code/apps/api, production branch develop → every merge to develop applies new migrations and deploys the functions declared in config.toml ([functions.graphql]). Auth/API settings and seed are not synced by the integration, so dashboard auth config is set by hand per §5. Workflow: develop locally (deno task dev + cloud auth) → PR into develop → integration deploys → test on pi-deal-demo. No CI job may also deploy to this project. The project is transferred/re-pointed to the company org later; only the ref changes.
2026-09-07 — Mobile sign-up is three steps on one screen: identity → create password → 6-digit OTP. Password stays required (a passwordless variant was tried the same day and dropped: accounts without a password need an OTP on every sign-in, one SMS each for phone users). The password step comes before the code because Supabase sends the code from signUp({identity, password}) and verifying it signs the user in. Doc 03 §2.2/§2.3 updated.
2026-08 (38)
2026-08-28 — Mobile architecture settled in 12-mobile-architecture.md: pub workspace (no melos), packages pi_core · pi_services · pi_localization · pi_ui · pi_feature_* under packages/app-* / packages/app-features/*, feature-first with data/domain/presentation inside each feature, Bloc + get_it, go_router with a per-app AuthPolicy (app-sale required, app-user optional — public browsing, sign-in at checkout), graphql + graphql_codegen from the same SDL as the web, slang (vi base + en), --dart-define-from-file env files, unit tests only.
2026-08-28 — Errors travel as values: Result<T> / sealed PiFailure from pi_core; the only catch sites are PiApi.run() and PiSession; blocs store the PiFailure, screens map it through failureText().
2026-08-28 — Mock data source at the service boundary: DATA_SOURCE=mock swaps HttpLink → FixtureLink and supabase_flutter → FakePiSession; features, repositories and generated parsing run unchanged. No per-feature mock repositories.
2026-08-28 — Kebab-case file names repo-wide (TS and Dart). Exceptions are tooling-imposed only: *_test.dart, generated *.g.dart / *.graphql.dart, slang <namespace>.i18n.json, and the package entry file lib/<package_name>.dart. pi_ui renamed to comply.
2026-08-26 — Local dev gets its own Supabase project pideal-local (ovwlkhenmlqbuycpiyge) instead of sharing pideal-dev for Auth — one Site URL per project, and pideal-dev must keep pointing at the deployed dev site (https://dev.web.pideal.space) while local needs http://localhost:8080. Supersedes the 2026-08-25 note "local auth delegates to pideal-dev".
2026-08-26 — First working auth method: Google sign-in on pideal-local for web-admin (Google Cloud OAuth client shared across environments, one redirect URI per project ref).
2026-08-26 — web-admin master layout: AdminShell in @pi/ui (src/components/pi/) — Animate UI Radix sidebar collapsible to icons + sticky top bar. Data-driven and routing-free (render wraps the kit's icon+label in the app's <Link>); the app keeps only app/admin-layout.tsx and app/admin-nav.ts.
2026-08-26 — The Animate UI registry ships Tailwind v4 syntax (w-(--sidebar-width), --spacing(4)) but this workspace is on v3, where those utilities silently generate nothing. radix/sidebar.tsx was converted to v3 (w-[var(--sidebar-width)], theme(spacing.4)) and added to SKIP_TARGETS in sync-animate-ui-registry.mjs so a sync cannot reintroduce them. Check any newly synced component for the same.
2026-08-26 — Admin chrome: dark masthead (#181818, 56px) above the shell — logo · search · account menu (profile · vi/en · sign out). The search is per page: pages register their own via useAdminSearch, so one field serves products / orders / … Route /profile added.
2026-08-26 — Backend bootstrapped in code/apps/api/supabase: CLI project, first migrations (E01 Identity & RBAC — profiles, roles, permissions, role_permissions, user_roles), plain-PG stubs and scripts/db-reset.sh (native PG17 @5433, no Docker).
2026-08-26 — Permission codes use dots, resource.action with up to three segments (user.read, user.role.assign, payment.refund.approve) — following the conceptual ERD. Doc 01 §12 shows product:view with a colon; the dot form wins because codes live in the database and three-segment codes read better. permissions.resource is a generated column.
2026-08-26 — Permission scope is OWN / TEAM / ALL (conceptual ERD §1), not the five-level own/branch/region/company/global sketched in doc 01 §12. Revisit when a real multi-branch requirement appears.
2026-08-26 — First account in the system becomes super_admin with an ACTIVE web-admin membership (trigger on auth.users, serialized by an advisory lock). Guard rails: the last usable super admin can be neither suspended (account- or app-level) nor stripped of the role.
2026-08-26 — Edge Functions verify the caller by calling Supabase Auth /auth/v1/user rather than checking an HS256 signature locally — projects now issue asymmetric keys, so there is no shared secret to pin, and revoked tokens are caught. Supersedes the "JWT secret of the cloud project" note in §6. Cost: one request per call; revisit with a cache if latency shows.
2026-08-26 — API style: GraphQL served from our own Edge Function (graphql, GraphQL Yoga), not REST routes. This replaces doc 01 §6's REST examples but keeps §4 intact — Supabase's autogenerated /graphql/v1 and /rest/v1 stay disabled, clients never touch tables, every field goes resolver → permission check → service → repository. Also settles the open item on the Flutter API contract: both clients codegen from one schema. Doc 01 §6/§9 examples still show Hono routes and need rewriting.
2026-08-26 — One account, three apps, independent per app. A person signs in to app-user / app-sale / web-admin with a single auth account; per-app state lives in user_app_memberships (own status) and roles.app (roles belong to one app). Effective permissions = effective_permissions(user, app), requiring both the account and that membership to be ACTIVE. First open of an app creates the membership: app-user → ACTIVE + user; app-sale → PENDING + sale; web-admin → PENDING + no role (waiting screen only).
2026-08-26 — Clients must send x-pi-app: APP_USER \| APP_SALE \| WEB_ADMIN on every API call — permissions are resolved per app and an OAuth callback carries no app metadata, so the header is the only reliable signal.
2026-08-26 — Web GraphQL client: graphql-request + graphql-codegen in @pi/web-services (createApiClient(app) → typed SDK). Not urql/Apollo — the apps already run TanStack Query and a second normalized cache would duplicate it. Codegen reads an SDL file exported from the backend (deno task schema:export), so it works offline; generated.ts is committed.
2026-08-26 — RequireAuth in web-admin now gates on access, not just session: it reads me.nextStep and routes anything but READY to /pending. Closes the TODO that let any Google account into the portal.
2026-08-25 — Region: ap-southeast-1 (Singapore) for all projects — lowest latency for users in Vietnam. The initial Sydney project was deleted and recreated. Region cannot be changed after project creation.
2026-08-25 — Hosting: 3 free-tier Supabase projects spread across multiple Supabase accounts (a free organization allows max 2 active projects). No Pro plan for now.
2026-08-25 — Production: deferred — will be created when go-live approaches (est. several months). Revisit plan/org structure at that point.
2026-08-25 — Local Edge Functions: run directly with Deno (deno serve), not supabase functions serve (which requires Docker). Local auth delegates to the cloud pideal-dev project.
2026-08-25 — Edge Function stack: Hono (router) + Zod (validation) + postgres.js (npm:postgres, prepare: false).
2026-08-25 — Clients: customer + sale mobile apps = Flutter; admin web = React + Vite SPA (deployed to AWS Amplify per SOW). Consequence: Zod schemas/TS types are shared only between admin-web and Edge Functions; the Flutter apps need their own API contract (e.g. OpenAPI → Dart codegen — TBD).
2026-08-25 — Repo layout: all source code moves under a code/ folder (monorepo for backend + admin web + mobile). Restructuring done by hand by the user; scripts/docs to be updated afterwards.
2026-08-25 — First feature slice: sign-up / login — clients call Supabase Auth directly (/auth/v1/*); backend side starts with a profiles migration + user-api (GET /me) verifying JWT.
2026-08-25 — Web UI kit: WES @wes/shadcn cloned into code/packages/web-ui as @pi/ui — apps import from the single barrel only (import { Button } from '@pi/ui'). Primary source = Animate UI, Radix family; shadcn/ui classic fills gaps. base/headless/community/demo families pruned; the registry sync script skips them. Rules in code/packages/web-ui/CLAUDE.md.
2026-08-25 — Flutter UI kit: WES flutter_ui (GlowFox) cloned into code/packages/app-ui as Dart package pi_ui — prefix GF* → Pi*, brand refs rebranded. Flutter apps import UI only from package:pi_ui/pi_ui.dart. Rules in code/packages/app-ui/CLAUDE.md.
2026-08-25 — Old root supabase/, scripts/ and .erd/ deleted — the backend (Supabase CLI project, config, migrations, stubs, local tooling) will be rebuilt from scratch inside code/apps/api/.
2026-08-25 — admin-portal renamed to web-admin. Stack: React 19 + Vite 6 SPA, React Router v7 (all routes guarded), TanStack Query v5, react-hook-form + Zod, @supabase/supabase-js (PKCE).
2026-08-25 — Technical docs split per package (05–10) with an index at docs/technical/README.md; package working rules stay in each package's CLAUDE.md/README.md.
2026-08-25 — Auth moved out of web-admin into @pi/web-services/auth (session provider AuthProvider/useAuth, identity validation, Supabase error → AuthErrorCode); the package stays copy-free, apps bridge codes to their dictionary (app/auth-i18n.ts).
2026-08-25 — Localization: all web copy moved to @pi/web-localization (i18next + react-i18next) — Vietnamese default + English, one independent folder/instance per app (web-admin, web-redirect-deep-link); vi.ts is the typed source of truth, @pi/ui holds no strings.
2026-08-25 — Front-end conventions consolidated in 04-front-end.md: flat pages/ with folder-per-page (prefix naming auth-sign-in…, entry index.tsx, separated view/hook/schema), styles live in @pi/ui (new kit components AuthShell, FieldError), supabase client moved to @pi/web-services.
2026-08-25 — Web routing: route paths are constants in @pi/web-constants (ROUTING_PATH, packages/web-constants/src/routing-path/) — apps never hard-code route strings. web-admin page components live under src/pages/ (renamed from src/features/).
2026-08-25 — Icons: all icons live in @pi/ui — rendered via <Icon name="…" /> backed by the ICONS registry (src/components/pi/icon.tsx); apps never inline SVGs or import icon libraries directly. Storybook lives in the dedicated app apps/web-storybook (nx serve web-storybook, stories organized as Primitives/<Category>/<Name>); every new component gets a story there.
2026-08-25 — Auth flows specified (see 03-authentication.md): social sign-up ≡ sign-in; email/phone sign-up = password + one-time OTP verification over that channel; daily sign-in = password (no OTP); password reset = OTP over the account's channel. Self sign-up: app-user + app-sale only; web-admin stays closed (its /sign-up page is a dev-phase reference). Routes renamed /login → /sign-in, added /sign-up.