Skip to content

Hàm SQL ​

Trang sinh tự động

Sinh từ ad83b0aea — chạy 820 migration lên PostgreSQL 17 rồi đọc pg_catalog. Không sửa tay: lần chạy docgen sau sẽ ghi đè.

1.518 hàm của dự án (316 hàm còn lại do extension cấp và không tính vào đây). 940 hàm chạy SECURITY DEFINER — đây là nơi chứa phần lớn logic nghiệp vụ: resolver gọi hàm, hàm giữ bất biến và kiểm quyền.

901/1518 hàm có COMMENT ON FUNCTION (59%). Chỗ thiếu ghi "Chưa có mô tả".

Theo schema ​

SchemaHàmSECURITY DEFINERCó mô tả
public23913355
payment209155123
campaign15280134
ordering12794113
tier793337
fulfillment736149
identity_flow544323
spin493041
sale_admin462938
catalog39929
customer391934
mission372218
privacy321712
report301711
attribution292412
pipoint_adjust281516
cms261512
finance_policy2667
notification261622
pipoint_reward232020
rbac22193
report_export181210
sale_profile15812
pipoint_report1445
shortage13611
pipoint_ekyc101010
identity977
sale_team986
sale_application_access706
sale_qualification744
sale_view766
mfa650
affiliate_reward555
pipoint_events444
auth300
profile_access323
settings222
pipoint_access101

schema public ​

standard public schema

HàmTham sốTrả vềMô tả
accounts_identity_change_guard—trigger
addresses_reject_deleted_update—trigger
api_actor_admin_roles—text[]definerP1-05. Effective WEB_ADMIN roles of the acting principal (ACTIVE membership + account, unrevoked); empty unless app.app = WEB_ADMIN. Definer only to avoid RLS recursion in the staff policies.
api_actor_app—textP1-09. Claimed app from app.app (transaction-local), NULL if unset/unknown.
api_actor_id—uuidP1-09. Acting account from app.actor_id (transaction-local), NULL if unset/invalid.
api_guest_throttle_beginp_key_hash bytea, p_total integer, p_quotes integer, p_max_total integer, p_max_quotes integer, p_window_seconds integerjsonbdefiner#469 (DEC-469-03). Counts one admitted token-less document of a client in a fixed window: PROCEED {total, quotes} or THROTTLED {retry_after_seconds}. Guest actor only (no account, APP_USER). pi_api only.
api_session_activep_sid uuid, p_account_id uuid, p_app app_codebooleandefinerAF-P2-04. PIDEAL session live for (sid, account, app): token contract step 10, in the actor-loading query.
api_staff_directory—TABLE(account_id uuid, masked_phone text, account_status text, account_version integer, membership_status text, membership_status_reason text, membership_version integer, registered_at timestamptz, approved_at timestamp with time zone, updated_at timestamp with time zone, roles text[])definerP1-05 AD-05 staff.read: WEB_ADMIN staff rows with the phone masked in the database; empty unless the acting principal (WEB_ADMIN) holds admin or super_admin. The only cross-account identity read of pi_api.
app_memberships_insert_guard—trigger
app_memberships_kind_guard—triggerPPI-P2-01 (E-05). Trigger function: WEB_ADMIN only on STAFF, APP_USER / APP_SALE only on CUSTOMER. Attached by PPI-P2-02 (trigger app_memberships_kind_guard, BEFORE INSERT OR UPDATE OF account_id, app); a status UPDATE of a legacy WEB_ADMIN membership on a CUSTOMER account is not checked (PPI-P2-06 revokes those).
audit_actor_namesp_ids uuid[]TABLE(account_id uuid, display_name text)definerCV3-P4-17. profiles.full_name of WEB_ADMIN staff ids (<= 1000) for audit.read holders.
audit_event_actions—TABLE(action text, category text, severity text)definerCV3-P4-17 (DEC-CV3-33). Every action in audit_events with the category / severity of its newest row; audit.read only.
audit_event_countp_filter jsonbbigintdefinerCV3-P4-17 (DEC-CV3-33). Number of audit_events matching the filter; audit.read only.
audit_event_detail_insertablep_audit_event_id uuidbooleandefinerCV3-P4-02. True for an audit_events row of the acting principal flagged metadata.hasDetail.
audit_event_detail_reader—booleandefinerCV3-P4-02. True while the acting principal holds audit.read at ALL (Z-01).
audit_event_filter_sqlp_filter jsonbtextCV3-P4-17. WHERE text (format %L literals) of the audit list filter; owner-only helper of the audit reads.
audit_event_onep_id uuidTABLE(id uuid, occurred_at timestamptz, actor_account_id uuid, actor_app text, actor_roles text[], action text, category text, severity text, result text, resource_type text, resource_id text, resource_ids text[], request_id text, has_detail boolean, operation text, correlation_id text, reason text, resource_version bigint, client_ip text, user_agent text, before text, after text, metadata text)definerCV3-P4-17 (DEC-CV3-33). One audit_events row with before / after / metadata as JSON text, as stored; audit.read only.
audit_event_pagep_filter jsonb, p_limit integer, p_offset integerTABLE(id uuid, occurred_at timestamptz, actor_account_id uuid, actor_app text, actor_roles text[], action text, category text, severity text, result text, resource_type text, resource_id text, resource_count integer, request_id text, has_detail boolean)definerCV3-P4-17 (DEC-CV3-33). One page of audit_events, newest first, as stored (masked at write); audit.read only.
audit_event_read_require—voiddefinerCV3-P4-17. Raises 42501 unless the definer owner is RLS-exempt and the acting principal holds audit.read (Z-01).
campaign_children_guard—triggerdefiner
campaign_outcomes_guard—triggerdefiner
campaign_point_config_versions_guard—trigger
campaign_policy_versions_guard—triggerdefiner
campaign_state_events_guard—triggerdefinerU19-P1-01. Campaign history: no update; delete only by the cascade of its deleted campaign.
campaigns_after_change—triggerdefinerOne history row per campaign version (U19-P1-01 event names); U19-P1-02: an unversioned system update (clone source deleted) writes none; U19-P2-01: a COMMAND version takes its field diff from pideal.campaign_changes; CV3-P1-04: the refund_ordered:<id> WORKER version is REFUND_ORDERED.
campaigns_code—triggerdefinerU19-P1-02 B006.R13/R14. Gives every new campaign its code (campaign.next_code) and a copy its source code; both immutable, cloned_from_id may only become null (source deleted).
campaigns_delete_guard—triggerdefinerU19-P1-01. Hard delete only in DRAFT/PENDING_PUBLISH/UPCOMING and without orders (B006.R04, B198.R02).
campaigns_enqueue_outcome—triggerdefiner
campaigns_enqueue_recurring_close—triggerdefiner
campaigns_guard—triggerU19-P1-01. Word state machine (B006.R03), timed moves, version CAS, configuration lock from OPEN (B006.R12) and publish_at lock in UPCOMING (B006.R04). U19-P1-02: the ON DELETE SET NULL of cloned_from_id passes unversioned.
campaigns_legacy_flags—triggerU19-P1-06 GAP-W-CD-11. The legacy flags are never turned on after the backfill; legacy_unvalidated is cleared when a legacy draft leaves DRAFT.
campaigns_no_overlap—triggerdefinerU19-P1-02 B006.R18. Refuses a campaign entering (or re-timing within) the counted states over another counted campaign of its type: campaigns_no_overlap with the B284.R04 fields in DETAIL.
campaigns_outcome_required—triggerdefiner
cancellation_decisions_guard_insert—triggerdefiner
cashbook_entries_guard_insert—triggerdefiner
catalog_attribute_default_unit_listed—trigger
catalog_attribute_options_rules—trigger
catalog_attribute_rows_guard—trigger
catalog_attribute_units_rules—trigger
catalog_attribute_value_options_rules—triggerdefiner
catalog_attribute_values_highlight_limit—triggerdefiner
catalog_attribute_values_options_required—triggerdefiner
catalog_attribute_values_position—triggerdefiner
catalog_attribute_values_shape—triggerdefiner
catalog_attribute_values_validate—triggerdefiner
catalog_attributes_rules—trigger
catalog_brands_guard—trigger
catalog_categories_tree_guard—triggerU6-P2-20: tree shape guard of public.categories. max_level = parent already at level 5; subtree_max_level = parent below level 5 but the moved subtree would exceed 5 levels (NEW-NH-01).
catalog_combo_components_guard—trigger
catalog_detach_products—trigger
catalog_product_accessories_guard—triggerdefiner
catalog_product_accessories_unit_guard—triggerdefiner
catalog_product_import_runs_frozen—trigger
catalog_product_media_close_use—trigger
catalog_product_media_complete—trigger
catalog_product_media_guard—trigger
catalog_product_units_conversion_guard—trigger
catalog_product_units_guard—trigger
catalog_product_units_map—trigger
catalog_product_units_recompute_values—triggerdefiner
catalog_products_combo_complete—trigger
catalog_products_guard—trigger
catalog_products_status_guard—trigger
catalog_products_unit_guard—trigger
cms_articles_close_uses—triggerdefiner
cms_articles_guard—trigger
cms_banners_guard—trigger
cms_categories_tree_guard—trigger
cms_keywords_delete_guard—triggerdefiner
cms_keywords_state_guard—trigger
cms_pages_guard—trigger
cms_parent_has_version—trigger
cms_publish_ready_guard—triggerdefiner
cod_collections_guard_insert—triggerdefiner
cod_collections_guard_update—triggerdefiner
cod_remittances_guard_insert—triggerdefiner
content_versions_insert_guard—triggerdefiner
content_versions_record_uses—triggerdefiner
customer_group_memberships_guard—trigger
customer_groups_default_check—trigger
customer_groups_guard—trigger
daily_code_counters_guard—trigger
deal_terms_sets_touch—trigger
deposit_checkouts_enqueue—triggerdefiner
deposit_checkouts_insert_guard—trigger
deposit_checkouts_rearm_close—triggerdefinerPAF-P1-19 (DEC-PAF-18). A deposit checkout of an order of a CLOSING campaign ended: the close runs again.
deposit_checkouts_tender_snapshot—triggerdefiner
deposit_checkouts_transition_guard—trigger
event_actor_snapshot—triggerdefiner
fulfillment_events_guard_insert—triggerdefiner
fulfillment_exceptions_guard_insert—triggerdefiner
identity_guard_immutable—trigger
identity_guard_set_once—trigger
identity_reject_mutation—trigger
identity_touch_row—trigger
in_app_events_guard—trigger
job_runs_guard_transition—trigger
job_runs_record_event—trigger
media_insert_guard—trigger
media_is_catalog_imagep_media uuidbooleandefinerU6-P3-38. True for a READY, undeleted JPG/PNG PRODUCT_IMAGE of at most 5 MiB (product gallery, category image, brand logo). Ownership / attach rules stay in the API (assertAttachable) and the media_uses policies.
media_purpose_limits_insert—trigger
media_purpose_limits_ready—trigger
media_purpose_max_bytesp_purpose textbigintU6-P3-38. Largest object of a purpose in bytes (1 MB = 1 MiB; <= 20 MiB); null for an unknown purpose.
media_purpose_mimesp_purpose texttext[]U6-P3-38. MIME types a NEW ticket of the purpose may declare (mirror of purposes.ts); null for an unknown purpose.
media_sale_profile_attachedp_media uuid, p_purpose textbooleandefinerU6-P3-38. True when this Sale profile media is attached live to a Sale under the use type of its purpose.
media_update_guard—trigger
media_uses_insert_guard—trigger
member_tier_history_guard—triggerdefiner
mfa_reset_requests_guard—trigger
mfa_step_up_grants_guard—trigger
mission_assignments_completed_event—triggerdefiner
mission_assignments_insert_guard—trigger
mission_contributions_insert_guard—trigger
mission_criteria_guard—trigger
mission_versions_guard—trigger
order_close_outcomes_guard—triggerdefinerP2-15, U19-P2-06. An order close row matches its order (state, version) and its campaign outcome: LOCK under SUCCESS / PARTIAL_SUCCESS (legacy CONFIRMED), CANCEL under FAILED / PARTIAL_SUCCESS.
order_close_outcomes_open_remaining—triggerdefinerU19-P2-21, G1S-P1-02. Close LOCK: checks the remaining formula of the row shape (rounded to 1,000đ for rows with the Giá thực tế columns), opens the offline case of a cash excess, records the wallet refund of excess Pi-Point; no ONLINE remaining (default COD, B013.R11). The ONLINE obligation is opened by the buyer choice.
order_cycle_lines_insert_guard—triggerdefiner
order_cycles_guard—triggerdefiner
order_lines_insert_guard—trigger
order_periods_guard_mutation—triggerG2S-P1-04. order_periods stays append-only (identity_reject_mutation message) except the money of a period (prepaid_vnd, points_value_vnd, rounding_vnd) while ordering.drop_order_points drops the points of its order.
order_periods_insert_guard—trigger
order_points_excess_refunds_guard—triggerdefiner
order_quotes_basket_guard—triggerdefiner
order_quotes_group_cutoff—triggerdefiner
order_quotes_guard—triggerdefiner
order_remaining_methods_guard—triggerdefiner
order_return_cases_guard—triggerdefiner
orders_after_change—triggerdefiner
orders_commit_recurring—triggerdefiner
orders_copy_lines—triggerdefiner
orders_deposit_rounding_from_quote—triggerdefinerG1S-P1-01. BEFORE INSERT on orders: the order keeps the deposit rounding of its quote (CEIL, or HALF_UP for a quote written before 20261227010000), so orders_money checks the deposit the quote priced.
orders_group_cutoff—triggerdefiner
orders_guard_insert—triggerdefinerBEFORE INSERT on orders: checks the quote (own, OPEN; unexpired for Mua định kỳ), campaign and policy version, address and milestone, copies the snapshot and consumes the quote. G1S-P1-04: Mua chung is written at its quote's price (no expiry or tier recheck, R3). G1S-P1-04 + G2S-P1-04: every new order needs terms_accepted and consumes the re-priced quote named in repriced_from_quote_id too (Mua định kỳ: same basket, package, window and per-cycle quantities).
orders_guard_update—trigger
orders_issue_code—triggerdefiner#298. BEFORE INSERT on orders: draws a new code while it is blank or already used (20 draws, then orders_code_unavailable).
orders_payment_obligations—triggerdefinerP3-01. Records the DEPOSIT (and PI_POINT when points are used) obligation in the order insert transaction.
orders_recurring_package—triggerdefinerU19-P2-37, G2I-P2-01, U28-P2-04 (DEC-U28-03) = G2S-P1-04 (DEC-FS27-MD-EMPTY-CYCLE). Order insert (Mua định kỳ): copies the quote package / window, refuses a cycle with every product at 0 (orders_cycle_empty, detail {cycleNo} of the first one) and the first cycle below Giá trị đơn tối thiểu (orders_below_min_order_value, detail {cycleNo, shortfallVnd}).
orders_zero_deposit_refund_axis—triggerdefinerU19-R13 (GAP-W-DH-13 owner 20/10: allowed — needs re-checking). A cancelled 0 VND deposit order without cash waits for its Pi-Point return (WAITING_REFUND), never for a customer refund request.
password_credentials_touch—trigger
payment_allocations_guard_insert—triggerdefiner
payment_allocations_settle—triggerdefiner
payment_events_guard_insert—triggerdefiner
payment_hold_releases_guard—trigger
payment_intents_guard_insert—triggerdefiner
payment_intents_guard_update—triggerdefiner
payment_intents_rearm_close—triggerdefinerPAF-P1-19 (DEC-PAF-18) / #479. A DEPOSIT intent of an order of a CLOSING campaign left CREATED / PENDING / UNKNOWN (SUCCEEDED, FAILED, NEEDS_REVIEW): the close runs again.
payment_intents_remaining_follow—triggerdefinerPAF-P1-22 (finding 5). The attempt on an ONLINE REMAINING kept at its old amount (DEC-PAF-21 b) FAILED or expired: the remaining is opened again on the dues now (payment.recurring_remaining_follow). Only an order with a skip snapshot or a FORFEITED cycle; nothing when the obligations are busy.
payment_obligations_cod_due—triggerdefiner
payment_obligations_cod_end_case—triggerdefinerPAF-P1-26 (DEC-PAF-30). AFTER a cycle COD REMAINING obligation goes OPEN -> CANCELLED for a reason other than skip_respread, cycle_forfeited or remaining_switch_online: payment.recurring_cod_collect_case (source cod-collect🔚<obligation>; nothing unless the order has a skip or a COD rebalance and the rounding collected is now owed back). Internal.
payment_obligations_guard_insert—triggerdefinerP3-01, U28-P2-03. Insert guard of payment_obligations: OPEN v1, order snapshot amounts, REMAINING after the close, one method per order (PAY-BR04) except the online remaining of a Mua định kỳ order beside the COD of locked cycles.
payment_obligations_guard_update—triggerdefiner
payment_overpayment_cases_guard—triggerdefiner
payment_overpayment_cases_open_claim—triggerdefiner#479 C (Q4). Every new cọc dư case opens ONE EXCESS_DEPOSIT refund case (APPROVED, no leg, the stored excess) in the same transaction: the buyer claims it through the refund request flow, Operations transfer and confirm it. #479 D: the opened claim writes refund_case.excess_claim_opened (the buyer's notice EXCESS_DEPOSIT_CLAIM_OPENED).
pipoint_reject_delete—trigger
point_adjustments_enqueue—triggerdefiner
point_adjustments_insert_guard—trigger
point_adjustments_reverse_fence—triggerdefinerFU-1822. A CREDIT adjustment is refused (PT409) while another compensation of the same REDEEM would exceed it.
point_adjustments_transition_guard—trigger
point_reconciliation_items_guard—trigger
point_reconciliation_runs_guard—trigger
point_report_version_lines_guard—trigger
point_report_versions_guard—trigger
point_requests_adjust_link_guard—triggerdefinerPPI-P3-14 (DEC-PPI-OWN02-RECALL-OLDLINK), #479 A. Trigger: the ADJUST request of a system recall slip (RETURN_RECALL, FAILED_DELIVERY_RECALL) sits on the slip's link (live or ended); of a MANUAL slip on a live link of the account (PPI-P3-12). Internal.
point_requests_adjust_settles_checkout—triggerdefiner#479 T7. An ADJUST request became ACCEPTED: the COMPENSATION_REJECTED deposit checkouts of the REDEEM its CREDIT adjustment compensates are settled (payment.checkout_settle_manual_compensation).
point_requests_available_event—triggerdefiner
point_requests_debited_event—triggerdefiner
point_requests_insert_guard—triggerdefiner
point_requests_recall_rank_debit—triggerdefinerPPI-P5-09 (E-09d), #479 A. AFTER UPDATE trigger: an ADJUST DEBIT of an APPROVED customer system recall slip (RETURN_RECALL or FAILED_DELIVERY_RECALL) that PiPoint refused for insufficient points -> one PENDING system rank-only debit (rank_adjustments, no maker, the slip's reason code) of the same points.
point_requests_reverse_adjust_fence—triggerdefinerFU-1822. A REVERSE_REDEEM is not written ahead when an approved CREDIT adjustment already compensates the REDEEM.
point_requests_transition_guard—trigger
point_requests_worker_fence—trigger
point_reward_actions_enqueue—triggerdefiner
point_reward_actions_insert_guard—trigger
point_reward_actions_transition_guard—trigger
point_reward_partial_cancels_enqueue—triggerdefiner
point_reward_partial_cancels_guard—trigger
price_tiers_guard—triggerdefiner
provider_transactions_guard_insert—triggerdefiner
provider_transactions_guard_update—trigger
rank_adjustments_insert_guard—trigger
rank_adjustments_transition_guard—trigger
rank_lot_deductions_fefo_only—trigger
rank_lots_carry_remaining—trigger
rank_lots_guard—trigger
recovery_grants_insert_guard—trigger
recurring_basket_cycle_lines_guard—triggerdefiner
recurring_basket_lines_guard—triggerdefiner
recurring_baskets_cycle_empty—triggerdefinerG2S-P1-03 (BR-MD-05, DEC-FS27-MD-EMPTY-CYCLE). At commit: a DRAFT basket with a package has no cycle where every product is 0 (constraint recurring_baskets_cycle_empty, DETAIL = the cycle).
recurring_baskets_fill_package—triggerdefiner
recurring_baskets_guard—triggerdefiner
recurring_cycles_skip_cutoff_guard—triggerdefiner
recurring_forfeit_effects_follow_payment—triggerdefinerPAF-P1-22 (finding 4), PAF-P1-25 (DEC-PAF-28). On a forfeit approval (after the share is stored, before the refund case), under the lock of every obligation of the order: refused while a payment is in flight; the OPEN COD of the forfeited cycle is CANCELLED, the COD rounding of the cycles still to collect rebalanced (payment.recurring_forfeit_cod_rebalance) and an unpaid ONLINE remaining is opened again on the dues without it (payment.recurring_remaining_follow).
recurring_forfeit_reviews_update_guard—trigger
recurring_skip_requests_carry_deposit—triggerdefinerPAF-P1-03 (DEC-PAF-06). A skip accepted after the close spreads the deposit again (payment.recurring_skip_respread), in the same transaction and before recurring_skip_requests_complete (the order is still LOCKED for the case).
recurring_skip_requests_forfeited_guard—triggerdefiner
recurring_skip_requests_guard—triggerdefinerP2-18, G2I-P1-01 D13, G2I-P2-02 G6-Q2, U28-P2-04 DEC-U28-03, PAF-P1-02 DEC-PAF-05, #479 A. Insert guard of a skip press: the owner's LOCKED Recurring order, a cycle not left empty when ordering (recurring_skip_cycle_empty), with goods after the close (recurring_skip_cycle_no_goods), not in a shipment (recurring_skip_cycle_shipped; no time lock); the skips used (presses + empty cycles, ordering.skips_used) + the cycles settled as failed deliveries (ordering.failed_delivery_count) + 1 never exceed the package n (recurring_skip_limit_reached). skip_cutoff_at records the instant the skip was accepted.
recurring_skip_requests_update_guard—trigger
refund_branches_after_update—triggerdefiner
refund_branches_exec_enqueue—triggerdefiner
refund_branches_guard_insert—triggerdefiner
refund_branches_guard_update—triggerdefiner
refund_branches_manual_fence—triggerdefiner
refund_cases_check_legs—triggerdefiner
refund_cases_exec_enqueue—triggerdefiner
refund_cases_guard_insert—triggerdefiner
refund_cases_guard_update—triggerdefiner
refund_cases_record_history—triggerdefiner
refund_cases_refund_ordered—triggerdefinerCV3-P1-04 (BR-CT-10). An automatic FULL_ORDER CAMPAIGN_FAILED case of an order the close cancelled (stored order_close_outcomes CANCEL) records the campaign's one "Tạo lệnh hoàn cọc" in the same transaction.
refund_cases_zero_cash_axis—triggerdefinerU19-R13 (GAP-W-DH-13 owner 20/10: allowed — needs re-checking). The Pi-Point-only refund case of a 0 VND deposit order is complete: payment REFUNDED (PARTIALLY_REFUNDED when a cycle is kept, #479 B3), actor SYSTEM.
refund_receiver_profiles_guard_update—trigger
role_assignments_insert_guard—trigger
sale_applications_guard—trigger
sale_applications_record_event—trigger
sale_role_transfers_guard—trigger
shipment_order_links_effective_lines—triggerdefiner
shipment_order_links_skip_guard—triggerdefiner
shipments_guard_update—trigger
shipments_unresolved_handover_guard—triggerdefiner
spin_draws_after_insert—triggerdefiner
spin_draws_before_insert—triggerdefiner
spin_draws_roll_guard—triggerP4-16, VQM-P1-11. Re-derives the tier of a draw with a roll from the session's config_snapshot (the rule version for a session without one): a later Sửa of the wheel never changes the draws of an existing session (R-23).
spin_order_outcomes_immutable—trigger
spin_results_before_insert—triggerdefiner
spin_rule_versions_guard—triggerdefiner
spin_sessions_guard—trigger
staff_credentials_account_guard—trigger
stock_shortage_case_orders_guard—triggerdefiner
system_settings_touch—trigger
tier_assignments_guard—trigger
tier_children_guard—trigger
tier_definitions_no_delete—trigger
tier_reevaluations_guard—triggerdefiner
tier_set_items_guard—triggerdefiner
tier_set_versions_check—triggerdefiner
tier_set_versions_guard—triggerdefiner
tier_set_versions_rules—triggerdefiner
tier_set_versions_serialize—trigger
tier_versions_guard—trigger

schema payment ​

P3-01. Payment helpers (obligations, intents, transactions, allocations).

HàmTham sốTrả vềMô tả
actor_in_rolesp_roles text[]boolean
actor_is_reader—booleanP3-01. Matrix F-01 mirror (PROPOSED): ACTIVE WEB_ADMIN membership with a payment.reader_roles() role.
assert_next_versionp_table text, p_old integer, p_new integer, p_old_source text, p_new_source textvoid
attempt_corep_system boolean, p_request_id text, p_to text, p_session_ref text, p_result_code text, p_source text, p_source_id textpayment.intent_changedefinerP3-02. Create-attempt result: CREATED -> PENDING|UNKNOWN|FAILED (UNKNOWN -> FAILED on a rejected resend); a DEPOSIT failure leaves the order DEPOSIT_PENDING (#377); superseded answers are NO_CHANGE.
backfill_paid_milestone—TABLE(kind text, order_id uuid, cycle_no integer, source text)definerU19-P2-20. Idempotent backfill: PAID axis for orders already paid by their facts; order.paid for PAID orders whose pending reward was never released. Returns what it did.
buyer_claim_intent_leasep_request_id text, p_purpose text, p_holder uuid, p_seconds integerbooleandefiner#479 T4. pi_api, the buyer of the order: payment.lease_core.
buyer_deposit_due_atp_obligation_id uuidtimestamptzdefiner#479 T2. pi_api, the buyer of the order only (payment.caller_may_touch): when the deposit window of the order of this open DEPOSIT obligation ends; null otherwise. startDepositCheckout refuses a new attempt when less than one provider session is left.
buyer_excess_claimsp_order uuidTABLE(refund_case_id uuid, reference_code text, state text, can_submit boolean)definer#479 C. Excess claims of the caller's own order (buyer only): DU code, state, can_submit.
buyer_observep_request_id text, p_provider text, p_mode text, p_event_id text, p_event_type text, p_status text, p_txn_id text, p_amount_vnd bigint, p_payload_hash bytea, p_occurred_at timestamp with time zone, p_correlation_id textpayment.intent_changedefiner
buyer_open_checkoutp_obligation_id uuid, p_expected_version integer, p_source_id text, p_cash_request_id text, p_redeem_date date, p_correlation_id textpayment.checkout_statedefinerP3-04 / #377 / G1S-P1-05. The 7-argument write-ahead with method MOMO_WALLET.
buyer_open_checkoutp_obligation_id uuid, p_expected_version integer, p_source_id text, p_cash_request_id text, p_redeem_date date, p_correlation_id text, p_method textpayment.checkout_statedefinerP3-04 / #377 / G1S-P1-05. startDepositCheckout write-ahead (pi_api, own order): one LIVE checkout per order; a new numbered attempt after a REDEEM_REJECTED / CASH_FAILED / COMPENSATED one; same command scope = EXISTING; a Group Buy order of a closed campaign is refused (payment_checkout_campaign_closed); stores the payment method.
buyer_open_intentp_obligation_id uuid, p_expected_version integer, p_request_id text, p_provider text, p_mode text, p_payload_hash bytea, p_source_id text, p_correlation_id textpayment.intent_changedefinerP3-02. startDepositPayment write-ahead (pi_api, own order): one CREATED intent per attempt, or the existing one; refuses stale version, non-deposit, non-pending order, closed obligation and unsettled points.
buyer_open_remaining_intentp_obligation_id uuid, p_expected_version integer, p_request_id text, p_provider text, p_mode text, p_payload_hash bytea, p_source_id text, p_correlation_id textpayment.intent_changedefinerP3-05, U19-P2-21, PAF-P1-25. startRemainingPayment (pi_api, own order): opens one gateway attempt on the ONLINE REMAINING obligation (stale version, COD choice, live attempt, order state and obligation status refused). An unpaid remaining of an order with a skip or a forfeit not at the dues now is re-synced first (payment.recurring_remaining_resync, busy -> payment_remaining_busy) and the attempt opens on the re-opened remaining.
buyer_record_attemptp_request_id text, p_to text, p_session_ref text, p_result_code text, p_source text, p_source_id textpayment.intent_changedefiner
buyer_record_sessionp_request_id text, p_pay_url text, p_deeplink text, p_qr_data text, p_expires_at timestamp with time zonebooleandefiner#479 T5. pi_api, the buyer of the order: records the session of its PENDING intent (payment.session_core).
buyer_refund_accountp_order uuidTABLE(bank_name text, account_last4 text)definer#412 G1-10. Bank name and the last 4 account digits of the latest refund receiver profile of the caller's OWN order. Never the CCCD, the holder or the full account number.
buyer_refund_rejectionsp_order uuidTABLE(refund_case_id uuid, reason_code text, customer_note text, requested_at timestamptz, superseded boolean)definerG2I-P1-03 O6a. The latest Operations send-back of each refund case of the buyer's OWN order: code, the note only when marked for the customer, time, superseded by a newer revision. Never the internal reason.
buyer_refund_transfersp_order uuidTABLE(refund_case_id uuid, code_tail text, transferred_on date, source text)definer#412 O-37D. Per refund case of the caller's OWN order: last 4 characters of the transfer code, its date and who confirmed it (OPERATIONS transfer record, else the PROVIDER refund of an accepted cash leg).
buyer_release_intent_leasep_request_id text, p_purpose text, p_holder uuidbooleandefiner#479 T4. pi_api, the buyer of the order: payment.lease_release_core.
buyer_remaining_methodp_order uuidTABLE(method text, version integer)definerU19-P2-21. Order.paymentMethod (pi_api): method and choice version of the caller's own order; nothing otherwise.
buyer_remaining_switchp_order uuidjsonbdefinerU28-P2-03, PAF-P1-09. Order.remainingSwitch (pi_api): payment.remaining_switch of the caller's own order (Mua chung or Mua định kỳ, after the close); null otherwise.
buyer_select_remaining_methodp_order_id uuid, p_method text, p_expected_version integer, p_source_id textjsonbdefinerU19-P2-21, U28-P2-03, PAF-P1-09. selectRemainingPaymentMethod (pi_api, own CONFIRMED order): records ONLINE | COD. Mua chung: before Dang dong goi, cancels an OPEN COD remaining and opens the online remaining (R-09, DEC-PAF-09). Mua định kỳ after the close (DEC-U28-04): per cycle, cancels the COD of the open cycles and opens the versioned online remaining of ⌈Σ due⌉ - locked COD (all_cycles_locked / nothing_remaining refused); refuses COD while an online attempt is live; logs payment.method_selected. PAF-P1-25: a Mua chung ONLINE choice with nothing left to pay is refused nothing_remaining (the choice is not recorded).
caller_may_touchp_system boolean, p_obligation_id uuidboolean
cancel_decidep_order uuid, p_source_type text, p_source_id textjsonbdefiner
cancel_decision_jsonp_id uuidjsonbdefiner
cancel_evaluatep_cause text, p_campaign_type text, p_timing textjsonb
cancel_policy_version—text
cashbook_manual_guardp cashbook_entriescashbook_entriesdefiner
change_ofp_outcome text, p_intent uuid, p_prior_version integer, p_prior_status text, p_order_prior_version integer, p_order_prior_state textpayment.intent_change
checkout_settle_manual_compensationp_id uuidpayment.checkout_statedefiner#479 T7 (GAP-1850 route). A COMPENSATION_REJECTED checkout whose REDEEM an ACCEPTED CREDIT ADJUST returned in full: -> COMPENSATED_MANUALLY, the point tender REVERSED, event deposit_checkout.compensated_manually; otherwise NO_CHANGE. pi_worker (the saga) and the ADJUST trigger.
checkout_state_ofp_outcome text, p_id uuidpayment.checkout_state
close_covered_paid—triggerdefinerU19-P2-20. Group Buy LOCK close with remaining 0 -> payment.mark_paid(DEPOSIT_COVER), SYSTEM.
close_payment_wait—interval#479 T6. The longest a campaign close waits for a live deposit attempt started before closes_at, counted from closes_at: the transaction setting pi.close_payment_wait_minutes (whole minutes) set by the close jobs; null = no cap.
cod_apply_evidencep_cod uuid, p_type text, p_ref text, p_by uuid, p_amount bigint, p_at timestamp with time zone, p_evidence_ref text, p_media uuid, p_source text, p_source_id text, p_hash textjsonbdefiner
cod_changep_cod uuid, p_kind textjsonbdefiner
cod_collector_roles—text[]U19-P2-31. Matrix COD-01 cod.collect mirror: operations and admin record a COD collection by hand (Word B186.R02, B244.R06; supersedes the admin-only rule of U13-FU-01 / DEC-U13-COD-COLLECT-ADMIN).
cod_document_okp_media uuidbooleandefiner
cod_lock_for_commandp_cod uuid, p_expected_version integercod_collectionsdefiner
cod_reconciliation_items_guard—trigger
cod_reconciliation_localp_end timestamp with time zoneTABLE(cod_id uuid, status text, obligation_status text, amount_due_vnd bigint, assigned_at timestamptz, delivered_at timestamp with time zone, collected_amount_vnd bigint, collected_at timestamp with time zone, completed_at timestamp with time zone, collector_type text, collector_ref text, collection_recorded_at timestamp with time zone, carrier_code text, shipment_id uuid, shipment_state text, shipment_delivered_at timestamp with time zone, remitted_amount_vnd bigint, remitted_at timestamp with time zone)definerP3-14. COD rows with obligation, collection, remittance and shipment facts for the COD reconciliation job (pi_worker): ids, states, amounts, carrier code, collector reference, times only. Read-only definer.
cod_reconciliation_runs_guard—trigger
cod_record_carrier_collectionp_carrier_code text, p_carrier_ref text, p_event_id text, p_amount bigint, p_collected_at timestamp with time zone, p_payload_hash textjsonbdefiner
cod_record_remittancep_cod uuid, p_expected_version integer, p_ref text, p_amount bigint, p_remitted_at timestamp with time zone, p_media uuid, p_note text, p_source_id textjsonbdefiner
cod_record_shipment_collectionp_shipment uuid, p_expected_version integer, p_total bigint, p_collected_at timestamp with time zone, p_evidence_ref text, p_media uuid, p_source_id textjsonbdefinerU19-P2-31 / U19-R26. Collect every OPEN COD obligation of a DELIVERED shipment in one transaction, the COD rows synced inline first (no consumer needed): shipment.update (updateShipmentStatus tick) or cod.collect (recordShipmentCodCollection); optional reference; Da thanh toan with the confirming actor; syncChanges = the inline sync.
cod_record_staff_collectionp_cod uuid, p_expected_version integer, p_amount bigint, p_collected_at timestamp with time zone, p_evidence_ref text, p_media uuid, p_source_id textjsonbdefiner
cod_remittance_gaps_guard—trigger
cod_remitter_roles—text[]P3-06. Matrix COD-02 cod.remit mirror (PROPOSED, GAP-77): finance.
cod_settlep_cod uuid, p_source text, p_source_id textvoiddefinerP3-06, PAF-P1-26. COD obligation OPEN -> SETTLED once its cod_collections row is COLLECTED (every collection path: payment.cod_apply_evidence, payment.cod_sync_shipment); then, for a Mua định kỳ order with a skip or a forfeit, the COD rounding collected above the due is one SKIP case (payment.recurring_cod_collect_case, DEC-PAF-30). Internal.
cod_states—text[]
cod_sync_shipmentp_shipment uuid, p_source_id textjsonbdefiner
cod_transition_allowedp_from text, p_to textbooleanP3-06. COD machine: DUE -> ASSIGNED -> DELIVERED -> COLLECTED -> REMITTED (collected is never remitted).
cycle_failed_deliveryp_order_cycle uuidbooleandefiner#479 A. Internal: the cycle was settled by Operations as a failed delivery (any outcome).
cycle_forfeit_droppedp_order_cycle uuidbooleandefinerPAF-P1-22 (finding 4). A FORFEITED cycle whose forfeit was approved while the online remaining of the order was not captured (COD, or online not paid yet): it left the payment plan, due and COD 0 from then on. A forfeit after the online remaining was paid keeps them (that capture paid the cycle; the forfeit refund weighs it). Internal.
cycle_forfeit_refund_rejectedp_order_cycle uuidbooleandefinerPAF-P1-25 (DEC-PAF-29). A FORFEITED cycle whose forfeit refund case was REJECTED (and no other case of it lives): a later whole-order refund refunds it again. No case yet, or PENDING / APPROVED / REFUNDED: false. Internal.
cycle_method_lockedp_shipping textbooleanU28-P2-03 (DEC-U28-04, DH-US-13 AC03). A cycle is locked (fixed COD, out of the COD -> ONLINE switch) from Đang đóng gói.
cycle_skippedp_order uuid, p_cycle integerbooleandefinerU19-P2-20, G2I-P2-02 (G6-Q2). A Recurring cycle the buyer skipped (order_cycles SKIPPED or a REQUESTED skip) or with nothing to deliver (empty when ordering, or every product left the order at the close); single read point.
deposit_due_atp_created_at timestamp with time zonetimestamptzdefiner#377 D2. created_at + the governing payment window (payment.order_window_for, the one the expiry applies); null when no APPROVED window governs. Reads only the window table; no order data.
emit_order_paidp_order uuid, p_cycle integer, p_milestone boolean, p_source text, p_actor uuidvoiddefinerU19-P2-20. Outbox order.paid {orderId, cycleNo, isRewardMilestone, source}, aggregate <order>:paid, once.
excess_refund_statep_case uuidtextdefiner#479 C. State of an excess claim: WAITING_REQUEST (nothing sent, or sent back), WAITING_REFUND, REFUNDED; null for any other case.
expire_unpaid_for_campaignp_campaign_id uuidTABLE(order_id uuid, order_version integer, prior_version integer, policy_version_id uuid, deposit_obligation_id uuid, deposit_vnd bigint, window_id uuid, window_minutes integer, due_at timestamptz, intent_changes jsonb, cancel_reason text)definerU19-P2-19 (DH-US-10 DESC/AC05) / G1S-P1-05 / PAF-P1-19 / #479 T6. pi_worker only: cancels every unpaid INITIATED order of a closing campaign (reason deposit_unpaid_at_close -> CANCELLED/DEPOSIT_UNPAID_AT_CLOSE), except an order with a live deposit attempt created before closes_at while now() < closes_at + payment.close_payment_wait() (DEC-PAF-18: the close waits for it; no cap when unset); each row carries the stored cancel_reason.
expire_unpaid_orderp_order uuid, p_reason text, p_source text, p_skip_locked booleanjsonbdefinerU19-P2-19 (Word B056.R02). Cancels one unpaid INITIATED order: live intents FAILED, OPEN obligations CANCELLED, order DEPOSIT_FAILED = CANCELLED/UNPAID/DEPOSIT_TIMEOUT, actor SYSTEM. Returns the intent changes, null = untouched.
expire_unpaid_ordersp_limit integer, p_correlation_id textTABLE(order_id uuid, order_version integer, prior_version integer, policy_version_id uuid, deposit_obligation_id uuid, deposit_vnd bigint, window_id uuid, window_minutes integer, due_at timestamptz, intent_changes jsonb, cancel_reason text)definerU19-P2-19 (Word B056.R02, was FU-DEF149) / G1S-P1-05. pi_worker only: cancels INITIATED/UNPAID orders whose window (seeded 1440 min) elapsed and with nothing in flight (order CANCELLED/DEPOSIT_TIMEOUT, actor SYSTEM, evidence row); each row carries the stored cancel_reason.
fail_deposit_orderp_order_id uuid, p_kind text, p_source_id textvoid#377 D1(a). No-op: a failed DEPOSIT attempt leaves the order DEPOSIT_PENDING (retry on the same order).
funds_guard—trigger
funds_model_statusp_at timestamp with time zonetextdefiner
group_pay_now_pointsp_order uuidintegerdefinerPAF-P1-09 (BR-MC-05). Thưởng thanh toán online of a Mua chung order as the reward consumer computes ONLINE_REMAINING: fixed points, or floor(final price x % / POINT_RATE in force); 0 without a bonus; null when unknown.
group_remaining_switchp_order uuidjsonbdefinerPAF-P1-09 (R-09, DEC-PAF-09). COD -> ONLINE switch of a Mua chung order after the close: available before Đang đóng gói, the close remaining (or the OPEN online remaining), no cycles, the Thưởng thanh toán online preview; null before the close or for another campaign type.
intent_hold_openp_intent uuidbooleandefiner#479 two-step. True when the provider's last word on the intent is AUTHORIZED (no SUCCEEDED, FAILED or REFUNDED observation recorded after it) and no capture is recorded. Internal.
intent_states—text[]
intent_transition_allowedp_from text, p_to textbooleanP3-01 / #479. Payment intent machine; NEEDS_REVIEW (terminal) = a captured provider result that cannot be applied; UNKNOWN -> PENDING when the provider reports the session still open (T5).
is_deposit_point_requestp_operation text, p_source text, p_order uuidboolean
is_refund_point_requestp_operation text, p_source text, p_order uuidboolean
lease_corep_system boolean, p_request_id text, p_purpose text, p_holder uuid, p_seconds integerbooleandefiner#479 T4. Takes (or renews, same holder) the lease of one provider step of an intent for p_seconds: SEND while CREATED / UNKNOWN; QUERY while PENDING / UNKNOWN; CAPTURE while PENDING / UNKNOWN with nothing captured, the obligation OPEN and the order payable (DEPOSIT_PENDING / LOCKED). False when the step is not allowed or another holder has a live lease. Lock order order -> obligation -> intent. Internal: buyer_/system_claim_intent_lease.
lease_release_corep_system boolean, p_request_id text, p_purpose text, p_holder uuidbooleandefiner#479 T4. Ends the lease of p_holder (false when it is not the holder any more). Internal: buyer_/system_release_intent_lease.
mark_paidp_order uuid, p_cycle integer, p_source text, p_actor uuidbooleandefinerU19-P2-20, U28-P2-02, U28-FU-REWARD, #479 A. Da thanh toan for an order or a Recurring cycle (ONLINE | COD | DEPOSIT_COVER), idempotent; logs PAYMENT through the axis writers and emits order.paid once per cycle. A paid cycle also settles the later cycles whose COD (payment.recurring_cycle_cod) is 0 while they owe once no earlier COD cycle is left to collect. PARTIAL_SUCCESS orders too; a cycle settled as a failed delivery owes nothing. Returns true when something moved.
mock_momo_create_plans_guard—trigger
mock_momo_sessions_guard—trigger
obligation_method_okp_kind text, p_method textboolean
obligation_settled_paid—triggerdefinerU19-P2-20, U28-P2-03. REMAINING settled -> payment.mark_paid (ONLINE: the order, or for a switched Mua định kỳ order each cycle without a fixed COD; COD: its cycle or the order), SYSTEM.
obligation_transition_allowedp_from text, p_to textbooleanP3-01 / #377. OPEN -> SETTLED | CANCELLED; PI_POINT only (table check + guard): SETTLED -> REVERSED (the REDEEM was fully reversed) -> SETTLED (the next attempt's ACCEPTED REDEEM).
observe_corep_system boolean, p_request_id text, p_provider text, p_mode text, p_event_id text, p_event_type text, p_status text, p_txn_id text, p_amount_vnd bigint, p_payload_hash bytea, p_occurred_at timestamp with time zone, p_correlation_id textpayment.intent_changedefinerP3-02 / #479. Applies one verified provider observation once (event dedupe, unique capture, intent lock): SUCCEEDED settles + PLACED, FAILED fails the attempt, a capture that cannot be applied (AMOUNT_MISMATCH / NOT_APPLICABLE) ends it NEEDS_REVIEW; late/duplicate observations never regress or double-apply.
open_remainingp_order_id uuid, p_final_total_vnd bigint, p_close_outcome_id uuid, p_source_id textTABLE(obligation_id uuid, remaining_vnd bigint, excess_vnd bigint, case_id uuid)definerP3-05, G1S-P1-02, U28-P2-02, U28-P2-03. One live ONLINE REMAINING obligation (> 0, never per cycle, versioned source after a cancelled one) and an offline overpayment case for the cash excess; a Recurring order at its close ⌈final - min(points value, final) - deposit⌉ to 1,000đ, after it the DEC-U28-04 switch amount (payment.remaining_switch); idempotent.
order_cash_collectedp_order uuidbooleandefinerU19-R13. True when the order ever collected cash (a SUCCEEDED capture or a COD collection).
order_excess_refund_requestsp_scope text, p_orders uuid[]jsonbdefiner#479 C. Excess claims (cọc dư refunded through the refund request flow) of each visible order (order.read TEAM/ALL): DU code, amount, state, latest request, transfer, canProcess; the masked profile only for order.refund.process.
order_expiry_blockedp_order uuidbooleandefinerU19-P2-19 / #377 / #479. True while money or points of an unpaid order may be in flight (unknown/succeeded intent, captured cash of an attempt that is neither FAILED nor NEEDS_REVIEW, a live CAPTURE lease of an authorized session, running checkout, a REDEEM neither rejected, reversed nor adjusted back, outside its CASH_PENDING checkout).
order_expiry_window—TABLE(window_id uuid, version_no integer, window_minutes integer, effective_from timestamptz)definer
order_refund_requestsp_scope text, p_orders uuid[]jsonbdefinerU19-P2-14, #479 B/C. Refund request of each visible order (order.read TEAM/ALL): amount, gateway, cancel reason/time, Pi-Point state, latest revision; the masked receiver profile only for order.refund.process (NFR #5). A return record (RETURN) and an excess claim (EXCESS_DEPOSIT, AdminOrder.excessRefundRequests) are not the refund request.
order_return_outcomesp_scope text, p_orders uuid[]jsonbdefiner#479 B. Return records (RETURN refund cases) of each visible order (order.read TEAM/ALL): outcome, kept cash / points, reason, date, internal note, who and when.
order_window_forp_created_at timestamp with time zoneTABLE(window_id uuid, window_minutes integer)definer
order_window_guard—triggerdefiner
overpayment_case_cycle_nop_case uuidintegerdefiner#479. Internal: the cycle number of a cọc dư case (SKIP skip:<cycle>, cod-collect:<collection>, FAILED_DELIVERY failed:<cycle>; null for the close), the rule of ordering.order_excess_deposits.
overpayment_case_from_depositp_source textbooleanPAF-P1-22, PAF-P1-25, PAF-P1-26. True for a cọc dư case the deposit funds (CLOSE overpayment:<order>, SKIP skip:<cycle> of a respread); false for a SKIP case paid above the due: skip-remaining:<obligation> (DEC-PAF-25) and the COD rounding no cycle absorbs (cod-collect:, DEC-PAF-30; skip-cod: / forfeit-cod: before it). Internal.
overpayment_cases_capturedp_order uuidbigintdefinerPAF-P1-25 (finding A, DEC-PAF-26). Σ excess of the cọc dư cases of the order whose money is inside its captures: the deposit ones (CLOSE, SKIP skip:) and skip-remaining: (the online capture). skip-cod: / forfeit-cod: were paid by COD on kept cycles and are never subtracted from a refund of captures. Internal.
payments_needing_attentionp_unknown_before timestamp with time zone, p_kind text, p_limit integer, p_offset integerjsonbdefiner#479 T6 / T9 / two-step. pi_api, Finance only (F-01, payment.actor_is_reader(); null otherwise): one page, oldest first, of the intents UNKNOWN since p_unknown_before or earlier, the intents NEEDS_REVIEW whose capture is still unapplied, the deposit checkouts COMPENSATION_REJECTED, the provider event conflicts of the last 30 days and the provider holds the sweep could not release, each with its customer (name, masked phone), with the total and the count per kind. Read only.
period_rowsp_ids uuid[], p_money booleanTABLE(order_id uuid, cycle_no integer, delivers_from timestamptz, delivers_to timestamp with time zone, obligation_vnd bigint, paid_vnd bigint, remaining_vnd bigint)definerFU-AC-TRIAGE L5 + FU-F3, PAF-P1-21, PAF-P1-24. Per-period obligation / paid / remaining of Recurring orders: the stored close allocation (final price; deposit cash of payment.recurring_cycle_alloc, so after a skip the deposit spread again, plus the Pi-Point share of the close) when the close made one, else the order-time V0 allocation from the last period backwards; a skipped (payment.cycle_skipped) or FORFEITED cycle has obligation 0 and remaining 0 (paid as allocated); NULL money for a non-Finance caller.
prepay_bonus_pointsp_order uuidintegerdefinerU28-P2-03, U28-FU-REWARD (BR-DK-07, CD-US-12 AC16 / AC17). Prepay bonus points of a Mua định kỳ order: fixed points, or floor(base x % / POINT_RATE in force), base = Σ kept final value after a partial close of the order, else V0; 0 without a bonus; null when the unit or the rate is missing.
provider_okp_provider text, p_mode textboolean
reader_roles—text[]
receipt_postp_txn uuid, p_posted_by textjsonbdefiner
receipt_reader_roles—text[]
receipt_sweepp_limit integer, p_posted_by textjsonbdefiner
receipt_sync_intentp_intent uuid, p_posted_by textjsonbdefiner
reconcile_reader_roles—text[]
reconcile_resolver_roles—text[]
reconciliation_items_guard—trigger
reconciliation_localp_provider text, p_mode text, p_start timestamp with time zone, p_end timestamp with time zone, p_txn_ids text[], p_request_ids text[]TABLE(source text, transaction_id uuid, intent_id uuid, request_id text, kind text, provider_txn_id text, amount_vnd bigint, currency text, status text, at timestamptz)definerP3-13 + FU-DEF151. PIDEAL side of one VN day for the payment reconciliation job (pi_worker): ids, kind, amount, status, time only; also the SUCCEEDED captures of the request ids the provider names (other-day context). Read-only SECURITY DEFINER; fails closed when the owner is not RLS-exempt.
reconciliation_runs_guard—trigger
record_return_no_refundp_order uuid, p_cycle_no integer, p_expected_version integer, p_reason text, p_returned_on date, p_note text, p_source_id textjsonbdefiner#479 B (Q3 11/11). Operations record that a returned unit paid in full (Mua chung order / Mua định kỳ cycle) is not refunded: one RETURN NO_REFUND refund case (CLOSED, kept = everything paid, reason, date, note), the unit's payment RETURN_NO_REFUND. order.refund.process, not the buyer; replay by source id.
recurring_cod_balancep_basis text[], p_due bigint[], p_cod bigint[], p_kept boolean[], OUT cod_vnd bigint[], OUT excess_vnd bigintrecordPAF-P1-22 (finding 8), PAF-P1-25 (DEC-PAF-28). Per close row (cycle order): basis (SKIPPED / FIXED / RESPREAD = still to collect), due, COD, kept. Σ COD of the kept rows becomes ⌈Σ their due⌉ to 1,000đ: an excess is absorbed by the RESPREAD rows last -> first down to 0 (excess_vnd = what none absorbs), a shortfall goes on the last RESPREAD row that owes (excess_vnd 0). Used by the skip respread and the forfeit rebalance. Internal.
recurring_cod_collect_casep_order uuid, p_source textbigintdefinerPAF-P1-26 (DEC-PAF-30). On a Mua định kỳ order with a skip snapshot or a COD rebalance (LOCKED, FULFILLED, CANCELLED or FORFEITED with delivered cycles): one SKIP cọc dư case (own DU code, source p_source = cod-collect:..., final = value of the kept cycles) for the increase of least(collected, planned) of payment.recurring_cod_rounding over the COD-rounding cases already open; nothing when there is no increase, idempotent on the source. Locks the order. Returns the amount opened. Internal.
recurring_cod_roundingp_order uuid, OUT planned_vnd bigint, OUT collected_vnd bigint, OUT recognized_vnd bigintrecorddefinerPAF-P1-26 (DEC-PAF-30). COD rounding of a Mua định kỳ order with a skip snapshot or a COD rebalance (0 / 0 otherwise): planned = Σ COD of the kept cycles whose COD can still be or was collected - ⌈Σ their due⌉ (what no cycle absorbs), collected = Σ COD collected on the kept cycles - ⌈Σ due of exactly those⌉, both to 1,000đ and >= 0, due / COD of payment.recurring_cycle_alloc; recognized = Σ of the COD-rounding cases already open (cod-collect:, skip-cod:, forfeit-cod:). Internal.
recurring_cycle_allocp_order uuidTABLE(order_cycle_id uuid, cycle_no integer, cash_vnd bigint, due_vnd bigint, cod_vnd bigint, respread boolean)definerPAF-P1-03, PAF-P1-22 (DEC-PAF-06), PAF-P1-25 (DEC-PAF-28). Per close row of a Mua định kỳ order: deposit share, exact due and COD now: the latest skip snapshot (order_cycle_skip_values, respread = true), else the close rows (COD as U28-FU-REWARD: stored owed, or the COD allocation of an ONLINE close on the actual price); the COD of the latest forfeit rebalance newer than that snapshot (order_cycle_cod_rebalances, respread = true); due and COD 0 for a forfeit that left the payment plan (payment.cycle_forfeit_dropped). Internal.
recurring_cycle_codp_order uuidTABLE(order_cycle_id uuid, cycle_no integer, due_vnd bigint, cod_vnd bigint)definerU28-FU-REWARD, PAF-P1-03 (DEC-U28-01, DEC-U28-12, DEC-PAF-06). Per close row of a Mua định kỳ order: the exact due and the COD the cycle takes at the method lock, from payment.recurring_cycle_alloc (after a skip: the deposit spread again on the cycles still delivered). Internal.
recurring_deposit_legsp_order uuidTABLE(refund_case_id uuid, amount_vnd bigint)definerU28-P2-11. The cash legs of an order's refund cases drawn on a DEPOSIT capture (the deposit part of each case).
recurring_forfeit_cod_rebalancep_review uuid, p_order uuid, p_order_cycle uuidjsonbdefinerPAF-P1-25 (DEC-PAF-28), PAF-P1-26 (DEC-PAF-30). On a forfeit approval that left the payment plan (payment.cycle_forfeit_dropped), ACTUAL_PRICE close: the COD of the kept cycles is balanced to ⌈Σ their due⌉ by payment.recurring_cod_balance (the cycles still to collect absorb, last -> first); the new COD of every close row in order_cycle_cod_rebalances (written also when only a rest is left), what none absorbs owed back only as it is collected (payment.recurring_cod_collect_case), an open COD that changes re-opened. Nothing when already balanced. Caller holds the order and its obligations. Internal.
recurring_order_moneyp_order uuidjsonbdefinerU28-P2-02, U28-P2-03, U28-P2-11, U28-FU-REWARD, PAF-P1-03, PAF-P1-22, PAF-P1-25, PAF-P1-26. Hold / refund / outstanding of a Mua định kỳ order after its close from the stored facts: deposit = held + refund due + refunded (the DEPOSIT legs of its refund cases) + the deposit cases; cash surplus = Σ of its offline overpayment cases (the close, every skip that left cọc dư, and what was paid above the due: an online remaining kept at its old amount, DEC-PAF-25, or a COD rounding no cycle absorbs), excess Pi-Point once refunded, the outstanding (online remaining + COD of locked cycles; due and COD per cycle of payment.recurring_cycle_cod; a skipped, CANCELLED or FORFEITED cycle owes nothing) and the 1,000đ rounding (paid-above cases and the COD rounding not collected yet excluded, PAF-P1-26; an OPEN remaining of an order with a skip or a forfeit counts at the dues now, an attempt in flight at an old amount stays outstanding, PAF-P1-25), and per close row the collected / outstanding, method (COD when the cycle keeps a live COD), lock and COD of the cycle; null before the close.
recurring_remaining_followp_order uuid, p_change_source text, p_source_id text, p_reason textbooleandefinerPAF-P1-03, PAF-P1-22. An unpaid OPEN ONLINE remaining of a closed Mua định kỳ order (nothing allocated, no attempt in flight) whose amount is not payment.recurring_remaining_target is CANCELLED and opened again by payment.open_remaining (the switch amount). Caller holds the order and its obligations. Internal.
recurring_remaining_followedp_order uuidbooleandefinerPAF-P1-25 (finding C). A LOCKED Mua định kỳ order with a skip snapshot or a FORFEITED cycle: its unpaid ONLINE remaining follows the dues now (payment.recurring_remaining_follow), as public.payment_intents_remaining_follow decides. Internal.
recurring_remaining_resyncp_order uuid, p_source_id textbooleandefinerPAF-P1-25 (finding C). Before the buyer pays the ONLINE remaining of a followed order: the order and every obligation locked (NOWAIT, busy -> payment_remaining_busy), then payment.recurring_remaining_follow (an unpaid OPEN remaining not at the dues now is CANCELLED and opened again). True when it re-opened. Internal.
recurring_remaining_settled_excess—triggerdefinerPAF-P1-22 (DEC-PAF-25). An ONLINE REMAINING of a Mua định kỳ order with a skip snapshot or a forfeit effect SETTLED above payment.recurring_remaining_target (its amount kept by an attempt in flight at a skip, DEC-PAF-21 b, or by a forfeit approved before this rule): one SKIP overpayment case for the difference, source skip-remaining:<obligation>, its own DU code; idempotent.
recurring_remaining_targetp_order uuidbigintdefinerU28-P2-03 (DEC-U28-04), PAF-P1-03, PAF-P1-22. What the ONLINE remaining of a closed Mua định kỳ order is now: ⌈Σ due of the cycles still owed (not skipped, CANCELLED or FORFEITED)⌉ to 1,000đ (EVEN_SPLIT: not rounded) - Σ COD of the locked cycles; due of payment.recurring_cycle_alloc. The computed amount of payment.remaining_switch. Internal.
recurring_skip_basisp_order uuidTABLE(order_cycle_id uuid, cycle_no integer, value_vnd bigint, net_vnd bigint, basis text, cash_vnd bigint, due_vnd bigint, cod_vnd bigint)definerPAF-P1-03, #479 A. Per close row of a Mua định kỳ order: value, net value (value - Pi-Point share), basis of a respread (SKIPPED = skipped or settled as a failed delivery, FIXED = paid / cancelled / out of COMMITTED / Đang đóng gói or later, RESPREAD) and the current allocation (payment.recurring_cycle_alloc). Internal.
recurring_skip_respreadp_skip uuidjsonbdefinerPAF-P1-03, PAF-P1-22, PAF-P1-26, #479 A (DEC-PAF-06, DEC-PAF-08, DEC-PAF-30, BR-MD-07 / BR-MD-10 / BR-DK-06). After a skip of a closed Mua định kỳ order, or a cycle settled as a failed delivery while the order continues (p_skip = the order_cycle_failed_deliveries row: case kind FAILED_DELIVERY, source failed:<order cycle>), the obligations of the order locked first (NOWAIT, else recurring_skip_payment_busy): the deposit not held by fixed cycles (paid, cancelled, forfeited, Đang đóng gói or later) nor by deposit cases is spread again last -> first on the cycles still delivered and not paid (campaign.recurring_allocate_actual), their COD balanced so that Σ COD of every kept cycle = ⌈Σ due⌉; the deposit left is one case; the COD rounding no cycle absorbs is owed back only as it is collected (payment.recurring_cod_collect_case, codExcessVnd = the planned rest); snapshot in order_cycle_skip_values, the open COD / ONLINE remaining follow, a cycle now covered is paid. Not for an order paid online in full (no refund, no case). Internal.
recurring_stop_onlinep_order uuid, p_source text, p_reason textintegerdefiner#479 A (owner 11/11). Internal, the order already locked by the caller and out of LOCKED: its ONLINE obligations still OPEN are cancelled and their CREATED / PENDING attempts FAILED (result ORDER_STOPPED); never a capture (the provider lane releases a hold of a FAILED attempt). Returns the attempts failed.
recurring_try_lock_obligationsp_order uuidbooleandefinerPAF-P1-22 (finding 6). Locks every payment obligation of the order, ordered by id, NOWAIT (fulfillment.lock_unit_payments): true when held, false when a payment transaction holds one (the caller refuses or skips; it never waits). Internal.
redeem_adjusted_backp_redeem uuidbooleandefiner#479 T7. True when ACCEPTED CREDIT ADJUSTs of APPROVED adjustments compensating this REDEEM (FU-1822 link: corrects_request_id or reconciliation item) returned all of its points. Internal.
refund_branch_recordp_branch uuid, p_expected_version integer, p_to text, p_refund_transaction uuid, p_reverse_request uuid, p_result_code text, p_source_id textjsonbdefiner
refund_case_jsonp_case uuidjsonbdefiner
refund_cash_by_opsp_case uuidbooleandefinerU19-P2-15. True when the cash of the case is refunded by Operations (order refund, DH-US-07): the job runs its Pi-Point legs only.
refund_cash_settledp_case uuidbooleandefinerU19-P2-15. True when the Operations confirm settled the cash of the case (its cash legs are not executed).
refund_changesp_case uuid, p_after_version integerjsonbdefiner
refund_evidence_okp_media uuid[], p_max integerbooleandefiner
refund_exec_job_name—text
refund_exec_loadp_case uuidjsonbdefiner
refund_exec_recordp_branch uuid, p_provider_txn text, p_amount bigint, p_payload_hash bytea, p_source_id text, p_correlation_id textuuiddefinerP3-11. Records the SUCCEEDED provider REFUND of one CASH leg (idempotent) and walks the intent to REFUNDED when every SUCCEEDED capture is refunded; the leg becomes ACCEPTED through payment.refund_branch_record.
refund_mask_namep_value texttext
refund_mask_tailp_value texttext
refund_name_keyp_value texttextU19-P2-14. Accent-, case- and blank-insensitive key of a person name (holder name vs name on the CCCD).
refund_open_automaticp_order uuid, p_origin text, p_request_key text, p_rule_versions text[], p_source_type text, p_source_id textjsonbdefiner
refund_open_casep_order uuid, p_origin text, p_request_key text, p_rule_versions text[], p_requested_by uuid, p_reason text, p_evidence uuid[], p_source_type text, p_source_id textjsonbdefinerP3-10 + FU-575 + U19-P2-17 + U19-R23 + U28-P2-11 + PAF-P1-23. FULL_ORDER case of a cancelled order; only MANUAL waits for a checker (D-SEC-01); a shortage or manual case refunds shortage.cancel_refund_figures (kept, skipped and forfeited Recurring cycles refund nothing; minus the cọc dư cases), a capped one draws its deposit share on the DEPOSIT captures and its collected part on the REMAINING captures; the other origins every refundable capture minus the cases funded from the captures (payment.overpayment_cases_captured, PAF-P1-25).
refund_open_forfeitp_review uuid, p_source_id textjsonbdefinerFU-FORFEIT, PAF-P1-23. Internal: opens the PARTIAL refund case (origin FORFEIT) of an approved cycle forfeit, idempotent by the key forfeit:<review id>; DEFERRED while an original is unresolved or the remainder cannot cover the stored share. Legs per obligation kind: the cycle's deposit share on the DEPOSIT captures, the rest on the online REMAINING captures.
refund_open_partialp_case uuid, p_order uuid, p_request_key text, p_source_type text, p_source_id textjsonbdefinerFU-575. pi_api + pi_worker: opens the PARTIAL_UNITS refund case of one partial shortage row (stored cash and points share); idempotent by key; DEFERRED while an original is unresolved; legs are at most the remainder of their original.
refund_open_remaining_excessp_case uuid, p_order uuid, p_request_key text, p_source_type text, p_source_id textjsonbdefinerFU-SHORTAGE2. pi_api + pi_worker: opens the REMAINING_EXCESS refund case of the excess of a settled online REMAINING; idempotent by key; DEFERRED while an original is unresolved; legs are at most the remainder of a REMAINING capture.
refund_ops_confirmp_order uuid, p_case uuid, p_expected_version integer, p_code text, p_transferred_on date, p_note text, p_source_id textjsonbdefinerU19-P2-15 DH-US-07 AC04. Operations confirms the manual refund transfer (one step, D-SEC-01): payment -> REFUNDED, or PARTIALLY_REFUNDED when the order keeps a cycle that is not cancelled (#479 B3).
refund_ops_lockp_order uuid, p_case uuid, p_expected_version integerrefund_casesdefiner
refund_ops_request_updatep_order uuid, p_case uuid, p_expected_version integer, p_reason text, p_customer_note text, p_source_id text, p_reason_code text, p_note_visible booleanjsonbdefinerU19-P2-15 DH-US-16; G2I-P1-03 O6a. Operations asks the customer to send the refund request again with a reason code and a note the customer reads only when marked visible: payment -> WAITING_REFUND_REQUEST.
refund_profile_jsonp refund_receiver_profilesjsonb
refund_reader_roles—text[]
refund_record_viewp_cases uuid[]jsonbdefiner
refund_recover_roles—text[]
refund_retry_branchp_branch uuid, p_expected_version integer, p_reason text, p_evidence uuid[], p_source_id textjsonbdefiner
refund_submit_excess_requestp_order uuid, p_case uuid, p_expected_revision integer, p_name text, p_citizen_enc bytea, p_citizen_last4 text, p_bank text, p_account_enc bytea, p_account_last4 text, p_holder text, p_key_id text, p_source_id textjsonbdefiner#479 C. The customer's refund request (receiver profile, sealed CCCD / account) of one excess claim of an OWN order, while it waits for a request (first time or sent back); the order's payment axis is not moved.
refund_submit_requestp_order uuid, p_expected_revision integer, p_name text, p_citizen_enc bytea, p_citizen_last4 text, p_bank text, p_account_enc bytea, p_account_last4 text, p_holder text, p_key_id text, p_source_id textjsonbdefinerU19-P2-14. The customer sends / sends again the refund request of an own order (WAITING_REFUND_REQUEST -> WAITING_REFUND), a new append-only revision with the sealed CCCD and account number. Idempotent by command source.
refund_transfer_jsont refund_transfer_recordsjsonb
refund_unresolvedp_order uuidtextdefiner
refundable_cashp_capture uuid, p_exclude_case uuidbigintdefiner
refundable_pointsp_redeem uuid, p_exclude_case uuidintegerdefiner
remaining_effectivep_obligation uuidbigintdefinerFU-SHORTAGE2. The REMAINING amount in force: the latest recalculation, else the obligation amount.
remaining_method_ofp_order uuidtextdefinerU19-P2-22, U28-P2-03, PAF-P1-09. Remaining payment method: a live online remaining chosen ONLINE (Mua định kỳ: locked cycles keep their COD, DEC-U28-04; Mua chung: its COD was cancelled by the switch), else a live COD remaining, else the choice row, else an opened REMAINING, else COD after the close, else NOT_CHOSEN (B013.R11).
remaining_recalculatep_case uuid, p_order uuid, p_source_type text, p_source_id textjsonbdefinerFU-SHORTAGE2. DEC-CP-SHORTAGE-FOLLOWUP (2): lowers an OPEN REMAINING obligation (online or COD) to remaining quantity x final price - deposit kept - points kept, records the excess of a settled one; idempotent by case + order; DEFERS on a live intent.
remaining_switchp_order uuidjsonbdefinerU28-P2-03 (DEC-U28-04), PAF-P1-09, PAF-P1-03, PAF-P1-22, PAF-P1-25. COD -> ONLINE switch of the remaining after the close. Mua định kỳ: availability, the reason when blocked, payment.recurring_remaining_target (⌈Σ due of the cycles kept⌉ to 1,000đ - Σ COD of the locked cycles; a skipped, CANCELLED or FORFEITED cycle is not kept; also the amount of an unpaid OPEN remaining of a followed order with no attempt in flight, finding C), locked / open cycles, the prepay bonus and the OPEN online remaining. Mua chung: payment.group_remaining_switch. Null before the close.
remaining_targetp_case uuid, p_order uuidbigintdefinerFU-SHORTAGE2. DEC-CP-SHORTAGE-FOLLOWUP (2): remaining quantity x final unit price - deposit kept - points kept (may be <= 0).
return_kept_amountsp_order uuid, p_cycle_id uuid, OUT cash_vnd bigint, OUT points integerrecorddefiner#479 B. Cash and Pi-Point a returned unit paid (Mua chung order: captures + COD + REDEEM; Mua định kỳ cycle: deposit share + its own captures + COD, points share of the close). Stored rows only.
reward_milestonep_order uuid, p_cycle integerbooleandefinerU19-P2-20, #479 A. The paid milestone: the whole order, or the first ACTUAL Recurring cycle (every earlier cycle skipped or settled as a failed delivery).
session_corep_system boolean, p_request_id text, p_pay_url text, p_deeplink text, p_qr_data text, p_expires_at timestamp with time zonebooleandefiner#479 T5. Records once the session of a PENDING intent (invalid parts dropped; false when nothing is kept or a session is already stored). Internal: called by payment.buyer_record_session / payment.system_record_session.
staff_order_allocationsp_order uuidTABLE(allocation_id uuid, transaction_id uuid, obligation_id uuid, amount_vnd bigint, created_at timestamptz, provider_ref_tail text)definerFU-AC-TRIAGE L5 GAP-187. Finance (F-01) read of the SYSTEM_ONLY allocations of an order; provider reference as last 4 characters.
staff_order_periodsp_order uuidTABLE(order_id uuid, cycle_no integer, delivers_from timestamptz, delivers_to timestamp with time zone, obligation_vnd bigint, paid_vnd bigint, remaining_vnd bigint)definerFU-AC-TRIAGE L5 A-OD-02 AC02. Finance (F-01 payment.read) periods of one order with obligation / paid / remaining.
staff_order_tendersp_order uuidTABLE(obligation_id uuid, kind text, method text, status text, amount_vnd bigint, points integer, order_cycle_id uuid, cycle_no integer, created_at timestamptz, settled_at timestamp with time zone, paid_vnd bigint, refunded_vnd bigint, attempt_id uuid, attempt_status text, cod_status text, point_request_id uuid, point_request_status text)definerFU-AC-TRIAGE L5 PAY-R1-01 HC01 / C-PAY-01 AC03. Finance (F-01) read of every tender of an order with paid and refunded VND.
system_cancel_depositp_id uuidpayment.checkout_statedefiner
system_cancel_pointsp_id uuidpayment.checkout_statedefiner
system_checkoutp_id uuidpayment.checkout_statedefiner
system_checkout_movep_id uuid, p_expected_version integer, p_to text, p_reason text, p_reverse_date datepayment.checkout_statedefiner
system_checkout_of_cashp_cash_request_id textuuiddefiner#479 T14. pi_worker: the deposit checkout whose cash leg is this provider request id (null when none). Read only.
system_checkout_tenderp_id uuidpayment.checkout_tenderdefiner
system_claim_hold_releasep_request_id text, p_holder uuid, p_seconds integerbooleandefiner#479 two-step. pi_worker: for a FAILED intent with an open provider hold and no ended release, takes its CAPTURE lease (released with payment.system_release_intent_lease) and opens its payment_hold_releases row. False when the hold is not open, the release ended, or another holder has a live lease. Lock order order -> obligation -> intent.
system_claim_intent_leasep_request_id text, p_purpose text, p_holder uuid, p_seconds integerbooleandefiner#479 T4. pi_worker: payment.lease_core.
system_close_capped_intentsp_campaign_id uuid, p_wait_minutes integer, p_limit integerTABLE(request_id text, intent_status text, checkout_id uuid)definer#479 item 2. pi_worker (the close jobs): once now() >= closes_at + p_wait_minutes of a CLOSING campaign, its DEPOSIT attempts the close no longer waits for (CREATED / PENDING started before closes_at, every UNKNOWN) of unpaid DEPOSIT_PENDING orders, oldest first, with the owning deposit checkout. Empty before the cap. Read only.
system_expiry_due_intentsp_limit integerTABLE(request_id text, order_id uuid, intent_status text)definer#479 T2. pi_worker: the CREATED / PENDING DEPOSIT intents of the (at most p_limit) orders the next payment.expire_unpaid_orders batch would cancel, so the expiry job can ask the provider first.
system_holds_to_releasep_now timestamp with time zone, p_stale_before timestamp with time zone, p_not_before timestamp with time zone, p_limit integerTABLE(request_id text, attempts integer, last_attempt_at timestamptz)definer#479 two-step. pi_worker (job payment.intent_recover): FAILED intents whose provider hold is open, never tried and failed inside the sweep window, or RELEASING and due at p_now; never tried first. Request id and attempts only.
system_intentp_request_id textTABLE(intent_id uuid, request_id text, intent_version integer, intent_status text, provider text, provider_mode text, amount_vnd bigint, payload_hash text, obligation_id uuid, obligation_kind text, obligation_status text, order_id uuid, order_version integer, order_state text, policy_version_id uuid)definerP3-02. pi_worker read of one intent by provider request id (callback binding, recovery).
system_note_hold_releasep_request_id text, p_result text, p_at timestamp with time zone, p_next_at timestamp with time zone, p_max_attempts integertextdefiner#479 two-step. pi_worker: one release attempt of the intent's hold (attempts + 1). RELEASED or CAPTURED ends it; after p_max_attempts other results it is GAVE_UP (Finance attention); otherwise due again at p_next_at.
system_note_intent_checkp_request_id text, p_checked_at timestamp with time zone, p_next_check_at timestamp with time zoneintegerdefiner#479 T8. pi_worker: the sweep checked this intent (attempts + 1) and may check it again from p_next_check_at.
system_observep_request_id text, p_provider text, p_mode text, p_event_id text, p_event_type text, p_status text, p_txn_id text, p_amount_vnd bigint, p_payload_hash bytea, p_occurred_at timestamp with time zone, p_correlation_id textpayment.intent_changedefinerP3-02. pi_worker: verified callback / status lookup -> payment.observe_core (system).
system_open_cash_intentp_id uuid, p_provider text, p_mode text, p_payload_hash bytea, p_correlation_id textpayment.intent_changedefinerP3-04. pi_worker: the one cash intent of a checkout in its cash stage (request id fixed at insert).
system_place_zero_depositp_id uuidTABLE(outcome text, order_id uuid, obligation_id uuid, order_prior_version integer, order_version integer, order_state text, policy_version_id uuid)definerU19-R13 (GAP-W-DH-13 owner 20/10: allowed — needs re-checking). pi_worker: a 0 VND deposit checkout in its cash stage settles the DEPOSIT obligation with no intent and places the order (INITIATED + DEPOSIT_PAID).
system_record_attemptp_request_id text, p_to text, p_session_ref text, p_result_code text, p_source text, p_source_id textpayment.intent_changedefiner
system_record_sessionp_request_id text, p_pay_url text, p_deeplink text, p_qr_data text, p_expires_at timestamp with time zonebooleandefiner#479 T5. pi_worker: records the session of a PENDING intent (payment.session_core).
system_recoverable_intentsp_now timestamp with time zone, p_stale_before timestamp with time zone, p_not_before timestamp with time zone, p_limit integerTABLE(request_id text, intent_status text, status_changed_at timestamptz, check_attempts integer, last_checked_at timestamp with time zone)definerFU-DEF201 GAP-201 / #479. pi_worker: open payment intents (CREATED / PENDING / UNKNOWN) inside a stale window whose backoff is over at p_now; never checked first, then least recently checked, then UNKNOWN and CREATED before PENDING, oldest first. Request id, status, change time and the check bookkeeping only.
system_release_intent_leasep_request_id text, p_purpose text, p_holder uuidbooleandefiner#479 T4. pi_worker: payment.lease_release_core.
system_reverse_pointsp_id uuidpayment.checkout_statedefiner#377. pi_worker: the PI_POINT tender settled by this checkout -> REVERSED once its REVERSE_REDEEM is ACCEPTED.
system_settle_pointsp_id uuidpayment.checkout_statedefiner
unapplied_capturesp_reason text, p_state text, p_limit integer, p_intent uuidTABLE(transaction_id uuid, intent_id uuid, order_id uuid, obligation_id uuid, obligation_kind text, provider text, provider_mode text, provider_txn_id text, amount_vnd bigint, applied_vnd bigint, unapplied_vnd bigint, recorded_at timestamptz, provider_recorded_at timestamp with time zone, reason text, state text, intent_status text, order_state text, total_count bigint, total_unapplied_vnd numeric, order_code text)definerFU-DEF149 GAP-149. Finance (PRC-01 reconcile.read) queue of captured money not applied to an obligation: derived reason and state, read only; no resolution exists (G-FIN open, GAP-1620). #479: + order_code, optional p_intent (the captures of one attempt).
voucher_approval_contextp_voucher_id uuidTABLE(maker_id uuid, status text, payload_hash bytea)definer
voucher_approvep_voucher_id uuid, p_expected_version integer, p_payload_hash text, p_correlation_id correlation_refSETOF vouchersdefinerP3-09. Checker approves SUBMITTED -> APPROVED (immutable) and posts one cashbook entry. Never the maker/editor.
voucher_cancelp_voucher_id uuid, p_expected_version integer, p_correlation_id correlation_refSETOF vouchersdefiner
voucher_checker_roles—text[]
voucher_drafter_roles—text[]
voucher_evidence_problemp_ids uuid[]text
voucher_maker_roles—text[]
voucher_payload_hashp_kind text, p_fund text, p_amount bigint, p_reason text, p_order uuid, p_txn uuid, p_original uuid, p_evidence uuid[], p_policy uuidbytea
voucher_reader_roles—text[]
voucher_refusep_code text, p_reason text, p_detail textvoid
voucher_rejectp_voucher_id uuid, p_expected_version integer, p_reason text, p_correlation_id correlation_refSETOF vouchersdefinerFU-713. Checker sends a SUBMITTED voucher back to DRAFT with a reason (VCH-04). Never the maker/editor/submitter.
voucher_rejections_immutable—trigger
voucher_save_draftp_voucher_id uuid, p_expected_version integer, p_kind text, p_fund_code text, p_amount_vnd bigint, p_reason text, p_order_id uuid, p_transaction_id uuid, p_original_voucher_id uuid, p_evidence uuid[], p_correlation_id correlation_refSETOF vouchersdefiner
voucher_submitp_voucher_id uuid, p_expected_version integer, p_correlation_id correlation_refSETOF vouchersdefiner
vouchers_fund_registered—triggerdefiner
vouchers_guard_update—trigger
vouchers_no_delete—trigger

schema campaign ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
activate_cycle_skipp_basket_id uuid, p_cycle_no integer, p_request_id textvoiddefinerP2-09. Owner-only skip activation gate: policy_undecided DEC-CP-SKIP; records nothing (P2-18 owns recording).
actor_can_manage—booleanP2-06, CV3-P4-16 (DEC-CV3-32). Acting principal holds deal.manage (O-03) at ALL in WEB_ADMIN right now (rbac.actor_grants()). The campaign WRITE predicate; reads use campaign.actor_can_read().
actor_can_read—booleanCV3-P4-16 (DEC-CV3-32). Acting principal holds deal.read (OPS-01) or deal.manage (O-03) at ALL in WEB_ADMIN right now (rbac.actor_grants()). The campaign READ predicate.
actor_holds_deal_manage—booleanCV3-P4-03 (DEC-CV3-28). Internal: acting principal holds deal.manage (O-03) at ALL in WEB_ADMIN right now (rbac.actor_grants()).
actor_is_buyer—booleanP2-09. Matrix U-01/U-02 mirror: APP_USER caller, ACTIVE account + membership, role user.
actual_price_splitp_total bigint, p_qty bigintTABLE(unit_price_vnd bigint, ceil_units bigint)G1S-P1-02 (BR-APP-08, GAP-G1S-06). Giá thực tế of qty units summing to total: unit = ceil(total / qty), the first k = total - qty x (unit - 1) units carry unit, the others unit - 1 (k = qty when it divides); total 0 -> 0, k = qty.
apply_recurring_close_obligationsp_campaign_id uuid, p_outcome_id uuidTABLE(status text, locked_orders integer, cycles integer, obligations integer, excess_orders integer, cancelled_orders integer, orders jsonb)definerFU-F3, U19-P2-07, G2I-P2-02, U28-P2-01, U28-P2-02, U28-P1-07. pi_worker, in the close transaction after the final prices: cancels an order whose products all failed (refund intent row), locks the others with their cycles, allocates on the actual price (campaign.recurring_allocate_actual: Pi-Point by value, deposit last -> first on V_c, COD ⌈due⌉ to 1,000đ balanced on the last cycle still to collect, a negative balance carried back, DEC-U28-12), opens the ONLINE remaining ⌈Σ due⌉ / the offline cash surplus case, records the excess Pi-Point refund, marks the deposit-covered cycles paid; lists the cycles left empty by the MOQ (not a skip, DEC-U28-03); idempotent.
apply_recurring_final_pricesp_campaign_id uuid, p_outcome_id uuidTABLE(status text, applied_orders integer, applied_rows integer)definerFU-AC-TRIAGE L7 UA-14 AC01, U19-P2-07, G2I-P2-02. pi_worker: writes the final unit price of each product that met its MOQ for every (cycle, line) with goods of every counted order (quantity of that cycle, ordering.cycle_lines), in the close transaction; idempotent; a failed product line or a cycle at 0 gets no price; a FAILED outcome writes nothing.
as01_version—text
as02_version—text
assert_basket_openp_campaign_id uuid, p_term integeruuiddefinerP2-09 / U19-P2-37 / G2S-P1-03. Raises unless the Recurring campaign is OPEN inside its window; a term (null = no package chosen yet) must be a package of the campaign with cycles 1..term scheduled. Returns its policy version.
assert_config_writablep_campaign_id uuidtextdefinerU19-P1-01. Locks the campaign row FOR SHARE and raises campaign_locked unless DRAFT/PENDING_PUBLISH/UPCOMING; returns the state (NULL when the campaign is gone: cascade delete).
assert_owner_bypasses_rls—void
assert_readyp_campaign_id uuidvoiddefinerU19-P2-01 / U28-P1-04 / CV3-P1-01 / CV3-P4-07. Leaving DRAFT: window/policy/products complete, deposit > 0 % (DEC-U28-11), MOQ >= 1, listed prices > 0, daily virtual cap >= daily, named and dated milestones (Đến >= Từ) with a reward (MC); ĐK: start month, minimum order value, window 1 and every window complete, Đến >= Từ, no overlap (delivery_window_order / delivery_window_overlap), package 1 and every package with Số kỳ, reward and skip, Số kỳ unique (term_duplicate), skip < Số kỳ (package_skip), term_options = package terms, schedule 1..max(Số kỳ); per product On sale and 1-3 complete tiers from >= 1, thresholds up, prices down and > 0, Mốc 1 below the listed price; MOQ >= the Mốc 1 threshold (#324, moq_below_tier1:<position>:<threshold>); in the PERCENT_ORDER unit every milestone / package reward, Thanh toán ngay and trả trước bonus <= 10000 bp (CV3-P4-07: reward_over_percent, pay_now_bonus_over_percent, prepay_bonus_over_percent).
assert_transitionp_campaign_id uuid, p_type text, p_from text, p_to text, p_opens_at timestamp with time zone, p_closes_at timestamp with time zonevoiddefinerU19-P1-01. Readiness/policy gates when a campaign leaves DRAFT (create) or CLOSING (outcome).
basket_snapshotp_basket_id uuidjsonbdefinerP2-09. Owner-only basket preview data (lines, policy items; tiers + schedule while the campaign is ACTIVE).
campaign_participant_countp_campaign_id uuid, p_at timestamp with time zone, p_joining uuidbigintDEC-OWN30-S1-ORDINAL. Participants of one campaign / Mua định kỳ basket at p_at: Σ virtual units of its products + distinct buyers of committed orders (+ p_joining, the buyer being confirmed). participant_counts.total and the Recurring "Người thứ n" both read it. Owner-side only.
campaign_system_columns—text[]U19-P1-01. public.campaigns columns that are not configuration; every other column locks from OPEN (B006.R12).
campaigns_spin_wheel_choice—triggerdefinerCV3-P1-08 + VQM-P1-01 BR-VQ-03 / BR-VQ-05 / DEC-VQM-14. A campaign choosing a wheel (insert, or update to another wheel) must choose an ACTIVE, non-legacy one (campaigns_spin_wheel_inactive, also for an unknown id; DETAIL has status and legacy) and marks spin.wheels.ever_chosen_at (first time only). The wheel already chosen is kept when resent, INACTIVE or legacy included; null (Không áp dụng) always passes. Every state, DRAFT included.
cancel_cycle_skipp_skip uuid, p_expected_version integer, p_source_id textjsonbdefinerP2-18, U28-P2-04 (DEC-U28-02). Buyer: kept for old App builds; an own skip request is never withdrawn (recurring_skip_irreversible, nothing written); an unknown or foreign one is recurring_skip_not_found.
cancel_job_runp_run_id uuid, p_version integerbooleandefinerU19-P2-05. Settles one PENDING run as cancelled (PENDING -> LEASED -> SUCCEEDED, code cancelled).
close_allocatep_deposit bigint, p_points_value bigint, p_points integer, p_values bigint[]TABLE(cycle_no integer, value_vnd bigint, cash_vnd bigint, points_value_vnd bigint, points integer, owed_vnd bigint)FU-F3. Pure: the deposit + points pool is consumed from the LAST cycle backwards over the final cycle values (cumulative proportional cash / points split, exact over all cycles); owed = value - share.
close_awaits_paymentp_campaign_id uuidbooleandefinerPAF-P1-19 (DEC-PAF-18). pi_worker: true when every unpaid order holding a parked close has a deposit attempt that will end by itself (live or UNKNOWN DEPOSIT intent, running deposit checkout): the close job settles and is re-armed by the payment result. False = an order held by something no payment event moves (UNKNOWN park, replay).
close_job_name—textU19-P2-05. Job name of the close run (slot campaign:<id>:close:v<n>); was campaign.group_close (P2-07).
close_payment_waitp_campaign_id uuid, p_wait_minutes integerjsonbdefiner#479 T6 / item 2. pi_api, campaign readers (campaign.actor_can_read(); null otherwise): while the campaign is CLOSING, the unpaid orders holding its close (pendingOrders), those with a deposit attempt the close waits for (live and started before closes_at, or UNKNOWN: waitingOrders) and closes_at + p_wait_minutes (waitUntil, null without waiting orders or a cap). Null when the campaign is not CLOSING or nothing is pending.
close_registrationp_campaign_id uuid, p_run_id uuidTABLE(outcome text, campaign_type text, version integer, policy_version_id uuid, opens_at timestamptz, closes_at timestamp with time zone)definerU19-P2-05 (was P2-07). Close write: OPEN -> CLOSING (WORKER, reason expired) once closes_at has passed.
config_writable_states—text[]U19-P1-01. States whose configuration and children may change: DRAFT, PENDING_PUBLISH, UPCOMING (B006.R04).
creator_accounts—TABLE(account_id uuid, display_name text)definerU19-P2-03 B036.R06 / CV3-P4-06 DEC-CV3-26. Người tạo filter: ACTIVE WEB_ADMIN accounts holding a live deal.manage ALL grant, plus every distinct campaigns.created_by (any status, any role now); id + profiles.full_name, by name. For campaign readers (campaign.actor_can_manage() or a live deal.read ALL grant); definer, fails closed if the owner is not RLS-exempt.
current_policy_versionp_campaign_id uuiduuid
cycle_reminder_factsp_order uuid, p_cycle_no integerjsonbdefinerP2-18, G2I-P2-02, G2I-P6-01. pi_worker read: whether a cycle reminder event may be emitted for a period (DUE / SKIPPED: payment.cycle_skipped, a press or a cycle without goods / SHIPPED / PAST / NOT_ACTIVE / NOT_FOUND) and the VN dates of the order's own window. No delivery, no schedule (G-NOT).
deal_participant_countp_campaign_product_id uuid, p_at timestamp with time zone, p_joining uuidbigintDEC-OWN30-S1-ORDINAL. Participants of one Mua chung Deal at p_at: virtual units + distinct buyers of committed orders (+ p_joining, the buyer being confirmed). Deal participantCount and "Người thứ n" both read it. Owner-side only.
decide_cycle_forfeitp_review uuid, p_expected_version integer, p_decision text, p_payload_hash text, p_note text, p_correlation_id correlation_refjsonbdefinerFU-FORFEIT. Operations checker (never the maker) approves or rejects a PROPOSED forfeit review. APPROVE also forfeits that cycle only, stores its refund share and opens the PARTIAL refund case (key forfeit:<id>), all or nothing.
deposit_confirmed_latep_order_id uuid, p_closes_at timestamp with time zonebooleandefinerPAF-P1-01 (BR-APP-06, DEC-PAF-07). True when the order was PLACED at/after closes_at by no deposit attempt created before closes_at (no SUCCEEDED deposit intent, nor 0 VND COMPLETED checkout, created earlier): the close parks it as LATE_CONFIRMATION. A deposit started before closes_at and confirmed later is counted.
discard_recurring_drafts—triggerdefinerG2S-P1-03 (BR-MD-05). A Mua định kỳ campaign leaving OPEN discards its DRAFT baskets with closed_notice_at; myRecurringBasket returns each one once with closedNotice true.
display_statusp_state text, p_opens_at timestamp with time zone, p_closes_at timestamp with time zonetextU19-P1-01. Admin status = state; internal CLOSING shows as OPEN (GAP-W-CD-10 resolved by B006.R03).
finalize_group_outcomep_campaign_id uuid, p_expected_version integer, p_run_id uuidTABLE(status text, campaign_type text, version integer, policy_version_id uuid, outcome_id uuid, detail jsonb, orders jsonb, expired jsonb)definerP2-15, U19-P2-06, G1S-P1-02, PAF-P1-01. Group close per product: unpaid orders cancelled first (P2-19), virtual frozen, total = real + virtual vs MOQ; met products LOCK (final price, Giá thực tế split, remaining rounded up to 1,000đ, excess Pi-Point), missed products CANCEL (full refund intent); CLOSING -> SUCCESS | PARTIAL_SUCCESS | FAILED. A deposit started before closes_at and confirmed later is counted (BR-APP-06). Parks (CLOSING kept) on payments in flight, a confirmation of a deposit started after closes_at, inconsistency, no tier.
find_overlapp_type text, p_opens timestamp with time zone, p_closes timestamp with time zone, p_exclude uuidTABLE(id uuid, code text, opens_at timestamptz, closes_at timestamp with time zone)U19-P1-02 B006.R18 / GAP-W-CD-02. Counted campaigns of p_type whose [opens, closes) overlaps the given window (touching is not overlapping), earliest first; p_exclude = the campaign being edited.
fixed_initialsp_seed texttext
forfeit_approval_contextp_review uuidTABLE(maker_id uuid, status text, payload_hash bytea)definer
forfeit_cycle_event_refp_review uuidTABLE(order_cycle_id uuid, cycle_version integer, policy_version_id uuid)definerFU-AC-TRIAGE L7 A-OPS-03 HC02. Operations only: the forfeited cycle id, its version and the order policy version of an APPROVED review, for the order_cycle.forfeited event the decision command emits.
forfeit_cycle_sharep_order uuid, p_cycle_no integerTABLE(cash_vnd bigint, points integer)definerFU-FORFEIT + FU-F3 + U19-R10, PAF-P1-21 (DEC-PAF-22), PAF-P1-22 (DEC-PAF-25). Cash and points refunded for one forfeited cycle: the deposit cash of the current allocation (payment.recurring_cycle_alloc: after a skip the deposit spread again) and the points of the close (order_cycle_close_values) or, without close values, the order-time pool from the last cycle backwards; plus the exact cumulative share of the online REMAINING capture weighted by the current due (or due), adding up to the capture less the SKIP cases of what it paid above the due (skip-remaining:, refunded by their DU code).
forfeit_effect_version—text
forfeit_jsonr recurring_forfeit_reviewsjsonbdefiner
forfeit_payload_hashp_order uuid, p_cycle_no integer, p_reason textbytea
forfeit_pool_splitp_deposit bigint, p_points_value bigint, p_points integer, p_value bigint, p_cycles integer, p_cycle_no integerTABLE(cash_vnd bigint, points integer)
forfeit_refusep_constraint text, p_message text, p_detail textvoid
forfeit_roles—text[]
form_product_factsp_ids uuid[]TABLE(id uuid, name text, product_type text)definerCV3-P4-16 (DEC-CV3-32). Id, name and type of the products a campaign form names (<= 5000), for deal.manage holders (no catalog.read needed); empty otherwise.
group_close_resultsp_campaign_id uuid, p_policy_version_id uuidjsonbdefinerU19-P2-06. Per-product close computation (BR-C-04/05/06): real + virtual at closes_at vs MOQ, final tier = highest threshold <= total. committed_qty = total (campaign_outcomes.product_results shape). Owner-side only.
group_overview_factsp_campaign_id uuidjsonbdefinerU19-P2-08 / U28-P1-09, CV3-P1-02, CV3-P4-04, CV3-P4-19. Order facts of the Admin Mua chung overview (BR-CT-05..08): live real/virtual/total per product and deposited orders per product x milestone (+ configured % reward floored per order at the rate of its ISSUE, else the order rate snapshot; issued reward net of close cancels; reward already Available), or the close snapshot once closed. Aggregates only. Read by deal.read / deal.manage (CV3-P4-16).
import_sku_lookupp_skus text[]TABLE(input text, key text, id uuid, sku text, name text, product_type text, status text, unit text, brand_name text, category_path text[], image jsonb)definerCV3-P4-03 (DEC-CV3-28, BR-IM-01). Campaign import SKU lookup for deal.manage holders (no catalog.read needed): per distinct cell its catalog key and the live product with that key, or nulls. At most 1000 cells.
list_expected_deliveryp_campaign_id uuidTABLE(delivers_from date, delivers_to date, windows jsonb, start_month date)U19-P2-03 B016.R10 / CV3-P1-11 BR-DS-09. Expected delivery of one campaign: Group Buy first milestone from -> last milestone to; Recurring first day of the complete windows (Đến >= Từ) in Kỳ bắt đầu giao -> their last day in the month of the longest package, those windows, the start month; legacy: typed cycles. Invoker (RLS).
lock_campaign_productp_product_id uuidtextdefinerCV3-P1-01. Product of a DRAFT row (BR-TC-07: not checked On sale): locks a live product FOR SHARE, returns its type; raises campaign_products_product_on_sale when it does not exist or was deleted.
lock_on_sale_productp_product_id uuidtextdefinerP2-06. Locks (FOR SHARE) a live ON_SALE product and returns its type; raises otherwise.
manager_roles—text[]P2-06 / FU-OPSGRANTS role mirror of matrix O-03 / OPS-01 (operations, admin). Since CV3-P4-16 no access predicate reads it: campaign access follows the deal.read / deal.manage grants.
name_initialsp_name texttext
next_codep_at timestamp with time zonetextdefinerPAF-P1-17 BR-C-13 (Product 02/11; was U19-P1-02 global counter). CD + ddmmyyyy (Vietnam date of p_at) + 4-digit number of that day (campaign.next_daily_code scope campaign, from 0001 each day); campaign_code_exhausted past 9999 in a day. Column default of campaigns.code and trigger campaigns_code only.
next_daily_codep_scope text, p_prefix text, p_width integer, p_at timestamp with time zonetextdefinerPAF-P1-17 BR-C-13. Next code of a per-day counter: prefix || ddmmyyyy (Asia/Ho_Chi_Minh date of p_at) || the day's next number on p_width digits, from 1 every day; the (scope, day) row stays locked until the caller commits. daily_code_exhausted past 10^width - 1. Owner only: call it from SECURITY DEFINER functions and triggers.
open_job_name—textU19-P2-05. Job name of the open run (slot campaign:<id>:open:v<n>).
order_forfeit_reviewsp_order uuidSETOF jsonbdefiner
order_skip_statep_order uuid, p_lock booleanjsonbdefinerP2-18, G2I-P1-01 D14, G2I-P2-02 G6-Q2, G2I-P6-01 D2/D11, U28-P2-04 DEC-U28-02/03, #479 A. Buyer: the skip facts of an OWN Recurring order (policy, lock rule with skipLeadDays = x_eff or null, skipsUsed = presses + cycles left empty, failedDeliveryCount = cycles settled as failed deliveries (counted with the skips against n), per cycle the order's own window (VN dates), the money of ordering.cycle_money, the lock, the active skip, the shipment, empty, emptyAfterMoq (null before the close), failedDelivery and the quantities of the cycle); optionally under the order row lock.
outcome_job_name—textP2-15. Job name of the Group close outcome run (slot campaign:<id>:v<CLOSING version>).
outcome_results_okp_outcome text, p_results jsonbbooleanU19-P1-01. Shape of campaign_outcomes.product_results: SUCCESS all met, FAILED none, PARTIAL_SUCCESS some.
overlap_pairs—TABLE(campaign_type text, first_id uuid, first_code text, second_id uuid, second_code text)U19-P1-02. Existing overlapping counted pairs (legacy data written before the rule); owner only, for U19-P1-06.
overlap_states—text[]U19-P1-02 B006.R18. States that hold the one open slot per type: Chờ công bố, Sắp mở, Đang mở (+ internal CLOSING).
overview_order_rewardp_unit text, p_value integer, p_v0 bigint, p_rate numeric, p_order_id uuidTABLE(cfg bigint, released bigint)definerU28-P1-09. Internal: configured % milestone reward of one order (floor per order) and its points already Available.
overview_released_pointsp_order_ids uuid[]TABLE(order_id uuid, released bigint)CV3-P1-02. Internal: per order of the set, Σ ORDER_PENDING reward points already Available (U28-P1-09 rule).
overview_reward_cfgp_unit text, p_value integer, p_v0 bigint, p_rate numericbigintCV3-P1-02. Internal: configured % milestone reward of one order, floor per order (U28-P1-09 rule).
package_snapshot—triggerdefinerU19-P1-05. Baskets/orders: skip_max and package_reward_value are copied from campaign_term_packages on package_no.
participant_countsp_campaign_id uuid, p_at timestamp with time zoneTABLE(total bigint, today bigint)G2I-P1-02 (D5) + #395 + DEC-OWN30-S1-ORDINAL. total = campaign.campaign_participant_count (distinct buyers of committed orders + virtual units of the campaign products); today = those confirmed / virtual units added since 00:00 Asia/Ho_Chi_Minh of p_at. Owner-side only (the definer public reads).
picker_brandsp_search text, p_limit integer, p_offset integerjsonbdefinerCV3-P4-16 (DEC-CV3-32). Thương hiệu list of the "Thêm sản phẩm" picker: live brands by name keyword, Tên A→Z; {total, items[{id, code, name}]}; null without deal.manage (no catalog.read needed).
picker_categories—TABLE(id uuid, parent_id uuid, name text, level integer, is_leaf boolean)definerCV3-P4-16 (DEC-CV3-32). Ngành hàng list of the "Thêm sản phẩm" picker: every live category (id, parent, name, level, leaf) in tree order, for deal.manage holders (no catalog.read needed); empty otherwise.
picker_product_factsp_ids uuid[]TABLE(id uuid, sku text, name text, product_type text, status text, unit text, brand_name text, category_path text[], image jsonb)CV3-P4-03 (DEC-CV3-28). Internal: picker / import facts of live products (id, SKU, name, type, status, unit, brand, category path root first, primary picture).
picker_productsp_search text, p_product_type text, p_category_id uuid, p_brand_id uuid, p_added uuid[], p_limit integer, p_offset integerjsonbdefinerCV3-P4-03 (DEC-CV3-28). "Thêm sản phẩm" picker page for deal.manage holders (no catalog.read needed): On sale live STANDARD / COMBO products by keyword, type, category subtree and brand; {total, items}; null without deal.manage.
point_config_actorp_kind textbooleanP2-10. Acting principal holds a point-config MAKER/CHECKER role in WEB_ADMIN right now.
point_config_checker_roles—text[]P2-10. WEB_ADMIN roles that may approve/reject a point cap/rate version. Empty: no matrix rule (GAP-65).
point_config_maker_roles—text[]P2-10. WEB_ADMIN roles that may propose a point cap/rate version. Empty: no matrix rule (GAP-65).
point_config_record_benefit_policy—triggerdefinerFU-BIZOWNER. Trigger: approving a TIER_BENEFIT_POLICY version inserts the immutable tier_benefit_policy_versions row.
point_config_snapshot—TABLE(point_cap_bp integer, point_cap_policy_version text, point_rate_vnd numeric, point_rate_policy_version text)definerP2-10. Effective APPROVED cap + rate (refs <key>@v<n>:<id>) for activation; managers only; else no row.
points_excess_pendingp_campaign_id uuidTABLE(order_id uuid, policy_version_id uuid, owner_account_id uuid, points integer, request_id text, recorded_at timestamptz, original_request_id text, original_status text, original_account_id uuid, original_role text, original_points integer, rate_snapshot_vnd text, rate_policy_version text)definerG1S-P1-02, G2S-P1-06, U28-P2-02. pi_worker: PENDING excess Pi-Point refunds of a campaign (Group Buy: close outcome; Mua định kỳ: campaign outcome) with the original REDEEM to reverse partially.
policy_statuses—text[]
product_line_factsp_campaign_id uuidTABLE(product_id uuid, brand_name text, unit text, category_path text[], image jsonb)definerCV3-P4-16 (DEC-CV3-32). Brand, unit, category path (root first) and primary picture of the products of one campaign, for a campaign reader (deal.read / deal.manage; no catalog.read needed); empty otherwise.
product_linesp_campaign_ids uuid[]TABLE(campaign_product_id uuid, campaign_id uuid, product_id uuid, moq_qty integer, sku text, name text, product_type text)definerP2-07, CV3-P4-16. Product rows (SKU/name/type/MOQ) of campaigns, for a campaign reader (deal.read / deal.manage); empty otherwise.
product_position_default—triggerdefiner
product_qtysp_campaign_id uuid, p_at timestamp with time zoneTABLE(campaign_product_id uuid, real_qty bigint, virtual_qty integer, total_qty bigint)CV3-P1-02. Thật / ảo / tổng (BR-C-04) of every product of a campaign in one read: the set form of campaign.total_qty = ordering.committed_units + campaign.virtual_qty. Owner-side callers (overview facts) only.
propose_cycle_forfeitp_order uuid, p_cycle_no integer, p_reason text, p_source_id text, p_correlation_id correlation_refjsonbdefinerFU-RECCLOSE. Operations maker proposes the forfeit review of one committed period of a LOCKED Recurring order.
public_campaign_categoriesp_campaign_id uuidjsonbdefinerG2S-P1-09 (BR-KPD-02). [{id, name, imagePath, position}] of the live ACTIVE level-1 categories with a product of the campaign, in the public_categories() order; [] unless the campaign is shown on the App (BR-APP-02).
public_campaign_idsp_search text, p_statuses text[], p_from date, p_to date, p_limit integer, p_offset integerjsonbdefinerP2-08 / G1S-P1-09. {total, ids} of published Group Buy campaigns: the 7-argument form with no category.
public_campaign_idsp_search text, p_statuses text[], p_from date, p_to date, p_limit integer, p_offset integer, p_category_id uuidjsonbdefinerG1S-P1-09 + U28-P1-05. {total, ids} of the Group Buy campaigns the App lists: Đang mở then Sắp mở (CD-US-19 AC10; keyword / status / VN-date window); with a category, only campaigns with a Deal in it or a sub-category (BR-KP-05). A closed campaign stays readable by id (campaign.public_campaigns).
public_campaign_jsonp_id uuid, p_status text, p_version uuidjsonbU19-P2-35 + G2I-P1-02 + G1S-P1-08 + G1S-P1-06c + PAF-P1-12 + CV3-P1-08. One public Mua chung object: no description (internal), Word offer fields, terms, milestones with choiceSharePct, products by position with their Deal facts (totalUnits from campaign.product_qtys), spinEnabled = a wheel is chosen (BR-C-09), spinSchedule (D6), maxPointsPerSpin (R5), participantCount / participantsToday (D5) and pointRateVnd (BR-APP-07; null when none).
public_campaignsp_ids uuid[]jsonbdefinerP2-08. Allow-listed public projection (products, tiers, progress, images, milestones) of published ids.
public_categories—jsonbdefinerG1S-P1-09. [{id, name, imagePath, position}] of the live ACTIVE level-1 categories with a Deal in a Group Buy campaign shown as Đang mở / Sắp mở; imagePath only for a READY, undeleted PUBLIC image (BR-KP-05 chips).
public_community_savingsp_ids uuid[]TABLE(campaign_product_id uuid, saving_vnd bigint)definer#412 G1-09. Cả cộng đồng tiết kiệm per published Group Buy Deal: Σ (listed − final unit price) × quantity of the real orders LOCKED by the close and not cancelled or forfeited since; NULL before the outcome, when the MOQ was missed or no listed price.
public_deal_facts_jsonp_campaign_product_id uuidjsonbG1S-P1-08 + DEC-OWN30-S1-ORDINAL + PAF-P1-10. Deal facts of one campaign product: participantCount (campaign.deal_participant_count: real buyers + virtual units), the 3 most recent participants' initials newest first (virtual included, fixed set), isGenuine, highlightedSpecs, milestoneShares (campaign.public_milestone_shares_json). Owner-side only.
public_deal_root_categoriesp_ids uuid[]TABLE(campaign_product_id uuid, category_id uuid)definer#412 G1-10 + G2S-P1-09. The level-1 (root) live category of each published Group Buy Deal's product (what publicCampaigns(categoryId) takes) and of each published Recurring product (APP_USER only); no row without a live chain.
public_highlighted_specsp_product_id uuidjsonb
public_milestone_shares_jsonp_campaign_product_id uuidjsonbPAF-P1-10 (G1-04). x% chọn per milestone of one Deal: whole % (largest remainder, sum 100) of the committed orders with a line on the Deal that chose each milestone of its campaign; 0 for every milestone without such an order. Owner-side only.
public_milestones_jsonp_campaign_id uuidjsonbG1S-P1-08. Published milestones of a Mua chung campaign with choiceSharePct (largest remainder over the committed orders, sum 100; null before the first). Owner-side only.
public_product_jsonp_campaign_product_id uuid, p_status text, p_version uuidjsonbU19-P2-35. One public campaign product: catalog presentation, position, listed price, tag while selling, tiers and totalUnits = campaign.total_qty (thật + ảo) while UPCOMING / OPEN.
public_product_row_jsonp_campaign_product_id uuid, p_status text, p_version uuid, p_total_units bigintjsonbCV3-P1-02. Body of campaign.public_product_json (U19-P2-35) with totalUnits given by the caller (shown while UPCOMING / OPEN): a basket read passes campaign.product_qtys instead of total_qty per product.
public_products_in_categoryp_campaign_id uuid, p_category_id uuiduuid[]definerG1S-P1-09. Campaign product ids of a published Group Buy campaign whose product is in the category subtree, in the Admin order (BR-KP-05: the list keeps only those Deals).
public_reader—booleanP2-08 / FU-525. PUB-01 mirror: true for a request in the APP_USER app (scope PUBLIC: no account needed). PUB-02 mirror: true for an ACTIVE Sale in the APP_SALE app holding a live deal.read_public grant at ALL.
public_recurring_campaignsp_ids uuid[]jsonbdefiner#286. Allow-listed public projection (products, tiers, progress, images, cycles, rule numbers) of published Recurring ids.
public_recurring_idsp_search text, p_statuses text[], p_limit integer, p_offset integerjsonbdefinerU28-P1-05. {total, ids} of the Recurring campaigns the App lists: Đang mở then Sắp mở (CD-US-19 AC10); a closed campaign stays readable by id (campaign.public_recurring_campaigns).
public_recurring_jsonp_id uuid, p_status text, p_version uuid, p_cutoff_hours integerjsonbU19-P2-35 + G2I-P1-02 + G2S-P1-09 + G2S-P5-16. One public Mua định kỳ object: no description (internal), Word offer fields, packages with their months, delivery windows, terms, products by position with isGenuine / highlightedSpecs, spinSchedule (D6), maxPointsPerSpin (R5), participantCount (D5), the Admin-set participantsToday (G2S-TD-01) and pointRateVnd (APPROVED POINT_RATE in force, BR-APP-07; null when none).
public_recurring_reader—boolean#286. PUB-01 mirror for Recurring: true for a request in the APP_USER app only (APP_SALE pending, not admitted).
public_search_facetsp_keyword text, p_kind text, p_category_ids uuid[]jsonbdefinerG1S-P1-16. {total, kindCounts, categories} of campaign.public_search_items for the U-16 filter (BR-KP-03): kindCounts ignore the kind, category counts ignore the categories; ACTIVE 2-level tree.
public_search_itemsp_keyword text, p_kind text, p_category_ids uuid[]TABLE(kind text, campaign_id uuid, campaign_product_id uuid, category_id uuid, ord bigint)definerG1S-P1-16 + G2S-P1-09 + PAF-P1-16. Products of the campaigns shown on the App (BR-APP-02: per type the first Đang mở and the first Sắp mở bán) matching the keyword (product, brand, campaign / basket name; case ignored, Vietnamese diacritics kept: catalog.name_key, BR-KP-02 03/11), kind and categories (subtrees, union); display order.
public_shown_campaign_ids—SETOF uuidG2S-P1-09 (BR-APP-02). Campaigns shown on the App: per type the first Đang mở (closing first) and the first Sắp mở (opening first), the publicCampaignHome / publicRecurringHome pair, for the readers of the request. Owner-side.
public_spin_schedule_jsonp_campaign_id uuid, p_spin_enabled booleanjsonbG2I-P1-02 D6, CV3-P1-07, VQM-P1-11. spinSchedule of a public campaign: the PUBLISHED rule of the chosen wheel as [{startsAt, endsAt, spins}] — shape 1 its order-time intervals, shape 2 its rounds cut to the campaign window (spin.resolve_rounds: Ngày 1 from opens_at, half-open ends, the last round until closes_at, rounds past it dropped). [] when the wheel is off or has no rule.
public_statusp_state text, p_opens_at timestamp with time zone, p_closes_at timestamp with time zonetextU19-P2-35. UPCOMING / OPEN / CLOSED / SUCCESS / PARTIAL_SUCCESS / FAILED from the Word state (+ closes_at for OPEN); NULL = not published (DRAFT, PENDING_PUBLISH, legacy states).
public_terms_jsonp_terms_set_id uuidjsonbU19-P2-35. {id, name, content} of the campaign's Điều khoản tham gia Deal set (B058.R10); helper of the public reads.
public_tsp_at timestamp with time zonetext
publish_job_name—textU19-P2-05. Job name of the publish run (slot campaign:<id>:publish:v<n>).
rearm_close_for_orderp_order_id uuid, p_tag textvoiddefinerPAF-P1-19 (DEC-PAF-18). Enqueues one more close run (slot campaign:<id>:v<version>:<tag>, due now) when the order's campaign is CLOSING; nothing otherwise. Called by the payment re-arm triggers only.
rebuild_cyclesp_campaign_id uuidintegerU19-P1-05 / CV3-P1-01. Replaces the Recurring schedule: period k = Kỳ bắt đầu giao + (k-1) months, k = 1..max(Số kỳ); delivers_from/to = smallest Từ / largest Đến ngày of the complete windows with Đến >= Từ (VN). Empty without start month/such a window/package.
reconcile_jobsp_campaign_id uuidtext[]definerU19-P2-05. Enqueues the publish/open/close runs the campaign wants at its version and cancels its other QUEUED runs.
record_cycle_skipp_order uuid, p_cycle_no integer, p_request_id text, p_rule_version text, p_source_id text, p_reason_code text, p_reason_text textjsonbdefinerP2-18, G2I-P1-01 D12. Buyer: records a skip of one period of an OWN LOCKED Recurring order under the order row lock, with an optional reason (code + text); the insert guard re-checks the policy, n and the lock at write time. A skip is never a delivery.
record_points_excess_refundp_order_id uuid, p_point_request_id uuidbooleandefinerG1S-P1-02. pi_worker: marks the excess Pi-Point refund REFUNDED once its REVERSE_REDEEM is ACCEPTED; true only for the call that marked it (the caller appends order.points_excess_refunded in the same transaction).
record_recurring_outcomep_campaign_id uuid, p_expected_version integer, p_run_id uuid, p_rule_code text, p_rule_version text, p_outcome text, p_products jsonbTABLE(status text, version integer, outcome_id uuid, detail jsonb)definerP2-16, U19-P2-07, G2I-P2-02. Recurring close write: freezes the virtual quantity, recomputes real (Σ units of the PLACED orders) + virtual per product under lock, records the immutable outcome and campaign_product_outcomes, CLOSING -> SUCCESS | PARTIAL_SUCCESS | FAILED; parks (writes nothing) on a mismatch, unresolved payment or tier gap.
record_refund_orderedp_campaign uuidbooleandefinerCV3-P1-04 (BR-CT-10). The one REFUND_ORDERED history version of a closed campaign (WORKER, Hệ thống): campaign row locked, written only when absent; false when it exists or the campaign holds no outcome yet.
recurring_actual_linesp_points_value bigint, p_cells jsonbTABLE(cycle_no integer, line_no integer, quantity integer, unit_price_vnd bigint, value_vnd bigint, points_value_vnd bigint, net_value_vnd bigint)U28-P2-01 (DEC-U28-01, BR-C-08, DEC-OWN27-ACTUAL-PRICE-CEIL). Pure: per (cycle, line) the value at the unit price, the Pi-Point value placed (applied = min(points value, Σ values), split over the lines by value, cumulative floor) and the net value at the actual unit price (ceil on the first units of the line, cycle 1 -> n).
recurring_allocatep_deposit bigint, p_points_value bigint, p_points integer, p_values bigint[], p_round_cod booleanTABLE(cycle_no integer, value_vnd bigint, cash_vnd bigint, points_value_vnd bigint, points integer, owed_vnd bigint, rounding_vnd bigint)U19-P2-07 / G2I-P2-01 (BR-DK-08, B060.R02, GAP-W-CD-17, G6-Q7/Q8). Pure: Pi-Point value split evenly over the cycles with goods (remainder on the last ones), deposit from the last cycle back to the first (an empty cycle takes 0), owed = value - shares, COD rounded up to 1,000đ when asked; points count follows the value.
recurring_allocate_actualp_deposit bigint, p_points_value bigint, p_points integer, p_cells jsonb, p_cycles integer, p_round_cod boolean, p_fixed integer[]TABLE(cycle_no integer, value_vnd bigint, points_value_vnd bigint, net_value_vnd bigint, cash_vnd bigint, points integer, due_vnd bigint, owed_vnd bigint, rounding_vnd bigint)U28-P2-01 / U28-P2-02 (DEC-U28-01, DEC-U28-12, BR-DK-08, CD-US-12 AC06-AC08 / AC22). Pure: per cycle the value, Pi-Point value and V_c from campaign.recurring_actual_lines, the deposit last -> first on V_c, due = V_c - deposit, COD ⌈due⌉ to 1,000đ with the difference balanced on the last cycle still to collect (Σ COD = ⌈Σ due⌉); a negative balance is carried back onto the earlier COD cycles still to collect, nearest first; p_fixed cycles (paid or skipped) are never balanced or carried onto.
recurring_children_check—triggerdefinerCV3-P1-01. AFTER insert/update of a window or package of a non-DRAFT campaign: complete row, Đến >= Từ and no overlap (windows), Số kỳ set and unique, Được bỏ qua < Số kỳ (packages); raises the former constraint names. Serialised per campaign by a transaction advisory lock.
recurring_close_blockersp_campaign_id uuid, p_policy_version_id uuid, p_closes_at timestamp with time zoneTABLE(pending integer, late integer, odd integer, excluded integer, placed integer)definerP2-16, PAF-P1-01. Counts of a Recurring close: pending deposits, late confirmations (campaign.deposit_confirmed_late: a deposit started before closes_at and confirmed later is NOT late), inconsistent, excluded and placed orders.
recurring_close_cellsp_outcome_id uuid, p_order_id uuidjsonbU28-P2-01. The allocation cells of an order at the close: kept (cycle, line) with goods, unit price = least(final, order-time); input of campaign.recurring_allocate_actual.
recurring_close_inputsp_campaign_id uuid, p_expected_version integer, p_run_id uuidTABLE(status text, campaign_type text, version integer, closes_at timestamptz, closes_at_vn date, policy jsonb, detail jsonb, products jsonb, expired jsonb)definerP2-16, U19-P2-07, G2I-P2-02. Locks the CLOSING Recurring campaign, cancels its unpaid orders (P2-19), locks the open orders; returns the frozen policy version and per product the MOQ, the virtual quantity at closes_at and the valid commitments (one per order line and quantity per cycle, Σ quantityPerCycle x cycles = Σ units), or a parked status; expired lists the orders the close cancelled as unpaid.
recurring_close_job_name—textP2-16. Job name of the Recurring close run (slot campaign:<id>:v<CLOSING version>).
recurring_close_obligations_open—booleandefinerFU-F3. True only while the G-CP gate is open (the close job asks; a closed gate keeps the FU-L7 behaviour).
recurring_close_progressp_campaign_id uuidTABLE(campaign_product_id uuid, moq_qty integer, committed_qty bigint, progress_bp bigint, status text, close_rule_status text, final_committed_qty bigint, final_moq_met boolean, final_unit_price_vnd bigint, decided_at timestamptz, closes_at_vn date, as_of timestamp with time zone)definerP2-16. Provisional committed quantity per product plus the recorded outcome; every final field is NULL until the immutable outcome exists. Manager read (GAP-26).
recurring_gate_open—booleandefiner#286. G-CP retired 2026-10-16 (team decision): always true. Kept as the seam earlier callers read.
recurring_overview_factsp_campaign_id uuidjsonbdefinerU19-P2-09, G2I-P2-02, U28-P1-10, CV3-P1-02, CV3-P1-05, CV3-P4-04, CV3-P4-09, CV3-P4-19. Order facts of the Admin Mua định kỳ overview (BR-DKCT-03..08): live real/virtual/total per product, deposited orders per package term x delivery window (+ package Pi-Point already Available, the configured % package reward floored per order at the rate of its ISSUE, else the order rate snapshot, on V0, or after a Thành công một phần on the kept final value of every kept order (BR-DK-09, DEC-CV3-31), the net issued package reward (ISSUE - bound close partial cancels), and once closed the kept / to-refund / surplus deposit obligations of payment.recurring_order_money), product lines per term x window (units = Σ over the cycles), cycleLines (Σ quantity per product x cycle, the import matrix) and removedOrders (distinct orders that lost a product at the close), or the close snapshot (orders kept = LOCK, orders of failed products only = CANCEL) once closed. Aggregates only. Read by deal.read / deal.manage (CV3-P4-16).
recurring_participants_todayp_campaign_id uuidintegerG2S-P1-09 (DEC-OWN28-G2S-TODAY-FIXED). "+{n} hôm nay" of a Recurring campaign = system_settings recurring.participants_today (tech debt G2S-TD-01, GAP-G2S-12 replaces this body); never computed from orders.
remaining_capture_sharep_cap bigint, p_before bigint, p_weight bigint, p_total bigintbigintU19-R10. The part of a capture p_cap owed to a weight p_weight that follows p_before of weight, out of p_total: the cumulative floor difference, so the parts of all weights add up to p_cap exactly.
require_policyp_policy_version_id uuid, p_need texttextP2-06. APPROVED/INTERIM, or raises campaign_policy_undecided (DETAIL = decision id) for an UNDECIDED policy.
reward_policy_validp jsonbbooleanL9 / A-LOY-03, U19-R14. The shape of a reward policy document: 9 whole-number members (13 with the commitment terms for a version stored before U19-R14), Referral total = eKYC + purchase, rates in basis points 0..10000. No upper reference level (AC07), no milestone or Spin member (AC04).
run_schedule_stepp_step text, p_campaign_id uuid, p_slot_version integer, p_run_id uuidTABLE(outcome text, campaign_type text, version integer, policy_version_id uuid, from_state text, to_state text, cloned_from_id uuid)definerU19-P2-05. One scheduled run as pi_worker: publish / open / close of a campaign, idempotent per slot (B006.R03).
schedule_close_wait_rerunp_campaign_id uuidtimestamptzdefiner#479 T6 / item 2. pi_worker (the close jobs, when a close settles waiting for a payment): enqueues one more close run of the CLOSING version at closes_at + payment.close_payment_wait() (slot campaign:<id>:v<version>:wait) while a live deposit attempt started before closes_at, or an UNKNOWN one, is waited for; returns its due time, null when nothing is scheduled.
schedule_jobsp_campaign_id uuidtext[]definerU19-P2-05. create/update/delete: campaign.reconcile_jobs for a campaign manager (B006.R03).
skip_cutoff_version—TABLE(id uuid, version_no integer, hours_before_cycle integer)definerFU-RECCLOSE. The approved skip cutoff version that applies now, or no row (DEC-CP-SKIP-CUTOFF undecided).
spin_wheel_refp_wheel uuidjsonbdefinerCV3-P1-08 BR-CT-09 / BR-DKCT-09, CV3-P4-16, VQM-P1-11. One wheel as Campaign.spinWheel shows it: id, code, name, status, version, in_use_locked, round_count (shape 1 intervals / shape 2 rounds) and max_points of its PUBLISHED rule, for a campaign reader (deal.read / deal.manage) or a spin reader; null when unknown or not allowed.
staff_display_namesp_ids uuid[]TABLE(account_id uuid, display_name text)definerU19-P2-03 B016.R11, CV3-P4-16. profiles.full_name of WEB_ADMIN staff ids (<= 1000) for campaign readers (deal.read / deal.manage); definer, fails closed if the owner is not RLS-exempt.
step_job_namep_step texttextU19-P2-05. publish | open | close -> its job name.
total_qtyp_campaign_product_id uuid, p_at timestamp with time zonebigintU19-P1-04. Thật + ảo (BR-C-04): ordering.committed_units + campaign.virtual_qty. The only formula; owner-side callers (close, public and overview reads) use it.
unavailable_productsp_product_ids uuid[]SETOF uuiddefinerP2-07. Selected product ids that are not live ON_SALE (AP-26 AC05); managers only.
unfinished_states—text[]U19-P1-01. Unfinished campaign states (product discontinue guard); REVIEW/ACTIVE legacy rows until U19-P1-06.
virtual_qtyp_campaign_product_id uuid, p_at timestamp with time zoneintegerU19-P1-04, PAF-P1-05. Virtual quantity of a campaign product at an instant (BR-C-04, B075, GAP-W-CD-16): only from OPEN on (Product 02/11): FIXED as entered, DAILY per VN day from the opening day up to Tối đa; the frozen close value once written. CV3-P1-02: the formula is campaign.virtual_qty_value.
virtual_qty_valuep_state text, p_opens_at timestamp with time zone, p_closes_at timestamp with time zone, p_mode text, p_fixed_qty integer, p_daily_qty integer, p_max_qty integer, p_at_close integer, p_at timestamp with time zoneintegerCV3-P1-02. The virtual quantity formula of campaign.virtual_qty (PAF-P1-05, BR-C-04) over the campaign state and window and the product's virtual fields, no table read: a set read (Admin product rows) computes it per row without one RLS evaluation per row.
vn_datep_at timestamp with time zonedateP2-09. Vietnam calendar date (UTC+07:00, no DST) of a UTC instant.
wheel_optionsp_search text, p_limit integerTABLE(id uuid, code text, name text, max_points integer)definerCV3-P4-22 (DEC-CV3-37), VQM-P1-11. "Áp dụng vòng quay may mắn" of the campaign form (BR-C-09): ACTIVE, non-legacy wheels matching the keyword on code / name (catalog.name_key), newest first, at most p_limit (1..100): id, code, name, max_points of the PUBLISHED rule (null without one). For deal.manage holders; empty otherwise.
write_throttle_beginp_max_calls integer, p_window_seconds integerjsonbdefinerCV3-P4-01 (DEC-CV3-18). Counts one campaign write of the acting Web Admin account in a fixed window: PROCEED {call} or THROTTLED {retry_after_seconds}. pi_api only.

schema ordering ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
actor_reads_period_money—booleandefinerFU-F1 DEC-OPS-PERIOD-MONEY. ACTIVE WEB_ADMIN with a period_money_roles() role, or a payment reader (F-01); NULL money for everyone else.
admin_order_allocationp_scope text, p_order_id uuidjsonbdefinerU28-P2-01, PAF-P1-24. adminOrder(id).recurring allocation facts (order.read, TEAM/ALL): the policy frozen at the close (null before), each cycle's owed before rounding of the current allocation (payment.recurring_cycle_alloc: after a skip the deposit spread again and 0 for the skipped cycle; else the close row, else the order period) and, under ACTUAL_PRICE, each kept (cycle, line) value at its actual unit price (pure kernel on the frozen close inputs).
admin_order_detailp_scope text, p_order_id uuidTABLE(id uuid, code text, campaign_type text, created_at timestamptz, confirmed_at timestamp with time zone, order_status text, payment_status text, shipping_status text, address_version integer, source_channel text, source_owner_name text, source_link_code text, campaign_id uuid, campaign_code text, campaign_name text, campaign_status text, closes_at timestamp with time zone, closed_at timestamp with time zone, product_name text, total_qty bigint, moq_qty integer, remaining_vnd bigint, shipment_id uuid, shipment_code text, pii_full boolean, customer_account_id uuid, customer_code text, customer_name text, customer_phone text, tier_name text, tier_multiplier text, referrer_name text, referrer_code text, recipient_name text, recipient_phone text, province text, district text, ward text, address_line text, address_type text, customer_note text, address_updated_at timestamp with time zone, lines jsonb)definerU19-P2-11, G2I-P2-02. One staff-visible order (TEAM/ALL) for the Admin detail: header + source, status cards, campaign, customer (tier, referrer), delivery + customer note, lines (quantity per cycle, units over every cycle) with provisional / final price and tier; full PII only for customer readers (customer.actor_can_read).
admin_order_paymentp_scope text, p_order_id uuidTABLE(order_id uuid, campaign_type text, method text, locked boolean, order_value_vnd bigint, value_final boolean, points_used integer, points_value_vnd bigint, deposit_vnd bigint, collected_vnd bigint, paid_cash_vnd bigint, transactions jsonb)definerU19-P2-12. Thanh toan block of one staff-visible order (TEAM/ALL): method + lock, value (final after the close, else V0), stored points and deposit, collected and paid cash (settled), transactions (Pi-Point, online attempts, COD).
admin_order_recurringp_scope text, p_order_id uuidTABLE(campaign_type text, committed_cycles integer, delivery_window_no integer, window_from_day integer, window_to_day integer, allowed_skips integer, skipped_count integer, value_final boolean, campaign_products integer, moq_met_products integer, lines jsonb, cycles jsonb)definerU19-P2-13, G2I-P2-02, PAF-P1-21, #479 A. Mua định kỳ part of one staff-visible order (TEAM/ALL): committed cycles, delivery window, allowed skips (package n) and skips used (presses + cycles left empty, ordering.skips_used), products met, per-line MOQ result + final price, per-cycle allocation (deposit share of payment.recurring_cycle_alloc, COD of it after a skip, Pi-Point of the close values; else order_periods), cycle axes, delivered_equivalent, skip, empty, the quantities of the cycle (lines, changed), shipment and the failed-delivery settlement (failed_delivery). Stored rows only.
admin_order_shipmentsp_scope text, p_order_id uuidTABLE(shipment_id uuid, cycle_no integer, shipment_code text, carrier_code text, state text, expected_on text, handed_over_at timestamptz, order_cod_vnd bigint, trip_cod_vnd bigint, fee_vnd bigint, grouped jsonb, delivery_attempts integer)definerU19-P2-12, U28-FU-API-A. Giao hang block of one staff-visible order (TEAM/ALL): one row per shipment link (cycle for Recurring) with code, carrier, state, expected day, handover, order / trip COD, fee, the visible grouped orders and the delivery attempts counted by fulfillment.delivery_attempts_of (ASSUME-05).
admin_recurring_moneyp_scope text, p_order_id uuidjsonbdefinerU28-P2-02. adminOrder(id).recurring money (order.read, TEAM/ALL): payment.recurring_order_money of a visible order.
apply_no_receivep_order_id uuid, p_cycle_id uuid, p_shipment_event_id uuidtextdefinerU19-P2-23/24 (DH-US-14). Group Buy not fully paid -> FAILED + DEPOSIT_FORFEITED; paid online -> apply_return. Recurring cycle paid -> SUCCESS delivered_equivalent; not paid -> PENDING_DECISION, nothing written (GAP-OPS-02).
apply_returnp_order uuid, p_cycle_id uuid, p_shipment_event_id uuidtextdefinerU19-P2-18. Order / cycle -> RETURNED (log, outbox order.returned), payment kept (ASSUME-03); idempotent by state. PPI-P5-08 + PPI-P7-05: writes the PENDING recall slips of the unit (E-09a).
assert_group_open_nowp_campaign_id uuid, p_constraint textvoiddefinerP2-12. Group Buy cutoff at write time (clock_timestamp) under the campaign row lock; raises the given constraint name when the campaign is not ACTIVE or closes_at has passed.
assert_whole_schedulep_campaign_id uuid, p_term integervoidU19-P2-37. A package covers cycles 1..Số kỳ of the schedule (B208.R05); missing cycles -> recurring_schedule_short.
assign_participant_ordinal—triggerdefinerG1S-P1-08 + DEC-OWN30-S1-ORDINAL (BR-MC-02 per owner 30/10). "Người thứ n" of a Group Buy order at its deposit confirmation: campaign.deal_participant_count of its Deal at now() with the buyer counted, under a lock of the Deal row. Trigger orders_zz_participant_ordinal.
assign_recurring_participant_ordinal—triggerdefinerG2S-P5-15 + DEC-OWN30-S1-ORDINAL. "Người thứ n" of a Mua định kỳ order at its deposit confirmation: campaign.campaign_participant_count of its basket at now() with the buyer counted (= participantCount right after), under an advisory lock of the basket (no campaigns row lock). Trigger orders_zz_participant_ordinal_recurring.
backfill_order_axesp_batch integerintegerdefinerU19-P1-07. Fills the axes of orders that have none, in batches; idempotent (0 when nothing is missing).
backfill_shipping_axisp_batch integerintegerdefinerU19-P1-08. Fills the shipping axis of orders and the axes of cycles that have none, in batches; idempotent.
basket_matches_cycle_linesp_basket_id uuid, p_cycle_lines jsonbbooleanG2I-P2-01 (G2-06). True when the quote overrides are exactly the basket's recurring_basket_cycle_lines.
basket_matches_linesp_basket_id uuid, p_lines jsonbboolean
buyer_cancel_reasonp_order uuid, p_state text, p_campaign_state text, p_closes_at timestamp with time zonetextdefiner#388 O3. The buyer-cancellation rule of the read and the write: ordering.cancel_reason, then PAYMENT_PENDING for an unpaid order with a deposit attempt in flight.
cancel_orderp_order uuid, p_expected_version integer, p_reason text, p_source_id text, p_reason_code textjsonbdefinerP2-20 / #377 / #388. Buyer: PLACED or DEPOSIT_PENDING -> CANCELLED of an OWN order before the cutoff, under the campaign row lock; an unpaid order is refused while a deposit attempt is in flight (PAYMENT_PENDING) and its OPEN obligations are cancelled; optional reason text and reason code.
cancel_payment_pendingp_order uuidbooleandefiner#388 O3. True while a deposit attempt of the order may still take money or points: payment.order_expiry_blocked or a CREATED / PENDING intent. The buyer cancel of an unpaid order is refused (PAYMENT_PENDING) meanwhile.
cancel_reasonp_state text, p_campaign_state text, p_closes_at timestamp with time zonetextP2-20 / #388 O3. NULL when the buyer may cancel (PLACED or DEPOSIT_PENDING, campaign OPEN, before closes_at), else a reason code; payment-in-flight is ordering.buyer_cancel_reason.
cancellation_eligibilityp_order uuidjsonbdefinerP2-20. Buyers: server-computed cancellation eligibility of an OWN order (NULL for unknown/foreign), no lock.
committed_states—text[]
committed_unitsp_campaign_product_id uuidbigint
cycle_empty_after_moqp_order uuid, p_cycle integerbooleanU28-P1-07 (DEC-U28-03, BR-DK-09). True when the cycle had goods ordered (a quantity > 0) and every one of those products missed its MOQ at the close: value 0, no delivery, not a skip. NULL before the close or for a cycle outside the order; false for a cycle with goods or one left empty when ordering.
cycle_fully_cancelledp_order uuid, p_cycle integerbooleandefinerFU-SHORTAGE2, G2I-P2-02. True when the cycle had goods (its own quantities, ordering.cycle_lines) and every unit of them was cancelled for shortage: such a cycle is never shipped. An empty cycle is skipped, not cancelled.
cycle_goodsp_order uuidTABLE(cycle_no integer, order_line_id uuid, campaign_product_id uuid, quantity integer)G2I-P2-02 (G2-06, G6-Q11, BR-DK-09). The (cycle, line) an order still has to deliver: quantity of the cycle > 0 (ordering.cycle_lines) and the product did not miss its MOQ at the close (campaign_product_outcomes.met = false).
cycle_has_goodsp_order uuid, p_cycle integerbooleanG2I-P2-02 (G6-Q2). True when the cycle has something to deliver (ordering.cycle_goods); false for a cycle left empty when ordering, one whose every product left the order at the close, or a cycle outside the order.
cycle_is_emptyp_order uuid, p_cycle integerbooleanG2I-P2-01 (G2-06, G6-Q2). True when every product of the cycle is 0 (an empty cycle counts as one skip); NULL for a cycle outside the order.
cycle_linesp_order uuidTABLE(cycle_no integer, order_line_id uuid, campaign_product_id uuid, quantity integer)G2I-P2-01 (G2-06). Every (cycle 1..committed_cycle_count, line) of an order with its quantity: the override of order_cycle_lines, else order_lines.quantity. The only place override and default are combined.
cycle_moneyp_order uuidTABLE(cycle_no integer, value_vnd bigint, prepaid_vnd bigint, due_vnd bigint, cod_vnd bigint)G2I-P6-01, PAF-P1-03. Money of each cycle of a Recurring order for the buyer reads: order_periods before the close; after it the close values (value, cash + Pi-Point share, due = value - prepaid, COD = owed_vnd rounded up to 1,000đ, 0 for a CANCELLED cycle or an ONLINE remaining), the rule of the staff read; after a skip the deposit share, due and COD of the respread (order_cycle_skip_values, DEC-PAF-06; Pi-Point share unchanged). Internal: called by SECURITY DEFINER reads only.
cycle_skip_lock_atp_delivers_from timestamp with time zonetimestamptzdefinerG2I-P1-01 D14, U28-P2-04, PAF-P1-02 (DEC-PAF-05). Always NULL: a cycle has no skip lock instant any more (it can be skipped until it is in a shipment). Kept for campaign.order_skip_state and campaign.basket_snapshot (skipCutoffAt).
drop_order_pointsp_order_id uuid, p_deposit_vnd bigint, p_source_id textjsonbdefinerG1S-P1-15 (BR-DC-06 U-30b, GAP-G1S-04 = (a)) + G2S-P1-04 (BR-DCD-05). dropOrderPoints: the buyer's own DEPOSIT_PENDING Group Buy or Mua định kỳ order with no REDEEM running or settled goes to 0 points on the same order (code, created_at / depositDueAt, version kept); deposit = the given amount, checked by orders_money with CEIL; DEPOSIT obligation amount follows, an OPEN PI_POINT tender is CANCELLED; a Mua định kỳ order's periods are allocated again (no Pi-Point). 0 points already = no change. Refusals: order_points_drop_not_buyer / _not_found / _refused (reason order_not_pending | points_held = a REDEEM running or settled, API code kept by PPI-P4-04 W-08 | payment_pending).
effective_periodsp_order uuidTABLE(cycle_no integer, value_vnd bigint, cancelled_vnd bigint, prepaid_vnd bigint)definerFU-SHORTAGE2. PAY-BRULE-26 after the partial cancellations: cycle value less cancelled units, prepaid allocated from the last cycle backwards.
effective_v0_vndp_order uuidbigintdefiner
failed_delivery_countp_order uuidintegerdefiner#479 A. Cycles of the order Operations settled as failed deliveries; counted with ordering.skips_used against n.
group_policy_approvedp_policy_version_id uuidbooleandefinerP2-12. TRUE when a frozen Group Buy policy version snapshots APPROVED point cap/rate versions with the same values; FALSE otherwise; NULL for a non-buyer. groupQuote/submitGroupOrder refuse unless TRUE.
in_app_events_log_order—triggerdefinerU19-P1-09. NOTIFICATION activity row (SYSTEM) for every in-app notification about an order.
is_buyer—booleanP2-11. Matrix U-01/U-02 mirror: ACTIVE APP_USER membership with role user, ACTIVE account, claimed app.
legacy_cycle_axesp_cycle uuid, OUT order_status text, OUT payment_status textrecorddefinerU19-P1-08. Order / payment axes of a cycle from its stored facts (backfill); writes nothing.
legacy_order_axesp_order uuid, OUT order_status text, OUT payment_status text, OUT cancel_reason text, OUT confirmed_at timestamp with time zonerecorddefinerU19-P1-07. Axes of an order computed from its stored facts (backfill and reconciliation); writes nothing.
legacy_unit_shippingp_order uuid, p_cycle uuidtextdefinerU19-P1-08. Shipping axis of an order (cycle null) or cycle from its stored facts (backfill); writes nothing.
lines_okp_lines jsonb, p_v0 bigint, p_cycles integerboolean
log_activityp_order uuid, p_category text, p_action text, p_actor uuid, p_from text, p_to text, p_note text, p_cycle_no integerbigintdefinerU19-P1-09. Appends one order activity row; actor null = SYSTEM, owner = CUSTOMER, else OPERATIONS (name snapshot).
mark_cycles_duep_at timestamp with time zone, p_batch integerTABLE(order_id uuid, cycle_id uuid, cycle_no integer, delivery_date date)definerU19-P2-25 (DH-US-15). One batch: valid, not skipped Recurring cycles whose delivery day (VN date of the order period, minus ordering.cycle_due_lead_days = 0) is reached move NOT_PROCESSED -> WAITING_PACKING, one SHIPPING log row, actor SYSTEM; SKIP LOCKED, idempotent. pi_worker only (job order.cycle_due).
money_basis_okp_basis text, p_v0 bigint, p_deposit_bp integer, p_deposit bigint, p_cap_bp integer, p_rate numeric, p_max_points integer, p_points integer, p_points_value bigint, p_rounding textbooleanU19-P2-36 / U19-R13 / G1S-P1-01. Money CHECK by deposit basis: V0 = ordering.money_ok (deposit V0 x rate exactly); PAYABLE = deposit (V0 - points value) x rate rounded by p_rounding (CEIL up to whole VND, BR-APP-06; HALF_UP for rows before 20261227010000), 0 VND allowed (GAP-W-DH-13 owner 20/10), same cap/points rules.
money_okp_v0 bigint, p_deposit_bp integer, p_deposit bigint, p_cap_bp integer, p_rate numeric, p_max_points integer, p_points integer, p_points_value bigintbooleanP2-11. Deposit = V0 x rate exactly (never reduced by points); max points = floor(cap x V0 / rate).
my_order_bucketp_order uuidtextdefinerG2I-P3-02, G2I-P6-01. Status chip of the buyer's OWN order (AWAITING_DEPOSIT, AWAITING_PAYMENT, DEPOSITED, SHIPPING, COMPLETED, CANCELLED); every state has one chip. AWAITING_PAYMENT = LOCKED, no explicit COD choice, and an OPEN ONLINE remaining or (no remaining obligation yet) money due by the close. Shared by myOrderCounts and myOrders(bucket:).
new_order_code—text#298. TEMPORARY order code format: PO + 8 random A-Z0-9 (Product format open, NEW-SL-12). The only place the format lives; uniqueness is the orders_issue_code trigger + orders_code_key.
order_activityp_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integer, p_limit integer, p_offset integerTABLE(event_key text, occurred_at timestamptz, category text, action_code text, actor_kind text, actor_account_id uuid, actor_label text, actor_roles text[], source text, from_value text, to_value text, note text, cycle_no integer, shipment_id uuid, actor_basis text, legacy boolean)definerU19-P1-09. Staff order history from the activity log (legacy rows flagged), newest first, server-filtered.
order_activity_countp_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integerbigintdefinerU19-P1-09. Row count of the same filter; null when the order is missing or out of staff scope.
order_activity_viewp_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integerTABLE(event_key text, occurred_at timestamptz, category text, action_code text, actor_kind text, actor_account_id uuid, actor_label text, actor_roles text[], source text, from_value text, to_value text, note text, cycle_no integer, shipment_id uuid, actor_basis text, legacy boolean)definerU19-P1-09. Activity log rows + legacy history rows before each branch cutover, filtered; private.
order_axesp_scope text, p_ids uuid[]TABLE(order_id uuid, order_status text, payment_status text, cancel_reason text, confirmed_at timestamptz, status_version integer, shipping_status text)definerU19-P1-07/P1-08. Stored order/payment/shipping axes, cancel reason, confirmed_at of staff-visible orders (TEAM/ALL).
order_axes_changedp_order uuid, p_from_order text, p_to_order text, p_from_payment text, p_to_payment text, p_actor uuid, p_note textvoiddefinerU19-P1-07 hook, U19-P1-09 body: one ORDER_STATUS and/or PAYMENT activity row per axis change (actor null = SYSTEM).
order_code_ofp_order uuidtextdefiner#298. The order code (orders.code, TEMPORARY format, NEW-SL-12) of one order for a caller who may see that order id: its buyer, an active WEB_ADMIN staff member with a role, or the link owner of its attribution; null otherwise. Only the code is returned. Read beside the order id by the Admin reads (cashbook, COD, vouchers, refunds, payments, shortage, shipments, notifications, Sale team orders, cycle schedule).
order_delivery_labelp_order uuidtextdefiner
order_event_countp_scope text, p_order uuidbigintdefinerP2-14. History row count of a visible order; null when missing or out of scope (API: not_found).
order_eventsp_scope text, p_order uuid, p_limit integer, p_offset integerTABLE(id uuid, order_version integer, event_type text, from_state text, to_state text, source text, actor_account_id uuid, reason text, recorded_at timestamptz)definerP2-14. Order history in stable order (recorded_at, order_version, id); buyer view without actor/reason.
order_excess_depositsp_scope text, p_ids uuid[]TABLE(order_id uuid, reference_code text, excess_vnd bigint, kind text, cycle_no integer, created_at timestamptz)definerPAF-P1-06 (S2, DEC-PAF-08), #479 A. Excess deposit cases (Cọc dư) of staff-visible orders (TEAM/ALL), oldest first: reference code, amount, kind, cycle number (SKIP skip:<cycle> or the COD collected for cod-collect:<collection>, FAILED_DELIVERY failed:<cycle>), created_at.
order_extra_factsp_scope text, p_ids uuid[]TABLE(order_id uuid, approved_at timestamptz, campaign_state text, payable_vnd bigint, cycles_delivered integer, cycles_total integer, method text, cycle_delivering integer)definerU13-P1-03d. approved_at, campaign_state, payable_vnd, cycle progress and method of staff-visible orders (TEAM/ALL). U28-FU-API-C: cycle_delivering = lowest cycle whose stored shipping axis is SHIPPING (Recurring only).
order_factsp_scope text, p_ids uuid[]TABLE(order_id uuid, close_decision text, final_total_vnd bigint, remaining_vnd bigint, excess_vnd bigint, delivery text, payment text, refund text)definerP2-14. Close outcome + delivery/payment/refund labels of visible orders (OWN/TEAM/ALL).
order_historyp_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integer, p_limit integer, p_offset integerTABLE(event_key text, occurred_at timestamptz, category text, action_code text, actor_kind text, actor_account_id uuid, actor_label text, actor_roles text[], source text, from_value text, to_value text, note text, cycle_no integer, shipment_id uuid, actor_basis text)definerU13-P1-03d / FU-06. Staff order history, newest first, server-filtered; actor label/roles SNAPSHOT when stored, else read-time.
order_history_countp_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integerbigintdefinerU13-P1-03d. Row count of the same filter; null when the order is missing or out of staff scope.
order_history_rowsp_order uuidTABLE(event_key text, occurred_at timestamptz, category text, action_code text, actor_account_id uuid, source text, from_value text, to_value text, note text, cycle_no integer, shipment_id uuid, snap_label text, snap_roles text[])definerU13-P1-03d / FU-06. Unscoped union of order state, payment, delivery and buyer points facts + stored actor snapshot; private.
order_history_viewp_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integerTABLE(event_key text, occurred_at timestamptz, category text, action_code text, actor_kind text, actor_account_id uuid, actor_label text, actor_roles text[], source text, from_value text, to_value text, note text, cycle_no integer, shipment_id uuid, actor_basis text)definerU13-P1-03d / FU-06 / FU-10. Filtered history rows; a CUSTOMER actor has no label and no basis (kind only), staff keep name/roles.
order_id_by_codep_code textuuiddefiner#479. The order id of a business order code (orders.code, case-insensitive exact match) for a caller to whom ordering.order_code_of shows that code; null otherwise. Used by the Finance list filters (payments, refund cases).
order_list_countsp_scope text, p_filter jsonbTABLE(campaign_type text, n bigint)definerU19-P2-10. Staff-visible orders per campaign_type under the list filter without the type (tab counts).
order_list_factsp_scope text, p_ids uuid[]TABLE(order_id uuid, final_value_vnd bigint, paid_cash_vnd bigint, campaign_status text)definerU19-P2-10. Final value (MC close total / DK sum of cycle close values; null before the close), paid cash (settled cash obligations, no Pi-Point) and Word campaign status of staff-visible orders (TEAM/ALL).
order_list_pagep_scope text, p_filter jsonb, p_limit integer, p_offset integerTABLE(order_id uuid)definerU19-P2-10. One page of staff-visible order ids (TEAM/ALL), newest first, under the list filter.
order_list_wherep_scope text, p_filter jsonb, p_with_type booleantextU19-P2-10, PAF-P1-06, #479 A. PRIVATE. WHERE clause of the staff order list from the keys of the filter ($2); phone branch for customer readers only; excess (Cọc dư case) and failed_cycle (Mua định kỳ cycle DELIVERY_FAILED, not PAID, not settled by Operations yet).
order_methodp_order uuidtextdefinerU19-P2-21. AdminOrder.method / list filter: payment.remaining_method_of with NOT_CHOSEN read as NONE.
order_point_adjustment_linkp_scope text, p_ids uuid[]TABLE(order_id uuid, buyer_account_id uuid, role text, account_id uuid, available_points integer)definerU19-P2-18. pi_api only: buyer / Referral / Affiliate accounts and Available points from a RETURNED order (TEAM/ALL).
order_reward_entriesp_scope text, p_ids uuid[]TABLE(order_id uuid, entry_id uuid, kind text, recipient_role text, recipient_masked_phone text, is_buyer boolean, cycle_no integer, state text, reason_code text, undecided_ref text, points integer, base_vnd bigint, base_basis text, reward_vnd bigint, rate_bp integer, reward_policy_version text, point_rate_policy_version text, tier_multiplier text, vnd_per_point text, issued_at timestamptz, released_at timestamp with time zone, cancelled_at timestamp with time zone, cancel_end_state text, partial_cancelled_points integer)definerU13-P2-07d. pi_api only: the reward entries (ISSUE commands) of staff-visible orders (TEAM/ALL) with a derived state, a masked recipient and the stored amount evidence; one row with a null entry_id = readable order without an entry; no wallet, balance or total.
order_tierp_policy_version_id uuid, p_campaign_product_id uuid, p_basis bigintTABLE(min_qty integer, max_qty integer, unit_price_vnd bigint)U19-P2-36. Tier of an order line: the [min, max] range holding the basis, or Mốc 1 below its threshold (B006.R07).
orders_log_created—triggerdefinerU19-P1-09. order.created activity row of a submitted order.
own_current_cyclesp_ids uuid[]TABLE(order_id uuid, cycle_no integer, cycle_count integer, value_vnd bigint, due_vnd bigint, cod_vnd bigint, delivers_from_vn text, delivers_to_vn text, state text, shipping_status text)definerG2I-P3-02, G2I-P2-03, G2I-P6-01. Current (first open) cycle of the buyer's OWN Mua định kỳ orders: before the close the first cycle not left empty when ordering, PLANNED; else the smallest COMMITTED cycle not delivered / failed / returned / cancelled / skipped; value, due and COD of ordering.cycle_money (close values once closed).
own_cycles_empty_after_moqp_order uuidinteger[]definerU28-P1-07 (DEC-U28-03). Buyer: the cycles of an OWN Mua định kỳ order left empty after the MOQ (ordering.cycle_empty_after_moq), '{}' when none; NULL before the close or for an order that is not the caller's.
own_order_closed_atp_ids uuid[]TABLE(order_id uuid, closed_at timestamptz)definer#412 O-37F / U-64b. The close instant of the campaign outcome of the caller's OWN Group Buy orders; none before it.
own_order_line_factsp_ids uuid[]TABLE(order_id uuid, line_no integer, image_path text, brand_name text, reached boolean, final_unit_price_vnd bigint, final_tier_no integer)definerG2I-P3-01. Buyer (OWN) facts of each order line: product image path, live brand name, close result of the product (reached, final unit price and Mốc N when reached; null before the close).
own_order_referrersp_ids uuid[]TABLE(order_id uuid, code text, masked_name text)definerG2I-P3-01. ATTRIBUTED Affiliate referrer of the buyer's OWN orders: link code + masked owner name; nothing else.
own_order_reward_entriesp_ids uuid[]TABLE(order_id uuid, entry_id uuid, kind text, cycle_no integer, state text, points integer, issued_at timestamptz, released_at timestamp with time zone, cancelled_at timestamp with time zone)definerG2I-P3-01. The buyer's own reward entries (ORDER_REWARD / ONLINE_BONUS / SPIN, recipient = buyer) of its OWN orders, state derived as ordering.order_reward_entries; no phone, rate, policy version or reason code.
payment_labelp_order uuid, p_decision text, p_remaining biginttextdefinerP2-14. Payment status label from stored obligations/attempts/transactions; UNKNOWN is never paid.
period_money_roles—text[]FU-F1 DEC-OPS-PERIOD-MONEY. WEB_ADMIN roles that read the money of AdminOrder.periods: finance, operations (interim; no payment.read grant).
point_cap_refp_campaign_id uuid, p_campaign_cap_bp integer, p_policy_ref texttextU19-P2-36. Point cap ref of a quote/order: CAMPAIGN:<id> for the per-campaign cap (B064.R07), else the legacy ref.
public_recurring_quote_periodsp_campaign_id uuid, p_window_no integer, p_term integer, p_cells jsonb, p_deposit bigintSETOF jsonbdefinerG2S-P1-01 (DR-09). ordering.recurring_quote_periods with 0 Pi-Point for a guest of the User App: periods 1..Số kỳ of a Recurring campaign the public quote source answers OPEN, from the cells of the priced grid, allocated by ordering.recurring_periods (DEC-U28-01).
public_recurring_quote_sourcep_campaign_id uuidjsonbdefinerG2S-P1-01 (DR-09, BR-MD-11). The OPEN branch of ordering.quote_source for a Recurring campaign shown on the App, for campaign.public_recurring_reader() (a guest included), with packages, windows, minOrderValueVnd, rewardUnit and onSale per product; {status: CLOSED} past its close; null otherwise.
quote_cycle_cellsp_lines jsonb, p_cycle_lines jsonb, p_cycles integerjsonbU28-P2-01. The allocation cells of a quote: every (cycle, line) with its quantity (override, else the line quantity) and the order-time unit price, keyed by the line number (campaign.recurring_allocate_actual input).
quote_cycle_gridp_lines jsonb, p_cycle_lines jsonb, p_cycles integerTABLE(cycle_no integer, campaign_product_id uuid, quantity integer, unit_price_vnd bigint)G2I-P2-01 (G2-06). The (cycle, line) grid of a quote: override of cycle_lines, else the line quantity; with the order-time unit price.
quote_cycle_lines_problemp_lines jsonb, p_cycle_lines jsonb, p_cycles integertextG2I-P2-01 (G2-06). Why a quote's cycle_lines are refused: shape | cycle (outside 1..Số kỳ) | quantity (outside 0..9999, G6-Q3) | product (not a line) | duplicate (cycle, product) | default (equal to the line quantity); NULL = valid.
quote_cycle_valuesp_lines jsonb, p_cycle_lines jsonb, p_cycles integerbigint[]G2I-P2-01 (G2-06). Value of each cycle of a quote: Σ order-time unit price x quantity of the cycle (no division).
quote_first_empty_cyclep_lines jsonb, p_cycle_lines jsonb, p_cycles integerintegerG2S-P1-04 (BR-MD-05, BR-DCD-04, DEC-FS27-MD-EMPTY-CYCLE). The first cycle of a quote grid where every line is 0 (an empty cycle, refused), NULL when none. Call it on validated cycle_lines only.
quote_sourcep_campaign_id uuidjsonbdefiner
read_visiblep_scope text, p_ids uuid[]TABLE(order_id uuid)definerP2-14. Ids of p_ids the actor reads at scope OWN (buyer) / TEAM / ALL; missing and out of scope look the same.
recurring_periodsp_campaign_id uuid, p_window_no integer, p_term integer, p_cells jsonb, p_deposit bigint, p_points_value bigint, p_points integerTABLE(cycle_no integer, recurring_cycle_id uuid, delivers_from timestamptz, delivers_to timestamp with time zone, value_vnd bigint, deposit_vnd bigint, points_value_vnd bigint, due_vnd bigint, rounding_vnd bigint)definerU19-P2-37 / G2I-P2-01 / U28-P2-01 / U28-P2-02. Periods 1..Số kỳ of a Mua định kỳ package from the cells of the order, dated by the window in each month, allocated by campaign.recurring_allocate_actual (DEC-U28-01; a negative COD balance carried back, DEC-U28-12).
recurring_quote_periodsp_campaign_id uuid, p_window_no integer, p_term integer, p_cells jsonb, p_deposit bigint, p_points_value bigint, p_points integerSETOF jsonbdefinerU19-P2-37 / G2I-P2-03 / U28-P2-01. The buyer's quote periods 1..Số kỳ from the cells of the priced grid, allocated by ordering.recurring_periods like the order insert (DEC-U28-01).
recurring_skip_lead_days—integerdefinerU28-P2-04, PAF-P1-02 (DEC-PAF-05). Always 0: a skip has no time lock (only a cycle in a shipment is refused); the System key ordering.recurring_skip_lead_days is not read. Kept for campaign.order_skip_state (skipLeadDays).
recurring_sourcep_basket_id uuidjsonbdefinerP2-13. Own basket as an ordering source (lines + on-sale state, whole schedule while ACTIVE); else NULL.
refund_labelp_order uuid, p_state text, p_points integertextdefinerP2-14. Refund status of a CANCELLED order; REFUNDED only after every capture is refunded (+ points reversed).
set_cycle_axesp_cycle uuid, p_order_status text, p_payment_status text, p_shipping_status text, p_actor uuid, p_note textintegerdefinerU19-P1-08. Writes the axes of one cycle (null = keep, status_version + 1, idempotent); one log row per moved axis.
set_order_axesp_order uuid, p_order_status text, p_payment_status text, p_cancel_reason text, p_actor uuidintegerdefinerU19-P1-07. Writes the order/payment axes (null = keep) as one axis-only update, status_version + 1; idempotent.
set_order_shippingp_order uuid, p_status text, p_actor uuid, p_note textintegerdefinerU19-P1-08. Writes orders.shipping_status (axis-only, status_version + 1, idempotent) and logs one SHIPPING row.
settle_failed_delivery_cyclep_order uuid, p_cycle_no integer, p_expected_version integer, p_note text, p_source_id textjsonbdefiner#479 A (Product 11/11 Q2, owner 11/11 decisions 2-4). Operations (order.cancel, not the buyer) settles a Mua định kỳ cycle whose delivery failed for good and is not paid: one order_cycle_failed_deliveries row; skips + failed cycles <= n of the package -> CONTINUED (the cycle Đã hủy, its deposit share spread again as a skip, its price-ratio share of the buyer's and the Affiliate reward cut: cancelled while Pending, clawed back once Available; the reward milestone said again when the first actual cycle was already paid; its Pi-Point lost); past n -> ORDER_CANCELLED (ordering.stop_recurring_order: the order Đã hủy DELIVERY_FAILED + Mất cọc, its online payment closed, the share of every cycle not delivered cut, the delivered keep theirs). Order version checked, obligations locked NOWAIT (failed_delivery_payment_busy), idempotent on p_source_id.
shortage_cancelled_cycle_valuep_order uuid, p_cycle integerbigintdefiner
shortage_cancelled_in_cyclep_order uuid, p_campaign_product uuid, p_cycle integerintegerdefiner
shortage_cancelled_unitsp_order uuid, p_campaign_product uuidintegerdefiner
shortage_cancelled_valuep_order uuidbigintdefiner
skips_usedp_order uuidintegerG2I-P2-01 (G2-06, G6-Q2, D13). Cycles counted against the package skipMax: ACTIVE (REQUESTED) skips plus cycles left empty at order time, each cycle once.
staff_all_reader_roles—text[]P2-14 / FU-OPSGRANTS. WEB_ADMIN roles reading every order (scope ALL): operations, admin (matrix OPS-02; DEC-OPS-ADMIN-ALL).
staff_order_countp_scope text, p_state text, p_type text, p_campaign uuid, p_customer uuid, p_from timestamp with time zone, p_to timestamp with time zone, p_as_of timestamp with time zone, p_order uuid, p_name textbigintdefinerP2-14. Total of the adminOrders filter (same scope and filter as ordering.staff_orders).
staff_order_count_extp_scope text, p_state text, p_type text, p_campaign uuid, p_customer uuid, p_from timestamp with time zone, p_to timestamp with time zone, p_as_of timestamp with time zone, p_order uuid, p_name text, p_approved_from timestamp with time zone, p_approved_to timestamp with time zone, p_payment text, p_delivery text, p_campaign_state text, p_method textbigintdefiner
staff_order_id_by_codep_scope text, p_code textuuiddefiner#298. Staff-visible (TEAM/ALL, read_visible) order with this code, case-insensitive exact match; null otherwise.
staff_order_idsp_scope text, p_state text, p_type text, p_campaign uuid, p_customer uuid, p_from timestamp with time zone, p_to timestamp with time zone, p_as_of timestamp with time zone, p_order uuid, p_name textTABLE(order_id uuid, created_at timestamptz)definerP2-14. Staff order filter (A-OD-01/08): scope + AND of state/type/campaign/customer/date/as-of/id/name.
staff_order_ids_extp_scope text, p_state text, p_type text, p_campaign uuid, p_customer uuid, p_from timestamp with time zone, p_to timestamp with time zone, p_as_of timestamp with time zone, p_order uuid, p_name text, p_approved_from timestamp with time zone, p_approved_to timestamp with time zone, p_payment text, p_delivery text, p_campaign_state text, p_method textTABLE(order_id uuid, created_at timestamptz)definerU13-P1-03d. ordering.staff_order_ids AND approval-date / payment / delivery / campaign-state / method filters.
staff_order_linesp_scope text, p_ids uuid[]TABLE(order_id uuid, line_no integer, campaign_product_id uuid, product_id uuid, sku_snapshot text, name_snapshot text, quantity integer, tier_min_qty integer, tier_max_qty integer, unit_price_vnd bigint, line_v0_vnd bigint, units bigint)definerP2-14, G2I-P2-02. Order line snapshots of staff-visible orders (TEAM/ALL scope); quantity = per cycle (default), units = over every cycle.
staff_order_page_extp_scope text, p_state text, p_type text, p_campaign uuid, p_customer uuid, p_from timestamp with time zone, p_to timestamp with time zone, p_as_of timestamp with time zone, p_order uuid, p_name text, p_approved_from timestamp with time zone, p_approved_to timestamp with time zone, p_payment text, p_delivery text, p_campaign_state text, p_method text, p_limit integer, p_offset integerTABLE(order_id uuid)definer
staff_order_periodsp_scope text, p_ids uuid[]TABLE(order_id uuid, cycle_no integer, delivers_from timestamptz, delivers_to timestamp with time zone, obligation_vnd bigint, paid_vnd bigint, remaining_vnd bigint)definerFU-AC-TRIAGE L5 A-OD-02 AC02, FU-F1 DEC-OPS-PERIOD-MONEY. Periods of staff-visible orders (TEAM/ALL); money NULL unless ordering.actor_reads_period_money().
staff_ordersp_scope text, p_state text, p_type text, p_campaign uuid, p_customer uuid, p_from timestamp with time zone, p_to timestamp with time zone, p_as_of timestamp with time zone, p_order uuid, p_name text, p_limit integer, p_offset integerTABLE(id uuid, owner_account_id uuid, quote_id uuid, campaign_id uuid, campaign_type text, campaign_version integer, policy_version_id uuid, committed_cycle_count integer, v0_vnd bigint, deposit_rate_bp integer, deposit_vnd bigint, point_cap_bp integer, point_rate_snapshot_vnd numeric, point_rate_policy_version text, max_points integer, points_used integer, points_value_vnd bigint, milestone_id uuid, milestone_no integer, milestone_delivers_from timestamptz, milestone_delivers_to timestamp with time zone, milestone_reward_point_bp integer, ship_recipient_name text, recipient_phone_masked text, ship_province text, ship_district text, ship_ward text, ship_address_type text, state text, quoted_at timestamp with time zone, state_changed_at timestamp with time zone, created_at timestamp with time zone, updated_at timestamp with time zone, version integer, customer_name text, customer_phone_masked text)definerP2-14. adminOrders page (TEAM/ALL scope), newest first (created_at, id); phones masked, street line withheld.
staff_orders_by_idsp_scope text, p_ids uuid[]TABLE(id uuid, owner_account_id uuid, quote_id uuid, campaign_id uuid, campaign_type text, campaign_version integer, policy_version_id uuid, committed_cycle_count integer, v0_vnd bigint, deposit_rate_bp integer, deposit_vnd bigint, point_cap_bp integer, point_rate_snapshot_vnd numeric, point_rate_policy_version text, max_points integer, points_used integer, points_value_vnd bigint, milestone_id uuid, milestone_no integer, milestone_delivers_from timestamptz, milestone_delivers_to timestamp with time zone, milestone_reward_point_bp integer, ship_recipient_name text, recipient_phone_masked text, ship_province text, ship_district text, ship_ward text, ship_address_type text, state text, quoted_at timestamp with time zone, state_changed_at timestamp with time zone, created_at timestamp with time zone, updated_at timestamp with time zone, version integer, customer_name text, customer_phone_masked text, code text)definerU13-P1-03d. Rows of ordering.staff_orders for given ids (TEAM/ALL), masked the same way, newest first. #298: + code.
staff_phonep_phone text, p_full booleantextU19-P2-11. National phone for a customer reader, customer.mask_phone otherwise.
staff_scope_okp_scope textbooleandefinerP2-14. Actor qualifies for TEAM (live order.read TEAM grant, M-02) or ALL (staff_all_reader_roles, empty).
states—text[]
stop_recurring_orderp_order_id uuid, p_source text, p_causation textbooleandefinerU19-P2-24, #479 A (Product 11/11 Q2, DEC-U19-SKIP-OVERLIMIT-FORFEIT reused; owner 11/11 decisions 1 and 3). Recurring order past "Được bỏ qua tối đa" (skips + cycles settled as failed deliveries), or ended within n with no cycle delivered: Đã hủy (DELIVERY_FAILED) + Mất cọc (state FORFEITED), cycles not handed over CANCELLED, their COD cancelled, the online payment closed (payment.recurring_stop_online), the reward share of the cancelled, skipped and failed cycles cut (pipoint_reward.failed_delivery_cut), outbox order.failed (cause FAILED_DELIVERY, rewardKept = a cycle delivered or on the road keeps its share), no refund; idempotent (false when not LOCKED).
team_order_ids—TABLE(order_id uuid)definerP2-14. Orders attributed (P4-11) to an APP_SALE link owner whose CURRENT team the actor manages (M-02).
team_sale_ids—uuid[]definerFU-PERF-A. APP_SALE accounts whose CURRENT team is one the actor manages (computed once per statement).
tier_nop_policy_version uuid, p_campaign_product uuid, p_min_qty integerintegerU19-P2-11. 1-based position of a price tier (by min_qty) in a policy version; the Moc N of the order detail.
transition_allowedp_from text, p_to textbooleanP2-11 / #388 O3. Order state machine (DEPOSIT_PENDING -> PLACED|DEPOSIT_FAILED|CANCELLED; PLACED -> LOCKED|CANCELLED; LOCKED -> FULFILLED|CANCELLED|FORFEITED).
transition_axesp_from text, p_to text, p_reason text, p_payment text, OUT order_status text, OUT payment_status text, OUT cancel_reason textrecordU19-P1-07 / G1S-P1-05. Order/payment axes and cancel reason of one commitment transition (pure). DEPOSIT_FAILED: deposit_unpaid_at_close -> DEPOSIT_UNPAID_AT_CLOSE, else DEPOSIT_TIMEOUT. ASSUME-01/02 labelled.

schema tier ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
active_rankp_account uuid, p_audience text, p_at timestamp with time zonebigint
actor_audience—text
actor_canp_action textbooleanP4-08. Acting principal may write Tier configuration (ADT-01) right now.
actor_can_read—booleandefiner
actor_is_member—booleandefiner
append_assignment_eventp_assignment uuid, p_kind text, p_account uuid, p_audience text, p_tier uuid, p_previous uuid, p_evaluation uuid, p_at timestamp with time zone, p_source_event uuid, p_correlation textvoid
audience_appp_audience texttext
backfill_activatep_run uuid, p_version integer, p_correlation textjsonbU28-P3-09 DEC-U28-06. Owner only. Preflight + set version 1 (MIGRATION) + items + the MIGRATION re-evaluation job in one transaction; an abort reason fails the run and writes nothing else.
backfill_fingerprint—jsonbU28-P3-09. Owner only. Count + hash of the tables the backfill must leave unchanged (reconcile).
backfill_mappingp_at timestamp with time zoneTABLE(definition_id uuid, version_id uuid, is_standard boolean, name text, rank_threshold bigint, coefficient numeric, coefficient_basis text, mission_count integer)U28-P3-09 DEC-U28-06. Owner only. Legacy USER ladder in force at t mapped to set items (coefficient by the all-6-activities-equal rule, else NULL).
backfill_reconcile—jsonbU28-P3-09. Owner only. Post-activation checks: ladder = legacy, one Standard at 0, job state, moved and rank-mismatched customers.
backfill_reportp_at timestamp with time zonejsonbU28-P3-09. Owner only. Read-only dry-run report of the customer Tier backfill (abort reasons and lists).
backfill_startp_correlation textTABLE(run_id uuid, run_version integer, phase text, status text, attempts integer, set_version_id uuid)U28-P3-09. Owner only. Opens / resumes / retries the BACKFILL run row; nothing once the set is in force.
benefit_policy_in_force—boolean
check_set_rulesp_version uuidvoid
check_set_versionp_version uuidvoid
create_membership_tierp_expected integer, p_name text, p_threshold bigint, p_coefficient numeric, p_benefit text, p_correlation textjsonbdefiner
customer_ladderp_at timestamp with time zoneTABLE(definition_id uuid, is_standard boolean, name text, rank_threshold bigint, coefficient numeric, benefit_description text, created_at timestamptz, updated_at timestamp with time zone, set_version integer, set_updated_at timestamp with time zone)U28-P3-08. Customer Tier ladder at an instant (dual read): set version items, else the legacy USER versions in force with the DEC-U28-06 coefficient mapping and set_version 0. Internal.
customer_set_active—booleandefinerU28-P3-03. True once the customer Tier set is in force: saveTierVersion / publishTierVersion refuse USER.
customer_tiers_atp_at timestamp with time zone, p_account uuidTABLE(account_id uuid, definition_id uuid, reached_at timestamptz, joined_at timestamp with time zone)U28-P3-08. Current Tier and reachedAt of ACTIVE customers: new history head, else legacy head, else Standard. Internal.
delete_membership_tierp_expected integer, p_tier uuid, p_correlation textjsonbdefiner
evaluate_customerp_account uuid, p_source text, p_at timestamp with time zone, p_source_id uuid, p_source_ref text, p_source_points bigint, p_reevaluation uuid, p_correlation textTABLE(status text, history_id uuid, reason text, source text, from_definition_id uuid, to_definition_id uuid, effective_rank bigint, reached_at timestamptz, set_version_id uuid)definerU28-P3-06. pi_worker only. Customer Tier = highest threshold <= effective rank in the set version in force (points only, any number of steps); one member_tier_history row per change, nothing when the Tier is kept.
evaluate_for_eventp_event_id uuid, p_aggregate_type text, p_aggregate_id text, p_correlation textTABLE(status text, evaluation_id uuid, outcome text, decision text, assignment_id uuid, tier_version_id uuid)definer
evaluate_memberp_account uuid, p_audience text, p_trigger text, p_at timestamp with time zone, p_source_event uuid, p_correlation textTABLE(status text, evaluation_id uuid, outcome text, decision text, assignment_id uuid, tier_version_id uuid)definerP4-09. pi_worker only. One evidence row and at most one one-step Tier movement per (member, instant); monthly demotion at VN day 1 00:00; unknown inputs record WAITING_FOR_DATA/POLICY_UNDECIDED and move nobody. U28-P3-06: a customer (USER) under a customer Tier set version is answered by tier.evaluate_customer (points only).
evaluate_rank_entryp_request uuid, p_correlation textTABLE(status text, history_id uuid)definerU28-P3-07. pi_worker only. "Xét ngay": the customer Tier evaluation of one rank entry (lot / SIGNED debit) in the rank-lot consumer transaction, one decision per source request; NOT_APPLICABLE / NO_SET outside the new model.
expire_due_lotsp_limit integerintegerdefiner
list_membersp_audience text, p_definition uuid, p_keyword text, p_limit integer, p_offset integerTABLE(account_id uuid, phone_masked text, tier_version_id uuid, tier_definition_id uuid, assignment_id uuid, assigned_at timestamptz, active_rank bigint, total bigint)definerP4-08 A-TIER-02, U28-P3-08. One page of ACTIVE members of a Tier system with current Tier (Standard by default), active rank and masked phone; USER under a set version reads the new model (tier_version_id NULL); refused unless the caller is a TIR-02 reader. total is the unpaged count.
lock_tier_setp_expected_version integertier_set_versions
member_activep_account uuid, p_audience text, p_at timestamp with time zoneboolean
member_history_headp_account uuid, p_at timestamp with time zoneSETOF member_tier_historyU28-P3-01. Customer's new-model Tier history row in force at the instant (current Tier, reachedAt).
member_progress—TABLE(current_version_id uuid, next_version_id uuid, as_of timestamptz, rank_points bigint, threshold bigint, rank_ok boolean, mission_status text, outcome text, missions jsonb, next_review_at timestamp with time zone, current_definition_id uuid, next_definition_id uuid, set_ladder jsonb, held_ref uuid, held_at timestamp with time zone)definerP5-S15, restated U28-P7-03. The caller's progress toward the next Tier at statement time. USER under a set version: the set ladder in set_ladder, rank-only comparison (DEC-U28-06), daily review; otherwise the legacy comparison of the P4-09 evaluator. No row for a non-member. Reads only.
membership_customersp_account uuid, p_definition uuid, p_keyword text, p_limit integer, p_offset integer, p_phone_search booleanTABLE(account_id uuid, customer_code text, full_name text, phone text, phone_masked text, tier_id uuid, tier_name text, tier_is_standard boolean, tier_deleted boolean, tier_threshold bigint, reached_at timestamptz, effective_rank bigint, expiring_points bigint, expiring_at timestamp with time zone, total bigint, rank_ledger_sum bigint)definerU28-P3-08 HT-US-07/08/09, U28-P7-04 DEC-U28-13, U28-FU-API-A. Customers with Tier, reachedAt, effective rank (the signed ledger rank_ledger_sum clamped at 0, BR-HT-11; the signed sum is returned too) and soonest-expiring credits; full phone only for customer readers; the keyword reaches the full phone only with p_phone_search AND a customer reader (B-4), else only the visible mask; TIR-02 readers only. One row with null account and the total when the page is empty.
membership_set_for_writep_expected integer, p_tier uuidjsonbdefiner
membership_tier_historyp_account uuid, p_limit integer, p_offset integerTABLE(id uuid, occurred_at timestamptz, reason text, source text, from_id uuid, from_name text, from_standard boolean, from_deleted boolean, to_id uuid, to_name text, to_standard boolean, to_deleted boolean, source_points bigint, source_ref text, total bigint)definerU28-P3-08 HT-US-10 (+ U28-P3-09 DEC-U28-14 synthesized SIGN_UP row). Customer Tier history (new model merged with legacy USER assignments), names at record time, deleted = not in the ladder now; TIR-02 readers only.
membership_tier_previewp_kind text, p_tier uuid, p_threshold bigintjsonbdefiner
membership_tiersp_counts booleanTABLE(definition_id uuid, is_standard boolean, name text, rank_threshold bigint, coefficient numeric, benefit_description text, created_at timestamptz, updated_at timestamp with time zone, tier_position integer, tier_count integer, customer_count bigint, set_version integer, set_updated_at timestamp with time zone)definerU28-P3-08 HT-US-01/03. Customer Tier ladder with position, count and customers per Tier; TIR-02 readers only.
mission_checkp_account uuid, p_audience text, p_version uuid, p_at timestamp with time zoneTABLE(status text, detail jsonb)
mission_is_effectivep_mission uuidboolean
multiplier_actorp_kind textboolean
multiplier_change_guard—triggerdefiner
multiplier_checker_roles—text[]FU-TIERAPPROVE mirror of matrix ADT-06 tier_multiplier.decide (WEB_ADMIN business_owner, CHECKER, MFA, PROPOSED).
multiplier_gate—trigger
multiplier_jsonp_version uuidjsonb
multiplier_previousp_version uuidjsonb
next_review_instantp_at timestamp with time zonetimestamptz
next_review_instantp_at timestamp with time zone, p_audience texttimestamptzU28-P7-03. Next Tier review instant after p_at: daily VN 00:00 for USER once a customer set version is in force (DEC-U28-08), else the monthly VN day 1 00:00 (tier.next_review_instant(timestamptz)).
open_set_for_writep_expected integertier_set_versions
order_problemp_definition uuid, p_audience text, p_order integer, p_threshold bigint, p_from timestamp with time zone, p_to timestamp with time zonetext
perform_sale_transferp_application uuid, p_correlation texttextdefinerFU-866. Idempotent User -> Sale transfer of one application (carry valid lots, ROLE_TRANSFER, evaluate); no grant: called by tier.run_sale_transfers and tier.sale_transition_retry only.
publish_guard—trigger
rank_expires_atp_anchor timestamp with time zone, p_months integer, p_zone texttimestamptz
rank_ledger_sump_account uuid, p_audience text, p_at timestamp with time zonebigintU28-P3-04. Signed rank ledger at an instant: lots valid at t (minus legacy LOT_FEFO deductions) minus SIGNED debits in force at t. May be negative; tier.active_rank clamps it at 0 (BR-HT-11).
rank_point_historyp_account uuid, p_limit integer, p_offset integerTABLE(id uuid, recorded_at timestamptz, source text, ref_kind text, ref_id uuid, ref_code text, points bigint, expires_at timestamp with time zone, status text, total bigint)definerU28-P3-08 HT-US-11. Signed rank entries (lots +, USER debits −) with status and source reference; debit expiry as stored (NULL, GAP-HT-V1-04); TIR-02 readers only.
rank_policy_atp_at timestamp with time zonerank_policy_versions
reader_roles—text[]P4-07 mirror of matrix TIR-02 tier.read (WEB_ADMIN, PROPOSED).
record_evaluationp_account uuid, p_audience text, p_trigger text, p_at timestamp with time zone, p_source_event uuid, p_correlation text, p_tested uuid, p_held uuid, p_head uuid, p_outcome text, p_decision text, p_target uuid, p_rank bigint, p_threshold bigint, p_evidence jsonbTABLE(evaluation_id uuid, assignment_id uuid)P4-09. Internal writer: one immutable evaluation row, and for a movement the chain row (+ INITIAL) and its event.
record_rank_debitp_event_id uuid, p_request_id uuid, p_correlation_id textTABLE(outcome text, debit_id uuid, allocated_points integer, unallocated_points integer)definerU28-P3-04. pi_worker only. One rank debit per accepted ADJUST DEBIT request: a customer debit is one SIGNED entry (no lot allocation, expiry open per GAP-HT-V1-04); a Sale debit is allocated to the lots valid at its instant, soonest-expiring first (LOT_FEFO, unchanged).
record_rank_lotp_event_id uuid, p_request_id uuid, p_correlation_id textTABLE(outcome text, lot_id uuid, policy_version_id uuid, anchor_at timestamptz)definerP4-07. pi_worker only. One rank lot per Available/posted point command, expiry from the policy version in force at the anchor time (VN calendar months). Duplicate event or request: no second lot.
reevaluation_advancep_job uuid, p_version integer, p_checkpoint text, p_processed integer, p_changed integer, p_done boolean, p_failure textintegerdefinerU28-P3-07. pi_worker only. CAS progress / checkpoint / COMPLETED / FAILED of one job; completing the latest job completes the older RUNNING ones it supersedes. Null = fenced.
reevaluation_candidatesp_after uuid, p_limit integerTABLE(account_id uuid)definerU28-P3-07. pi_worker only. Keyset page of the customers a full re-evaluation evaluates (active APP_USER members).
reevaluation_claimp_max_attempts integerTABLE(id uuid, version integer, reason text, checkpoint_key text, correlation_id text, attempts integer, total_count integer)definerU28-P3-07. pi_worker only. The latest re-evaluation job to work on (FAILED -> RUNNING retry under max attempts, total fixed on first claim); nothing when it is COMPLETED or out of attempts.
reevaluation_jsonp_job uuidjsonb
review_candidatesp_at timestamp with time zone, p_after_account uuid, p_after_audience text, p_limit integerTABLE(account_id uuid, audience text)definer
review_memberp_account uuid, p_audience text, p_at timestamp with time zone, p_correlation textTABLE(status text)definerU28-P3-07. pi_worker only. One member of the daily review: USER under a set version -> RANK_EXPIRED evaluation; otherwise the legacy MONTHLY_REVIEW on VN day 1, NOT_DUE on other days.
run_sale_transfersp_limit integer, p_correlation textTABLE(application_id uuid, status text)definer
sale_transition—TABLE(application_id uuid, application_source text, application_state text, status text, attempts integer, failure_code text, from_tier jsonb, to_tier jsonb, carried_rank bigint, carried_lots integer, completed_at timestamptz, acknowledged_at timestamp with time zone, evaluation_outcome text, evaluation_decision text)definer
sale_transition_acknowledge—booleandefiner
sale_transition_retryp_correlation texttextdefiner
save_rank_policyp_expected_version integer, p_expiry_months integerrank_policy_versionsdefinerU28-P3-05 (DEC-U28-08). tier.write only. CAS on the version in force, appends N effective now(); existing rank lots keep their expiry, only credits anchored from now on use the new N.
set_customer_countp_definition uuid, p_at timestamp with time zoneinteger
set_items_atp_at timestamp with time zoneSETOF tier_set_itemsU28-P3-01. Tiers of the customer set version in force at the instant, threshold ascending.
set_tier_jsonp_set uuid, p_definition uuidjsonb
set_tier_missingp_tier uuidvoid
set_version_atp_at timestamp with time zoneSETOF tier_set_versionsU28-P3-01. Customer Tier set version in force at the instant; no row = legacy path (B2 dual read).
test_tierp_account uuid, p_audience text, p_version uuid, p_at timestamp with time zoneTABLE(rank_points bigint, threshold bigint, rank_ok boolean, mission_status text, outcome text, evidence jsonb)P4-09. Rank AND every required Mission for one Tier version at one instant; WAITING_FOR_DATA when the Mission half is unknown (GAP-87), never a silent pass or failure.
update_membership_tierp_expected integer, p_tier uuid, p_name text, p_threshold bigint, p_coefficient numeric, p_benefit text, p_correlation textjsonbdefiner
versions_in_forcep_audience text, p_at timestamp with time zoneSETOF tier_versions
write_set_versionp_open tier_set_versions, p_kind text, p_tier uuid, p_name text, p_threshold bigint, p_coefficient numeric, p_benefit text, p_reason text, p_correlation textjsonb
writer_roles—text[]P4-08 mirror of matrix ADT-01 tier.write (WEB_ADMIN, PROPOSED).

schema fulfillment ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
actor_is_operator—booleanP2-17. Acting principal holds a shipment operator role in WEB_ADMIN right now (ACTIVE account/membership).
apply_eventp_shipment uuid, p_kind text, p_to text, p_issue text, p_source text, p_source_event_id text, p_actor uuid, p_carrier text, p_hash text, p_occurred timestamp with time zone, p_reason text, p_evidence uuid, p_expected_version integer, p_strict booleanjsonbdefiner
apply_exceptionp_shipment uuid, p_link uuid, p_kind text, p_issue text, p_source text, p_source_event_id text, p_actor uuid, p_carrier text, p_hash text, p_occurred timestamp with time zone, p_reason text, p_evidence uuid, p_expected_version integer, p_strict booleanjsonbdefiner
candidate_address_changesp_orders uuid[]TABLE(order_id uuid, address_updated_at timestamptz)definerU28-FU-API-A. When the buyer last changed the delivery address of the given orders (orders.address_updated_at; changed ones only). Shipment operators only (the fulfillment.ship_candidates gate).
cod_preview_axesp_orders uuid[]jsonbdefinerU28-FU-API-B. Order and cycle axes (order / payment status) keyed <order>:<cycle | 0>, read before and inside the dry run of fulfillment.shipment_cod_collect_preview. Internal.
cod_return_jsonp_case uuidjsonbdefiner
cod_return_refund_casep_case uuiduuiddefiner
cod_signals—text[]
complete_recurring_orderp_order uuid, p_cause textbooleandefinerU19-P2-30, #479 A. Recurring order whose every cycle ended: with a Thanh cong cycle SUCCESS, or PARTIAL_SUCCESS when a cycle was cancelled for a failed delivery, + FULFILLED + order.fulfilled + Mission once; without one but with a cycle settled as a failed delivery (within n, legacy order without a package) stopped as past n (ordering.stop_recurring_order: Đã hủy DELIVERY_FAILED + Mất cọc, order.failed; owner 11/11 decision 1); FORFEITED never; a failed cycle not settled yet is not ended.
delivery_attempt_countp_shipment uuidintegerdefinerU19-P2-32 (ASSUME-05). Delivery attempts of a shipment: moves into WAITING_REDELIVERY / DELIVERY_FAILED + legacy ISSUE facts kept in SHIPPING. Display only, no limit.
delivery_attempts_ofp_shipment uuidintegerU28-FU-API-A. ASSUME-05 formula of the delivery attempts of a shipment (moves into WAITING_REDELIVERY / DELIVERY_FAILED + legacy ISSUE facts kept in SHIPPING). Internal: called by definer readers only.
exception_cod_signalp_shipment uuid, p_link uuid, p_kind text, p_issue texttextdefiner
exception_kinds—text[]
exception_statusp_occurred timestamp with time zone, p_state text, p_delivered_at timestamp with time zonetextP2-21. Pure read status of an exception from the shipment state: OPEN | RETURNED | RESOLVED_BY_DELIVERY | LATE_AFTER_DELIVERY (order independent; a delivered shipment never regresses).
fulfill_ordersp_shipment uuid, p_event uuidjsonbdefinerU19-P2-30. DELIVERED shipment: Group Buy LOCKED -> FULFILLED; Recurring cycle -> SUCCESS, order completed by complete_recurring_order when every cycle ended. Independent of the COD collection (Word B186.R02).
group_shipmentp_carrier_code text, p_carrier_ref text, p_expected_on date, p_handed_over_at timestamp with time zone, p_evidence_media_id uuid, p_items jsonb, p_source_event_id textjsonbdefinerP2-17 + L6. Operators only: atomically creates one shipment of LOCKED, ready (paid online or COD) orders/committed cycles sharing one schedule source and delivery snapshot, its links and the CREATED event.
group_shipmentp_carrier_code text, p_carrier_ref text, p_expected_on date, p_handed_over_at timestamp with time zone, p_evidence_media_id uuid, p_items jsonb, p_source_event_id text, p_package jsonbjsonbdefinerU19-P2-29, G2I-P2-02, #400. Operators only: one atomic call creates the shipment of LOCKED orders/committed cycles with the same recipient + phone + address + delivery date (a cycle dated by its order period), locks their payment method (unpaid online -> fixed COD), its links (the goods of the unit: quantity of the cycle, products that met their MOQ only; a cycle without goods or not WAITING_PACKING is refused), and with a package the handover (carrier PIDEAL, request default VIEW_NO_TRY, date default the one-day window, code, COD snapshot, locked modes, PACKING). Replay by source event id returns the stored result.
handover_selection_takenp_items jsonbjsonbdefinerU28-FU-API-B. For the units a refused handoverShipment named: the shipment holding each now (code), when the unit was linked and the actor_label snapshot of the shipment's first event (who). Read-only; operator / shipment.create.
issue_codes—text[]
link_factsp_shipments uuid[]TABLE(link_id uuid, shipment_id uuid, order_id uuid, cycle_no integer, order_state text, cod_due_vnd bigint, resolution_state text)definerFU-AC-TRIAGE L6. Operators only: per grouped order/cycle its order state, COD still to collect and resolution state.
link_payment_modesp_shipments uuid[]TABLE(link_id uuid, payment_mode text)definerU13-P2-08d. Operators only: payment mode (COD/ONLINE) of each link of the given shipments.
lock_carrier_shipmentp_carrier_code text, p_carrier_ref textvoiddefiner
lock_cod_shipmentsp_cod uuidvoiddefiner
lock_unit_methodp_order uuid, p_order_cycle uuid, p_cycle_no integer, p_actor uuid, p_source textjsonbdefinerU19-P2-22, U28-P2-03, U28-FU-REWARD (B013.R11, DEC-U28-04, DEC-U28-01/12). Handover only: closes an unpaid (or stale switched) online remaining, opens the fixed COD (Recurring: per owing cycle without one, versioned source, amount of payment.recurring_cycle_cod: ⌈due⌉ to 1,000đ balanced on the last cycle still to collect for an ONLINE close), logs payment.method_locked; returns {orderId, cycleNo, from, mode, codDueVnd, converted}.
lock_unit_paymentsp_order uuidvoiddefiner
next_shipment_code—textdefinerU13-P1-04d. Next internal shipment code (placeholder format, GAP-VD-V1-01). The only place of the code shape; owner-run via the column default.
on_unit_delivery_failedp_link uuid, p_event uuidvoiddefinerU19-P2-26 hook, U19-P2-33 body (DH-US-14): a shipment moved to DELIVERY_FAILED -> ordering.apply_no_receive, once per live link.
on_unit_returnedp_link uuid, p_event uuidvoiddefinerU19-P2-26 hook, U19-P2-18 body (DH-US-09): a shipment moved to RETURNED -> ordering.apply_return, once per live link.
operator_roles—text[]P2-17 / FU-OPSGRANTS. WEB_ADMIN roles that operate shipments: operations, admin (matrix O-02, OPS-02, ALL; DEC-OPS-SCOPE, DEC-OPS-ADMIN-ALL).
order_cycles_complete_order—triggerdefiner
order_progressp_scope text, p_order uuidTABLE(cycle_no integer, cycle_state text, shipment_id uuid, carrier_code text, carrier_ref text, delivery text, expected_on date, last_event_at timestamptz, delivered_at timestamp with time zone, collection text, attention boolean)definerP2-21. One row per delivery unit (Group Buy order / Recurring cycle) copied from the shipment; never inferred; TEAM gets no carrier reference and no COD collection.
order_progress_headp_scope text, p_order uuidTABLE(order_id uuid, campaign_type text, order_state text, committed_cycles integer)definerP2-21. Header of a visible order (campaign type, state, committed delivery units); none when missing/out of scope.
reapply_pendingp_shipment uuidjsonbdefinerFU-DEF141. Applies retained OUT_OF_ORDER carrier/system facts that became legal, earliest occurred_at first (GAP-1600).
record_cod_returnp_shipment uuid, p_order uuid, p_reason text, p_evidence uuid[], p_source_event_id textjsonbdefinerFU-OIFF01 + FU-CODREFUND. Operators only: records the RETURN case of one Order whose COD was refused (shipment RETURNED, stored refusal fact, COD uncollected): Order LOCKED -> CANCELLED, COD obligation cancelled, and one manual refund case (deposit cash legs + points reversal legs) for Finance, DEC-COD-REFUSAL-REFUND.
record_delivery_attemptp_shipment uuid, p_expected_version integer, p_issue text, p_occurred timestamp with time zone, p_note text, p_evidence uuid, p_source_event_id textjsonbdefiner
record_external_eventp_source text, p_carrier_code text, p_carrier_ref text, p_source_event_id text, p_to text, p_issue text, p_occurred timestamp with time zone, p_payload_hash textjsonbdefiner
record_external_exceptionp_source text, p_carrier_code text, p_carrier_ref text, p_source_event_id text, p_kind text, p_issue text, p_occurred timestamp with time zone, p_payload_hash textjsonbdefiner
record_operator_eventp_shipment uuid, p_expected_version integer, p_to text, p_issue text, p_occurred timestamp with time zone, p_reason text, p_evidence uuid, p_source_event_id textjsonbdefiner
record_operator_exceptionp_shipment uuid, p_expected_version integer, p_order uuid, p_cycle integer, p_kind text, p_issue text, p_occurred timestamp with time zone, p_reason text, p_evidence uuid, p_source_event_id textjsonbdefiner
recurring_order_endedp_order uuidbooleandefinerU19-P2-30. Every committed cycle ended (SUCCESS / FAILED / CANCELLED / RETURNED, skipped, or cancelled for shortage); a PENDING_DECISION cycle (GAP-OPS-02) has not ended.
release_deliveredp_shipment uuidjsonbdefinerU19-P2-30. No-op (nothing is held for the COD any more); kept for the deploy window, dropped by U19-P4-02.
resolve_cancelled_itemsp_shipment uuid, p_expected_version integer, p_items jsonb, p_reason text, p_source_event_id textjsonbdefinerFU-AC-TRIAGE L6. pi_api operators: records that the lines of cancelled orders are removed from a shipment before handover.
search_foldp_text texttextdefinerU19-P2-27. Lower case, diacritics removed (unaccent; Đ -> d): the key of the shipment recipient-name search.
set_shipment_contactp_shipment uuid, p_name text, p_phone text, p_slot text, p_clear text[]jsonbdefinerG2I-P3-03 (O8, E9). Driver name / phone / delivery slot of a shipment, only in the transaction of its status update.
ship_candidate_days—SETOF datedefinerU19-P2-28 (FS-VD-03-02). Operators only: distinct VN delivery days (window start) of every step 1 unit, ascending.
ship_candidate_units—TABLE(u_order uuid, u_cycle_no integer, u_cycle uuid, u_campaign uuid, u_type text, u_from timestamptz, u_to timestamp with time zone, u_skey text)definerU19-P2-29. Internal: step 1 units - LOCKED Group Buy orders and valid Recurring cycles in WAITING_PACKING (stored axis), not skipped, without a shipment link, not the actor's own; a cycle's window is its order period (schedule row if none).
ship_candidatesp_date date, p_type text, p_limit integer, p_offset integerTABLE(total_groups bigint, group_no bigint, group_key text, order_id uuid, cycle_no integer, campaign_id uuid, campaign_type text, delivers_from_vn date, delivers_to_vn date, recipient_name text, phone_masked text, province text, district text, ward text, address_line text, address_type text, lines jsonb, payment_mode text, ready boolean, not_ready_reason text, cod_due_vnd bigint)definerU19-P2-28. The 7-argument candidates without a search (old callers); same columns as 20261214012100.
ship_candidatesp_date date, p_type text, p_prefix text, p_needle text, p_phone text, p_limit integer, p_offset integerTABLE(total_groups bigint, group_no bigint, group_key text, order_id uuid, cycle_no integer, campaign_id uuid, campaign_type text, delivers_from_vn date, delivers_to_vn date, recipient_name text, phone_masked text, province text, district text, ward text, address_line text, address_type text, lines jsonb, payment_mode text, ready boolean, not_ready_reason text, cod_due_vnd bigint, component_total bigint, online_fallback boolean)definerU19-P2-28, U28-P2-08 (VD-US-03 AC01/AC07/AC08, VD-US-04 AC02). Operators only: WAITING_PACKING units grouped by the exact recipient + phone + address + delivery date, search (order code prefix, folded name, exact phone) keeps matching components, component_total = whole group size; lines = the unit's goods (ordering.cycle_goods: quantity of that cycle, products that met their MOQ), as the handover links them; online_fallback (U28-P5-11) = chosen online, not paid in full, ships COD for the remaining. Read-only.
ship_readinessp_order uuid, p_order_cycle uuidTABLE(ready boolean, payment_mode text, cod_due_vnd bigint, reason text)definerU19-P2-22. Ready to ship = no payment still moving (payment_pending); mode and COD due as locked at the handover (an unpaid online unit is COD with the remaining at the lock).
shipment_cod_collect_factsp_shipments uuid[]TABLE(shipment_id uuid, due_vnd bigint, lines jsonb, collected boolean)definerU28-P2-10. Shipment.codCollect facts per shipment: OPEN COD lines, their total (fulfillment.shipment_cod_due = the totalVnd recordShipmentCodCollection accepts) and whether a COD row of its units was already collected. Read-only.
shipment_cod_collect_previewp_shipment uuidjsonbdefinerU28-FU-API-B. Query.shipmentCodCollectPreview: recordShipmentCodCollection (payment.cod_record_shipment_collection) run in a rolled-back subtransaction; per order / cycle the payment axis before / after, the reward milestone it reaches and the reward points; nothing written.
shipment_cod_duep_shipment uuidbigintdefinerU28-P2-09. COD still OPEN on the units of a shipment (the Đã thu đủ tiền COD total); read by update_shipment_status and shipment_status_preview.
shipment_event_effectsp_shipment uuidTABLE(event_id uuid, order_id uuid, order_code text, cycle_no integer, order_status text, payment_status text)definerU28-FU-API-C. Order / payment status each applied shipment fact left on its own units, read from the order activity rows written in the same transaction (occurred_at = fact recorded_at); no second formula. Shipment readers only.
shipment_line_factsp_shipments uuid[]TABLE(link_id uuid, line_no integer, unit_weight numeric, weight_unit text, unit_length numeric, unit_width numeric, unit_height numeric, dimension_unit text)definerU19-P2-34. Product packing facts of each shipment goods line (weight G|KG as stored, sizes in CM; null = not on the product). Shipment readers only, read-only.
shipment_order_links_sync_shipping—triggerdefiner
shipment_search_idsp_prefix text, p_needle text, p_phone textSETOF uuiddefinerU19-P2-27 (VD-US-02 AC01). Ids of the shipments whose code or order code starts with p_prefix (upper case), whose recipient name contains p_needle (LIKE-escaped; case and diacritics ignored) or whose phone equals p_phone (E.164). Operators only (actor_is_operator); no other column leaves the function.
shipment_status_previewp_shipment uuid, p_to text, p_cod booleanjsonbdefinerU28-P2-09. Query.shipmentStatusPreview: updateShipmentStatus(to[, COD tick]) run in a rolled-back subtransaction; effects, attempt number and COD due read inside it; nothing written. U28-FU-API-D: effectsBefore / attemptsBefore (same readers, before the dry run), attemptsAfter, p_cod.
shipment_unit_effectsp_shipment uuidjsonbdefinerU19-P2-26. Order / payment / shipping status of every order / cycle of a shipment (command result).
shipments_order_axes_delivered—triggerdefinerU19-P1-07. DELIVERED shipment -> its CONFIRMED Group Buy orders become SUCCESS (order axis), COD collected or not.
shipments_sync_unit_shipping—triggerdefiner
shortage_rows_complete_order—triggerdefiner
skip_requests_complete_order—triggerdefiner
sources—text[]P2-17. Fulfillment event sources: OPERATOR, CARRIER, SYSTEM. A customer is never a source.
staff_cycle_schedulep_campaign uuid, p_order uuid, p_state text, p_from timestamp with time zone, p_to timestamp with time zone, p_limit integer, p_offset integerTABLE(total bigint, order_id uuid, campaign_id uuid, order_state text, cycle_no integer, delivers_from timestamptz, delivers_to timestamp with time zone, cycle_state text, committed_units bigint, delivered boolean, cod_due_vnd bigint, cod_status text, value_vnd bigint, final_value_vnd bigint, lines jsonb, skip_reason_code text, skip_reason_text text)definerFU-AC-TRIAGE L7 A-OPS-02 HC01 / GAP-422, G2I-P1-01 D12, G2I-P2-02. Operator-only (repeats actor_is_operator): the period worklist of confirmed Recurring orders with the units and lines of the period (its own quantities), commitment state, COD obligation, final value and the reason of the period's active skip; no personal data.
state_rankp_state textinteger
states—text[]
sync_link_shippingp_link uuid, p_actor uuidbooleandefinerU19-P1-08. The order / cycle of one link takes the shipment state (CREATED reads PACKING); cancelled units kept.
sync_unit_shippingp_shipment uuid, p_actor uuidintegerdefinerU19-P1-08. Applies the shipment state to the shipping axis of every order / cycle it carries; returns units seen.
transition_allowedp_from text, p_to textbooleanP2-17. Shipment machine: CREATED -> PACKING -> SHIPPING -> DELIVERED|DELIVERY_FAILED|RETURNED; DELIVERY_FAILED -> SHIPPING|RETURNED.
transition_recordedp_from text, p_to textbooleanU19-P1-08. Shipment transitions ever legal (current machine + earlier ones + backfill): shape check of stored facts.
unit_cod_planp_order uuid, p_order_cycle uuidTABLE(payment_mode text, cod_due_vnd bigint, create_vnd bigint, online_open uuid)definerU19-P2-22, U28-FU-REWARD (B013.R11). Payment of a unit at the method lock: live COD remaining, else paid online (0), else COD = remaining at the lock (Group Buy: open online / close outcome; Recurring cycle: its COD of payment.recurring_cycle_cod, rounded per DEC-U28-01 / DEC-U28-12 for an ONLINE close).
unit_payment_pendingp_order uuidbooleandefiner
update_shipment_statusp_shipment uuid, p_expected_version integer, p_to text, p_note text, p_cod boolean, p_source_event_id textjsonbdefinerU19-P2-26. updateShipmentStatus: state + every order/cycle + logs + optional COD collection, one transaction (NFR #7). U28-P2-09: COD due from fulfillment.shipment_cod_due.

schema identity_flow ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
account_kind_for_appp_app app_codetextPPI-P1-02 (E-05). The accounts.kind an app's people live on: WEB_ADMIN -> STAFF, APP_USER/APP_SALE -> CUSTOMER.
auth_runtime_functions—TABLE(fn regprocedure, reconcile boolean)P1-02/P1-03 fix. The identity_flow functions the auth Edge Function calls (SECURITY DEFINER, EXECUTE: pi_auth).
auth_runtime_gaps—SETOF textP1-02/P1-03 fix. Missing/excess privileges of the auth runtime design (pi_auth + definer owner); expect 0 rows.
credential_changep_account uuid, p_sid uuid, p_hash text, p_correlation_id correlation_refjsonbdefinerPPI-P2-01. /password/change: CHANGED|NO_CREDENTIAL|SESSION_INVALID; other sessions revoked (PASSWORD_CHANGE).
credential_createp_subject uuid, p_phone text, p_hash text, p_challenge_id uuidjsonbdefinerAF-P2-03. Saga S2: create the local credential, idempotent by SIGN_UP challenge (CREATED|EXISTS|PHONE_EXISTS).
credential_for_accountp_account uuidjsonbdefinerPPI-P2-01. {account_id, kind, password_hash, must_change, temporary_expires_at} of the account's credential (staff_credentials for STAFF, password_credentials for CUSTOMER), or null.
credential_for_phonep_phone textjsonbdefinerAF-P2-03. Sign-in lookup {subject, password_hash, account_id, phone} or null.
credential_setp_account_id uuid, p_hash textjsonbdefinerAF-P2-03. Reset: upsert the account's credential (CREATED|UPDATED).
mask_emailp texttext
mask_phonep texttext
mask_pipoint_uidp texttext
mfa_attemptp_account uuid, p_app app_code, p_purpose text, p_factor_id uuid, p_max_attempts integer, p_window_seconds integerjsonbdefiner
mfa_auditp_account uuid, p_action text, p_result text, p_reason text, p_metadata jsonb, p_correlation_id correlation_refvoid
mfa_blockp_account uuid, p_app app_codetext
mfa_enrollp_account uuid, p_app app_code, p_factor_id uuid, p_factor_type text, p_sealed bytea, p_nonce bytea, p_key_id text, p_ttl_seconds integer, p_correlation_id correlation_refjsonbdefiner
mfa_finishp_account uuid, p_app app_code, p_purpose text, p_factor_id uuid, p_matched_step bigint, p_action text, p_session_id uuid, p_grant_ttl_seconds integer, p_max_attempts integer, p_lock_seconds integer, p_correlation_id correlation_refjsonbdefiner
mfa_statusp_account uuid, p_app app_codejsonbdefiner
password_reset_claimp_grant_hash bytea, p_app app_code, p_correlation_id correlation_refjsonbdefiner
password_reset_consumep_challenge_id uuid, p_phone text, p_app text, p_code_hash bytea, p_grant_hash bytea, p_grant_ttl_seconds integer, p_correlation_id correlation_refjsonbdefiner
password_reset_finishp_grant_id uuid, p_result text, p_correlation_id correlation_refjsonbdefiner
password_reset_issuep_challenge_id uuid, p_phone phone_e164, p_app app_code, p_code_hash bytea, p_ttl_seconds integer, p_max_attempts integer, p_cooldown_seconds integer, p_quota integer, p_quota_window_seconds integer, p_correlation_id correlation_refjsonbdefiner
password_reset_subjectp_phone textuuid
pipoint_auditp_account uuid, p_action text, p_result text, p_reason text, p_before jsonb, p_after jsonb, p_metadata jsonb, p_correlation_id correlation_refvoid
pipoint_bindp_issuer text, p_uid text, p_phone phone_e164, p_email text, p_display_name text, p_correlation_id correlation_refjsonbdefinerPPI-P3-03 / P3-08 / P3-15. POST auth/pipoint/exchange in one transaction: tombstone, link / auto-link by phone (CUSTOMER; REBIND_AFTER_UNLINK after a support unlink; never after a PiPoint deletion) / new account, identifier change (E-03), APP_USER membership + role user, point_account_links, profile name, audit. Outcomes: BOUND, IDENTIFIER_REQUIRED, ACCOUNT_DELETED, IDENTITY_CONFLICT, DENIED (account / membership lock).
pipoint_check_linkp_account_id uuid, p_sid uuid, p_issuer text, p_uid textjsonbdefinerPPI-P3-10 (D-09). Refresh check of an APP_USER session: MATCH (live link = verified token uid), LOST {reason} (token_missing, uid_mismatch, uid_deleted, link_ended) or NO_LINK (as before). Read only; pi_auth only.
pipoint_exchange_beginp_scope text, p_key_hash bytea, p_max_attempts integer, p_window_seconds integerjsonbdefinerPPI-P3-10 (GAP-PPI-01). Counts one exchange attempt of (scope, key hash) in a fixed window: PROCEED {attempt} or THROTTLED {retry_after_seconds}. pi_auth only.
purge_expired_credentialsp_retention_seconds integer, p_batch integerTABLE(o_grants integer, o_challenges integer, o_held integer, o_sign_in_challenges integer)definerFU-710 + PPI-P2-01. DEC-AUTH-PARAMS: deletes finished OTP challenges and grants (hashes, draft) and finished or expired staff sign-in challenges older than the retention; unfinished SIGN_UP sagas are held for sign_up_reconcile. Worker only.
purge_expired_sessionsp_retention_seconds integer, p_batch integerTABLE(o_sessions integer)definerAF-P2-04. Deletes PIDEAL sessions ended (revoked or expired) longer than the retention. Worker only.
role_assignment_revoked_end_sessions—triggerdefinerAF-P3-11. Trigger: a revoked WEB_ADMIN role assignment ends that account's WEB_ADMIN sessions (ROLE_DOWNGRADE).
role_grants_narrowed_end_sessions—triggerdefinerAF-P3-11. Trigger: a revoked (permission, scope) pair of a WEB_ADMIN role ends the WEB_ADMIN sessions of every current holder (ROLE_DOWNGRADE).
session_checkp_sid uuid, p_account_id uuid, p_app app_codebooleandefiner
session_createp_account_id uuid, p_app app_code, p_refresh_hash bytea, p_idle interval, p_absolute intervaljsonbdefiner
session_revokep_sid uuid, p_reason textjsonbdefiner
session_revoke_accountp_account_id uuid, p_app app_code, p_reason textintegerdefiner
session_rotatep_sid uuid, p_presented bytea, p_next bytea, p_app app_code, p_idle interval, p_grace intervaljsonbdefiner
sign_in_accessp_auth_user_id uuid, p_app app_code, p_phone phone_e164jsonbdefiner
sign_in_auditp_auth_user_id uuid, p_app app_code, p_action text, p_result text, p_reason text, p_phone phone_e164, p_correlation_id correlation_refvoiddefiner
sign_in_beginp_phone phone_e164, p_app app_code, p_max_failures integer, p_window_seconds integerjsonbdefinerP1-03 + PPI-P1-02 (B-07). Counts one sign-in attempt of (kind of p_app, phone) before the password is checked.
sign_in_challenge_createp_account uuid, p_app app_code, p_secret_hash bytea, p_steps text[], p_correlation_id correlation_refjsonbdefinerPPI-P2-01. Opens a 10-minute WEB_ADMIN sign-in challenge of a STAFF account (hash of the secret only).
sign_in_challenge_finishp_challenge_id uuid, p_secret_hash bytea, p_correlation_id correlation_refjsonbdefinerPPI-P2-01. Consumes a challenge whose steps are all done: FINISHED {account_id, app, phone}|STEPS_PENDING|refusal.
sign_in_challenge_openp_challenge_id uuid, p_secret_hash bytea, p_step text, p_max_attempts integerjsonbdefinerPPI-P2-01. PROCEED|INVALID|EXPIRED|LOCKED|OUT_OF_ORDER for the next step; read-only.
sign_in_challenge_refusalc sign_in_challenges, p_secret_hash bytea, p_step text, p_max_attempts integertext
sign_in_challenge_stepp_challenge_id uuid, p_secret_hash bytea, p_step text, p_result text, p_password_hash text, p_max_attempts integer, p_correlation_id correlation_refjsonbdefinerPPI-P2-01. Records DONE|FAILED of the next step: DONE|FAILED|LOCKED|NOT_READY or a refusal.
sign_in_failp_phone phone_e164, p_app app_code, p_max_failures integer, p_lock_seconds integer, p_correlation_id correlation_refjsonbdefiner
sign_in_releasep_phone phone_e164, p_app app_codevoiddefinerP1-03 + PPI-P1-02 (B-07). Gives back an undecided attempt of (kind of p_app, phone).
sign_up_abandonp_grant_id uuid, p_reason text, p_correlation_id correlation_refjsonbdefiner
sign_up_bindp_grant_id uuid, p_auth_user_id uuidjsonbdefiner
sign_up_consumep_challenge_id uuid, p_phone text, p_app text, p_code_hash bytea, p_grant_hash bytea, p_grant_ttl_seconds integer, p_correlation_id correlation_refjsonbdefiner
sign_up_find_identityp_phone text, p_challenge_id uuidjsonbdefiner
sign_up_issuep_challenge_id uuid, p_phone phone_e164, p_app app_code, p_code_hash bytea, p_ttl_seconds integer, p_max_attempts integer, p_cooldown_seconds integer, p_quota integer, p_quota_window_seconds integer, p_correlation_id correlation_refjsonbdefiner
sign_up_linkp_grant_id uuid, p_correlation_id correlation_refjsonbdefiner
sign_up_reconcilep_stale_seconds integer, p_correlation_id correlation_refjsonbdefiner
staff_credential_for_phonep_phone textjsonbdefinerPPI-P2-01. WEB_ADMIN sign-in lookup {subject, account_id, password_hash, phone, must_change, temporary_expires_at, temporary_expired, mfa_enrolled} of the STAFF account of the phone, or null.
staff_credential_issuep_caller uuid, p_sid uuid, p_target uuid, p_hash text, p_correlation_id correlation_refjsonbdefinerPPI-P2-04 / PPI-P7-01 POST auth/staff/temporary-password (D-15): ISSUED{account_id, expires_at (72 h), reissued, sessions_revoked} | SESSION_INVALID | FORBIDDEN | SELF | NOT_FOUND | ACCOUNT_NOT_ACTIVE | MEMBERSHIP_NOT_ACTIVE | NO_PHONE | STEP_UP_REQUIRED (each audited DENIED). Spends one staff.credential_issue step-up grant, except the first password of an account the caller created in this session within 15 minutes (covered by its staff.create step-up). No role needed (a new staff member gets the password before the role is approved).

schema spin ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
actor_canp_action textbooleanP4-15. Acting principal may read/write Lucky Wheel configuration (matrix SPN-02/SPN-03, GAP-67: nobody).
actor_wallet_linked—booleandefinerVQM-P1-07 DEC-VQM-08 C. pi_api: the acting buyer holds a live Ví của tôi link (entering a session needs one).
admin_session_detailp_session uuidTABLE(session_id uuid, order_id uuid, order_code text, account_id uuid, customer_code text, full_name text, phone text, phone_masked text, campaign_id uuid, campaign_code text, campaign_type text, wheel_id uuid, wheel_code text, wheel_name text, deposit_confirmed_at timestamptz, round_no integer, spins_allotted integer, spins_used integer, best_points integer, state text, end_reason text, entered_at timestamp with time zone, ended_at timestamp with time zone, points_status text, points_note text, draws jsonb)definerVQM-P1-09 VQ-US-08 AC07. spin.history.read (SPN-05) else 42501. The session row of admin_session_history and its draws in draw order (drawNo, drawnAt, slotNo = tier_no, points, highest = points equal to the kept points). No row for an unknown id.
admin_session_historyp_search text, p_wheel uuid, p_campaign_type text, p_state text, p_points_status text, p_from date, p_to date, p_phone_search boolean, p_limit integer, p_offset integer, p_session uuidTABLE(session_id uuid, order_id uuid, order_code text, account_id uuid, customer_code text, full_name text, phone text, phone_masked text, campaign_id uuid, campaign_code text, campaign_type text, wheel_id uuid, wheel_code text, wheel_name text, deposit_confirmed_at timestamptz, round_no integer, spins_allotted integer, spins_used integer, best_points integer, state text, end_reason text, entered_at timestamp with time zone, ended_at timestamp with time zone, points_status text, points_note text, total bigint)definerVQM-P1-09 VQ-US-08, BR-VQLS-01..05. spin.history.read (SPN-05) else 42501 spin_history_denied. One page of spin sessions, newest confirmed deposit first, filters combined with the keyword (Mã đơn / Mã KH / Mã chiến dịch contained, any case; phone per customer.pii.read: full only for a customer reader the API marked, else the visible mask). Days are Vietnam days, inclusive. Every row carries the total; an empty page is one row with total only (session_id null). phone is null unless customer.actor_can_read(); phone_masked always. p_session: one session.
allot_spinsp_intervals jsonb, p_at timestamp with time zoneintegerG2I-P1-02 (D6). Spins of the interval holding p_at, half-open [starts_at, ends_at); 0 outside every interval.
campaign_closedp_campaign_id uuid, p_at timestamp with time zonebooleandefinerG1S-P1-06. True when the campaign is no longer OPEN or at is at/after Thời gian đóng (closes_at): a KEPT session can no longer be resumed and expires.
campaign_has_outcomep_campaign_id uuidbooleandefinerVQM-P1-06 DEC-VQM-04 / 09. True once the campaign (Mua chung or Mua định kỳ) has its outcome: SUCCESS, PARTIAL_SUCCESS or FAILED. CLOSING is not an outcome: a session not entered keeps its spins until then.
campaign_rule_wheelp_campaign uuiduuiddefinerCV3-P1-07 S4. The wheel the deprecated campaignId names: campaigns.spin_wheel_id, else the wheel made for that campaign (spin.wheels.source_campaign_id); null when none or without spin.read.
campaign_rule_wheel_for_writep_campaign uuiduuiddefinerVQM-P1-11 S13 (deprecated saveSpinRuleDraft(campaignId), kept until the App / Web stop calling it). The wheel a new draft of the campaign goes to: campaigns.spin_wheel_id, else the wheel made for the campaign, else a new one made for it ('Vòng quay ' || code, ever chosen, not chosen by the campaign). Null for an unknown campaign; spin_wheel_write_denied without spin.write.
delete_wheelp_wheel uuidTABLE(id uuid, code text, name text)definerVQM-P1-01 BR-VQ-05, VQM-P1-04. Xóa vòng quay (spin.write): locks the wheel FOR UPDATE, refuses a legacy wheel (spin_wheel_legacy) and one any campaign ever chose (spin_wheel_ever_chosen), else deletes it with its change events (Lịch sử thay đổi) and rule versions and returns its id, code and name. spin_wheel_not_found for an unknown id; no version check (S7).
end_disconnectedp_session uuid, p_correlation textTABLE(result_id uuid, reward_action_id uuid)definerVQM-P1-07 DEC-VQM-07 (research-disconnect §9 rule 2). Internal: ends an entered ACTIVE session DISCONNECTED at last_seen_at + T (or now(), when earlier): >= 1 draw COMPLETED (highest kept, one ISSUE unless the order ended), else FORFEITED. No-op on any other session.
enter_sessionp_session uuid, p_correlation textTABLE(outcome text, state text, version integer, result_id uuid, reward_action_id uuid)definerVQM-P1-07 BR-VQ-08, DEC-VQM-07 / 08 C / 09 / 18. pi_api, the acting buyer's own session: NOT_ENTERED -> ACTIVE (needs a live Ví của tôi, else spin_sessions_wallet_required); lost before entering (order ended, campaign outcome) -> FORFEITED + ENDED; an entered ACTIVE session -> DISCONNECTED + ENDED; an ended one -> UNCHANGED. Ends commit.
finish_sessionp_session uuid, p_issue boolean, p_correlation textTABLE(result_id uuid, reward_action_id uuid)definerFU-717. Internal: ends a session that has draws (COMPLETED, the one highest result, the one reward intent).
heartbeatp_session uuid, p_correlation textTABLE(outcome text, state text, version integer, result_id uuid, reward_action_id uuid)definerVQM-P1-07 BR-VQ-08 E, DEC-VQM-07. pi_api, the acting buyer's own session: an entered ACTIVE session inside T -> last_seen_at = now() (version unchanged, ALIVE); past T -> DISCONNECTED (ENDED, committed); anything else UNCHANGED.
heartbeat_interval_seconds—integerVQM-P1-07 DEC-VQM-07. H: seconds between spinSessionHeartbeat calls while ACTIVE (SpinSession.heartbeatIntervalSeconds).
intervals_okp jsonbboolean
leave_sessionp_session uuid, p_actor uuid, p_correlation textTABLE(outcome text, state text, version integer, result_id uuid, reward_action_id uuid)definer#412 GAP-671, VQM-P1-06 / P1-07 (U-42, DEC-VQM-08 A, DEC-VQM-07). pi_api, the acting buyer's own entered ACTIVE session: with a draw COMPLETED, without one FORFEITED; end_reason LEFT, or DISCONNECTED when past T. Outcome COMPLETED / EXPIRED (no draw). Any other session: UNCHANGED.
manager_roles—text[]P4-15 + G2I-P1-02 mirror of matrix SPN-02/SPN-03 spin.read/spin.write WEB_ADMIN: operations, admin (D6).
next_wheel_codep_at timestamp with time zonetextdefinerVQM-P1-01 BR-VQ-02 / DEC-VQM-11. VQ + ddmmyyyy (Asia/Ho_Chi_Minh date of p_at) + 2-digit number of that day (campaign.next_daily_code scope spin_wheel, from 01 each day); spin_wheel_code_exhausted past 99. Owner only: spin.wheels_guard calls it with now().
open_session_from_depositp_order_id uuid, p_order_version integer, p_event_id uuid, p_correlation_id textTABLE(outcome text, session_id uuid, rule_version_id uuid, owner_account_id uuid, campaign_id uuid, deposit_confirmed_at timestamptz, window_ends_at timestamp with time zone, session_duration_seconds integer)definerVQM-P1-12 BR-VQ-06/08, DEC-VQM-04/08 C/09/14. The confirmed deposit (DEPOSIT_PENDING -> PLACED at that order version) opens one NOT_ENTERED session, no window, with or without a Ví của tôi: spins of the round holding deposit_confirmed_at (shape 2, spin.resolve_rounds; CLOSING -> the last round) or of the legacy interval (shape 1, round_no null), configuration snapshotted. CREATED | EXISTS | NOT_ENABLED | NO_RULE | NO_SPINS | NOT_DEPOSIT_CONFIRMED | ORDER_EVENT_MISSING (an outcome recorded before, e.g. NO_WALLET, is returned as is).
order_spinp_order_id uuidTABLE(availability text, session_id uuid, state text, spins_left integer, resumable_until timestamptz, wallet_required boolean, enterable_until_outcome boolean)definerVQM-P1-12 S11 (20261227020000 restated). pi_api: Order.spin of the acting buyer's own order (NOT_APPLIED for any other): SESSION (state as the sweep leaves it, spins left, wallet_required = NOT_ENTERED without a live Ví của tôi, enterable_until_outcome = NOT_ENTERED and neither the order ended nor the campaign has its outcome) | NO_SPINS | NO_WALLET (legacy) | NOT_APPLIED. resumable_until is always null (deprecated).
owns_sessionp_owner uuidboolean
playp_session uuid, p_draw_no integer, p_roll numeric, p_rng_source text, p_correlation textTABLE(outcome text, draw_no integer, tier_no integer, points integer, drawn_at timestamptz, spins_used integer, best_points integer, state text, version integer, result_id uuid, reward_action_id uuid)definerP4-16, VQM-P1-07 (BR-VQ-08 E, DEC-VQM-07). pi_api, the acting buyer's own entered ACTIVE session: an existing draw is REPLAYED first; past T the session ends DISCONNECTED (ENDED, committed, no draw); else one server draw (a heartbeat too), the last spin completes it (ALL_SPINS_USED, one ISSUE unless the order ended).
points_statusp_issue_status text, p_issue_reason text, p_release_status text, p_cancel_status textTABLE(status text, note text)VQM-P1-09 BR-VQLS-04, DEC-VQM-15. Trạng thái Pi-Point of a spin session from the status / reason of its SPIN ISSUE and the status of its RELEASE / CANCEL_ISSUE: NONE | PENDING | AVAILABLE | CANCELLED, and the reason line (SpinRewardState SYNCING / RETRYING / BLOCKED under PENDING, REJECTED / NO_WALLET under CANCELLED; null otherwise).
presence_timeout—intervalVQM-P1-07 DEC-VQM-07. T: an entered ACTIVE session whose last signal is older than this has disconnected.
prize_tiers_okp jsonbboolean
public_max_points_per_spinp_campaign_id uuid, p_spin_enabled booleanintegerG1S-P1-06 R5. Mức tối đa mỗi lượt: the largest prize of the PUBLISHED wheel; null when the wheel is off or nothing is published. Helper of the definer public reads (PublicCampaign.maxPointsPerSpin).
public_prize_pointsp_campaign_ids uuid[]TABLE(campaign_id uuid, points integer[])definer#412 GAP-672 (owner verdict 6, 28/10). pi_api public read: the points of each prize tier of the PUBLISHED wheel in tier order (PublicCampaign.spinPrizePoints), for published campaigns with the wheel on; no row otherwise. Never a probability. Empty for a caller outside the public read (campaign.public_reader).
public_wheel_displayp_campaign_ids uuid[]TABLE(campaign_id uuid, tone text, rules_text text, max_points integer, slots jsonb)definerVQM-P1-13 S14 (BR-VQ-02/07/10, DEC-VQM-02/14). The public preview of the wheel each campaign chose: tone, 8 slots with the tone colours, Thể lệ, Mức tối đa (shape 2); tone / Thể lệ null and no slots for a legacy wheel. Never the name or a probability. Same public gate as spin.public_prize_points.
record_wheel_changep_wheel_id uuid, p_actor uuid, p_kind text, p_old jsonb, p_new jsonbuuiddefinerVQM-P1-05 BR-VQ-12. Appends one spin.wheel_change_events row: CREATED / DEACTIVATED without changes, UPDATED with spin.wheel_config_changes(old, new). Called by spin.save_wheel_config and the DEACTIVATED trigger only.
resolve_roundsp_rounds jsonb, p_opens_at timestamp with time zone, p_closes_at timestamp with time zoneTABLE(round_no integer, from_day integer, to_day integer, spins integer, starts_at timestamptz, ends_at timestamp with time zone)VQM-P1-02 BR-VQ-06. The rounds of a shape 2 rule for a campaign window as [starts_at, ends_at) in GMT+7: Ngày 1 from opens_at to the end of its day, then whole days; the last round until closes_at; a round past closes_at is cut, one starting at or after it is dropped. No rows for an invalid round list or window.
result_for_orderp_order uuidTABLE(base_points integer, rule_version_id uuid)definerP4-16. pi_worker: base points of the one retained result of the order's COMPLETED session.
rounds_okp jsonbbooleanVQM-P1-02 BR-VQ-06. A shape 2 round list: 1..5 [{to_day, spins}], to_day integer >= from_day (1, then previous to_day + 1) except the last (null: until the campaign closes), spins integer >= 1 and never more than the round before.
save_wheel_configp_wheel_id uuid, p_actor uuid, p_config jsonb, p_expected_version integerTABLE(wheel_id uuid, code text, wheel_version integer, outcome text, rule_version_id uuid, superseded_rule_version_id uuid)definerVQM-P1-11 BR-VQ-06/07/10, DEC-VQM-19/20, VQM-P1-05 BR-VQ-12. Tạo (p_wheel_id null) / Sửa (p_expected_version = the wheel version) of a lucky wheel, the only SQL write path: config {name, tone, rules_text, rounds [{to_day, spins}], slots [8 x {tier_no, points, probability_pct}]}; writes the wheel row, a new shape 2 rule version PUBLISHED (the previous one SUPERSEDED) and the Lịch sử thay đổi row (CREATED / UPDATED with the diff) in one transaction, or nothing when unchanged. Returns wheel_id, code, wheel_version, outcome (CREATED | UPDATED | UNCHANGED), rule_version_id (in force), superseded_rule_version_id. spin.write; p_actor = the acting principal.
session_extrasp_sessions uuid[]TABLE(session_id uuid, order_state text, rewards jsonb)definerP4-16. pi_api: order state + SPIN reward rows of the acting buyer's own sessions (no other rows).
session_refp_session uuidtextdefiner
slots_okp jsonbbooleanVQM-P1-02 BR-VQ-07, DEC-VQM-02. A shape 2 slot table: exactly 8 [{tier_no = position, points, probability_pct}], points integer >= 0 (equal points allowed), probability 0..100 with at most 2 decimals (0 allowed), total 100 in units of 0.01 %.
sweep_sessionsp_limit integerTABLE(session_id uuid, order_id uuid, owner_account_id uuid, campaign_id uuid, rule_version_id uuid, version integer, ended_at timestamptz, state text, end_reason text, spins_allotted integer, spins_used integer, best_points integer, result_id uuid, reward_action_id uuid)definerVQM-P1-07 DEC-VQM-07 / 09 / 18. pi_worker, job spin.session_expire: one batch of entered ACTIVE sessions past T -> DISCONNECTED (COMPLETED with its one ISSUE, or FORFEITED), one batch of sessions not entered whose order ended or campaign has its outcome -> FORFEITED (ORDER_CANCELLED / CAMPAIGN_CLOSED). Returns every session it ended.
tier_for_rollp jsonb, p_roll numericTABLE(tier_no integer, points integer)P4-16, VQM-P1-02. The tier a roll in [0,100) selects: the first tier (tier_no order) whose cumulative probability, in units of 0.01 %, exceeds roll x 100. A 0% tier never wins.
tier_pointsp jsonb, p_tier_no integerinteger
tone_palettep_tone textTABLE(slot_no integer, background_color text, text_color text)VQM-P1-02 BR-VQ-07. Background / text colour of slot 1..8 for tone ORANGE (Cam) or CHERRY_PINK (Hồng cherry); the API's single source of slot colours. No rows for an unknown tone.
wheel_change_events_delete_guard—trigger
wheel_config_changesp_old jsonb, p_new jsonbjsonbVQM-P1-05 BR-VQ-12, DEC-VQM-20, api-change-spec §5.2. Pure diff of two wheel configs {name, tone, rules_text, rounds, slots} by position: [{scope null|ROUND|SLOT, scope_no, field NAME|TONE|TO_DAY|SPINS|POINTS|PROBABILITY_PCT|RULES_TEXT, before, after}] in the order NAME, TONE, Đợt n (TO_DAY, SPINS), Ô n (POINTS, PROBABILITY_PCT), RULES_TEXT. Numbers as decimal text, open last round END, missing Đợt / Ô null, RULES_TEXT without values; an added / removed open last round has no TO_DAY row.
wheel_delete_guard—trigger
wheel_history_pagep_wheel_id uuid, p_from date, p_to date, p_actor uuid, p_limit integer, p_offset integerTABLE(total bigint, actors jsonb, id uuid, at timestamptz, actor_id uuid, actor_name text, kind text, changes jsonb)definerVQM-P1-05 BR-VQ-12, VQ-US-04 AC07–AC08. spin.read (SPN-02) else 42501 spin_wheel_history_denied; unknown wheel P0002 spin_wheel_not_found. One page of the wheel's Lịch sử thay đổi, newest first, filtered by actor and by the Vietnam day range [p_from, p_to] (GMT+7, inclusive, null = open), with the filtered total and every actor of the wheel [{id, name}] (profiles.full_name, never a phone). An empty page is one row with id null.
wheel_in_use_lockedp_wheel uuidbooleandefinerCV3-P1-07 + VQM-P1-01 BR-VQ-04 / DEC-VQM-03. True while a campaign that chose the wheel is OPEN or CLOSING (Đang mở); a campaign with an outcome no longer locks. Locks the configuration (name, tone, rules, rule versions), never the status. SpinWheel.inUseLocked.
wheel_lock_campaignsp_wheel uuidtext[]definerVQM-P1-01 BR-VQ-04. Codes of the campaigns OPEN / CLOSING that chose the wheel (the ones that lock it), by code; empty when not locked. Fills campaignCodes of the wheel_locked error.
wheels_guard—triggerdefiner
wheels_record_deactivated—triggerdefinerVQM-P1-05 BR-VQ-12. AFTER UPDATE OF status on spin.wheels, ACTIVE -> INACTIVE only: records DEACTIVATED (Ngừng hoạt động) with actor = the row's updated_by.

schema sale_admin ​

P1-13. Sale membership activation / status functions for pi_api.

HàmTham sốTrả vềMô tả
account_statusp_account uuidtextU6-P2-22. Derived account status of one Sale (owner context only).
activatep_application_id uuid, p_account_id uuid, p_expected_version integer, p_reason text, p_correlation_id textTABLE(account_id uuid, membership_version integer, change_request_id uuid, change_version integer)definerP1-13. APPROVED application -> APP_SALE membership ACTIVE (approved_by = actor <> applicant) + PENDING ASSIGN_ROLE request for role sale (maker = actor; a different role_permission.approve holder applies it).
actor_can_manage—booleanU6-P2-22. The acting principal holds a live SAL-02 role now (WEB_ADMIN, ACTIVE account and membership); fail closed.
actor_can_read—booleanFU-L4-SALE-READ. The acting principal holds a live reader role (matrix SAL-01); false for everyone else (fail closed).
actor_can_review—booleanU6-P2-22. The acting principal holds a live SAL-03 role now (WEB_ADMIN, ACTIVE account and membership); fail closed.
affiliate_ordersp_account uuid, p_keyword text, p_limit integer, p_offset integerTABLE(order_id uuid, customer_account_id uuid, ordered_at timestamptz, order_state text, value_vnd bigint, order_total bigint, customer_total bigint, total bigint)definerFU-L4-SALE-READ AP-17. Orders attributed to one Sale (Affiliate Last-Touch), searchable; needs sale.read (SAL-01).
affiliate_pagep_account uuid, p_keyword text, p_limit integer, p_offset integerTABLE(order_id uuid, order_ref text, order_code text, customer_account_id uuid, customer_code text, ordered_at timestamptz, value_vnd bigint, order_total bigint, customer_total bigint, total bigint, reward_points bigint, reward_total bigint, success_total bigint, revenue_vnd bigint)definerU6-P2-22 SL-US-02 AC06 + U6-P7-56 + U6-P7-55 + #298. Orders attributed to one Sale; order_code = orders.code (temporary format, NEW-SL-12), order_ref = last 8 of the id in upper case (BUG-SL-VIS-07); keyword = part of order_ref, the whole order code or the whole Ma khach hang, any letter case; success_total = Hoan tat orders, revenue_vnd = sum of their final price (null when one has none), reward_points per order, reward_total over all; needs sale.read.
approve_ticketp_account uuid, p_ticket uuid, p_expected_version integer, p_qualification_verified boolean, p_correlation_id textTABLE(kind text, ticket_version integer, account_status text, version integer)definerU6-P2-22 SL-US-04 AC01/AC02. New account: approved + ACTIVE + role sale in one transaction; update: values applied, account kept. Needs sale.review (MFA in the API); never the Sale or its creator (K-10).
attach_mediap_account uuid, p_media uuid, p_use text, p_max_bytes bigint, p_field textvoid
conflictsp_account uuid, p_username text, p_email text, p_referral text, p_phone texttext[]
create_salep_account uuid, p_full_name text, p_username text, p_phone text, p_email text, p_date_of_birth date, p_tier_id uuid, p_referral_code text, p_note text, p_documents uuid[], p_image uuid, p_correlation_id textTABLE(account_id uuid, sale_code text, version integer)definerU6-P2-22 SL-US-03 + U6-P7-53/55/60 + #292. New account (phone unverified, provisioned_by, local identity link, no credential), or the existing account of the phone (membership + Sale profile only); Khoi tao + Cho duyet; the referral code is always system-generated (a typed one: invalid referralCode:not_editable, BUG-SL-VIS-06); <= 10 files. Needs sale.manage.
credited_rewardsp_account uuidTABLE(order_id uuid, points bigint)definerU6-P7-56 NEW-SL-08. Internal: points credited to one Sale per order (AFFILIATE_ORDER ISSUE accepted, not cancelled); sale.read.
derive_account_statusp_membership texttextU6-P2-22. APP_SALE membership status -> SaleAccountStatus (INITIATED | ACTIVE | INACTIVE | LOCKED).
derive_ticket_statusp_application text, p_change_pending boolean, p_membership texttextU6-P2-22. Delegates to the 4-argument form with no profile-change history (REJECTED application = REJECTED since U6-P7-02).
derive_ticket_statusp_application text, p_change_pending boolean, p_membership text, p_last_change texttextU6-P7-02 (Q-1 PROVISIONAL). PENDING_REVIEW | APPROVED | REJECTED | null (no ticket). REJECTED: a rejected new-account application, or the latest profile change rejected on an approved/active Sale.
directory—TABLE(account_id uuid, full_name text, phone text, phone_masked text, team_id uuid, team_name text, application_id uuid, application_status text, account_status text, membership_version integer, has_membership boolean, created_at timestamptz, updated_at timestamp with time zone)definerFU-L4-SALE-READ. Private: every Sale (membership or application) with the raw phone, for the reads below only.
format_codep_number biginttext
issue_code—triggerdefiner
lock_ticketp_account uuid, p_ticket uuid, p_expected_version integerTABLE(kind text, source text)
manager_roles—text[]U6-P2-22. Mirror of SAL-02 sale.manage (admin, super_admin, sale_manager; ALL).
may_attach_profile_mediap_media uuid, p_use_type text, p_account uuidbooleandefinerU6-P2-22. Policy helper: the acting sale.manage holder may attach this own READY media of the matching Sale profile purpose to this Sale (use_type sale_profile_file | sale_profile_image).
memberp_account uuidTABLE(account_id uuid, full_name text, phone_masked text, team_id uuid, team_name text, application_id uuid, application_status text, account_status text, membership_version integer, tier_code text, tier_name text, created_at timestamptz, updated_at timestamp with time zone)definerFU-L4-SALE-READ AP-17. One Sale: identity (masked), tier, application and account status; needs sale.read (SAL-01).
member_pagep_keyword text, p_ticket text, p_account text, p_limit integer, p_offset integerTABLE(account_id uuid, sale_code text, full_name text, phone text, phone_is_masked boolean, ticket_status text, account_status text, version integer, created_at timestamptz, updated_at timestamp with time zone, total bigint)definerU6-P2-22 SL-US-01. One page of Sales (ticket PENDING_REVIEW|APPROVED, account INITIATED|ACTIVE|INACTIVE|LOCKED, AND); full phone only for sale.manage; needs sale.read.
member_pagep_keyword text, p_ticket text, p_account text, p_limit integer, p_offset integer, p_sort textTABLE(account_id uuid, sale_code text, full_name text, phone text, phone_is_masked boolean, ticket_status text, account_status text, version integer, created_at timestamptz, updated_at timestamp with time zone, total bigint)definerU12-P3-14 SL-US-01 / ADD-SP-06. member_page with a sort key: CREATED_DESC | UPDATED_DESC | UPDATED_ASC | NAME_ASC (NULL = UPDATED_DESC, other = exception 22023); each ends with account_id; needs sale.read; full phone only for sale.manage.
member_profilep_account uuidTABLE(account_id uuid, sale_code text, full_name text, username text, phone text, phone_is_masked boolean, email text, date_of_birth date, referral_code text, note text, tier_id uuid, tier_code text, tier_name text, ticket_status text, account_status text, account_status_editable boolean, open_ticket_id uuid, open_ticket_kind text, open_ticket_source text, open_ticket_version integer, open_ticket_submitted_at timestamptz, version integer, created_at timestamp with time zone, updated_at timestamp with time zone)definerU6-P2-22 SL-US-02. One Sale: profile, tier, derived statuses, open ticket, editable account status; needs sale.read.
membersp_keyword text, p_application text, p_account text, p_team uuid, p_limit integer, p_offset integerTABLE(account_id uuid, full_name text, phone_masked text, team_id uuid, team_name text, application_id uuid, application_status text, account_status text, created_at timestamptz, updated_at timestamp with time zone, total bigint)definerFU-L4-SALE-READ AP-16. One page of Sales, filters AND-combined, phone masked, newest first; needs sale.read (SAL-01).
membershipp_sale uuidTABLE(account_id uuid, status text, version integer, team_id uuid, team_version integer)definerP1-13. APP_SALE membership + current team of a Sale in the actor's TEAM scope (guard row context).
new_referral_code—textU6-P7-55 (NEW-SL-07). System-generated Sale referral code (Referral link format), unused by any Sale, link or profile.
one_open_ticket_guard—triggerdefiner
phone_ownerp_phone textTABLE(account_id uuid, is_sale boolean)definerU6-P7-53 (NEW-SL-05). The account holding this phone and whether it already is a Sale; needs sale.manage.
profile_conflictsp_account uuid, p_username text, p_email text, p_referral text, p_phone texttext[]definerU6-P2-22. Taken fields (username, email, referralCode, phone) excluding the Sale itself; null unless sale.manage.
profiles_guard—triggerdefiner
reader_roles—text[]U6-P2-22. Mirror of SAL-01 sale.read (admin, super_admin, operations, sale_manager; ALL). Was FU-L4-SALE-READ.
referral_pagep_account uuid, p_keyword text, p_limit integer, p_offset integerTABLE(customer_account_id uuid, customer_code text, full_name text, registered_at timestamptz, referred_total bigint, total bigint, reward_points bigint, reward_total bigint)definerU6-P2-22 SL-US-02 AC05 + U6-P7-56. Customers referred by one Sale; customer_code from customer_codes; search by name or the whole code; reward_points = credited points of that customer's orders, reward_total over all referred customers; needs sale.read.
referralsp_account uuid, p_keyword text, p_limit integer, p_offset integerTABLE(customer_account_id uuid, full_name text, registered_at timestamptz, referred_total bigint, total bigint)definerFU-L4-SALE-READ AP-17. Customers referred by one Sale (SIGNUP milestone), searchable; needs sale.read (SAL-01).
reject_ticketp_account uuid, p_ticket uuid, p_expected_version integer, p_reason_id uuid, p_note text, p_correlation_id textTABLE(kind text, ticket_version integer, account_status text, version integer)definerU6-P7-02 SL-US-04 AC04/AC05 (Q-1 PROVISIONAL). Ticket REJECTED (terminal), account status kept, reason (+ note for "Khac") in the ledger, Sale version bumped. Needs sale.review (MFA in the API); never the Sale or its creator (K-10).
rejection_reasons—TABLE(id uuid, code text, label text, requires_note boolean)definerU6-P7-29 SL-US-04. Active seeded rejection reasons by display order, with requires_note; needs sale.review.
reviewer_not_creator_guard—triggerdefinerU6-P2-22 (K-10). A Sale ticket is never reviewed by the Admin who created the Sale (accounts.provisioned_by).
reviewer_roles—text[]U6-P2-22. Mirror of SAL-03 sale.review (admin, super_admin; ALL, MFA in the API).
roster—TABLE(account_id uuid, sale_code text, full_name text, phone text, phone_masked text, username text, email text, date_of_birth date, referral_code text, note text, application_id uuid, application_state text, application_source text, application_version integer, application_submitted_at timestamptz, change_id uuid, change_version integer, change_submitted_at timestamp with time zone, membership_status text, ticket_status text, account_status text, version integer, created_at timestamp with time zone, updated_at timestamp with time zone)definerU6-P2-22. Private: every Sale (sale_codes) with raw and masked phone, profile, derived ticket/account status, version.
set_statusp_sale uuid, p_status text, p_expected_version integer, p_reason textTABLE(version integer, status text, previous_status text)definerP1-13. ACTIVE/SUSPENDED/LOCKED of an activated Sale membership by a TEAM-scoped sale_profile.manage holder.
set_status_bulkp_items jsonb, p_status text, p_correlation_id textTABLE(account_id uuid, outcome text, previous_status text, status text, version integer)definerU6-P2-22 SL-US-01 AC09. Atomic bulk account status (1..100); Khoi tao skipped, same status unchanged; needs sale.manage.
ticket_statusp_account uuidtextU6-P2-22. Derived ticket status of one Sale (owner context only).
tier_options—TABLE(tier_id uuid, tier_version_id uuid, code text, name text, rank_order integer)definerU6-P2-22 SL-US-03 AC01. Published Sale tiers in force now; needs sale.manage.
touch_profilep_account uuidinteger
update_salep_account uuid, p_expected_version integer, p_patch jsonb, p_correlation_id textTABLE(version integer, changed boolean, fields text[])definerU6-P2-22 SL-US-02 + U6-P7-54/55/60. Direct edit (no ticket), compare-and-set on the Sale version, no-op writes nothing; account status only when not Khoi tao; phone / file-count gates; the referral code is never changed (a patch key referralCode: invalid referralCode:not_editable, BUG-SL-VIS-06). Needs sale.manage.

schema catalog ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
actor_can_manage—booleanP2-01, U12-FU-58 (GAP-2303). Acting principal holds catalog.write (CAT-02) at ALL in WEB_ADMIN right now (rbac.actor_grants()). The catalog WRITE predicate; reads use catalog.actor_can_read().
actor_can_read—booleanU12-FU-58 (GAP-2303). Acting principal holds catalog.read (CAT-01) at ALL in WEB_ADMIN right now (rbac.actor_grants()).
attribute_has_valuesp_attribute_id uuidbooleanPSW-P1-06. True when a live value of a live product uses the attribute (data_type lock, delete only with 0 values).
attribute_phasep_attribute_id uuidtextPSW-P1-05 (design §2). CATEGORY (live category) | COMMON (category_id null) | ARCHIVED (category soft-deleted); null for a missing, deleted or unreadable attribute.
attribute_scopep_category_id uuidTABLE(attribute_id uuid, category_id uuid, level integer, "position" integer)PSW-P1-05 (design §2, Q1). Live attributes of the live category and its ancestors: attribute_id, declaring category_id, level (1 = root), position; ordered by level, position, name_key, id. COMMON attributes are not included.
brand_product_countp_brand_id uuidbigintP2-01 hook, replaced by P2-02: non-deleted products assigned to the brand (0 until products exist).
category_branchp_category_id uuidTABLE(category_id uuid)PSW-P1-06 (R3). The live category with its live ancestors and descendants; empty for a missing / deleted category.
category_heightp_id uuidinteger
category_is_leafp_id uuidboolean
category_levelp_id uuidinteger
category_path_namesp_id uuidtext[]
category_product_countp_category_id uuidbigintP2-01 hook, replaced by P2-02: non-deleted products directly assigned to the category (0 until products exist).
category_subtreep_category_id uuidTABLE(category_id uuid)G1S-P1-09. The live category and its live descendants (a level-1 id includes children and grandchildren); empty for a missing / deleted category. Shared by the public category filter and search (G1S-P1-16).
combo_unavailable_componentsp_combo_id uuiduuid[]U6-P7-09, Q-5c. Ids of the components of a combo that are not ON_SALE or are deleted (sorted); {} = all live. Shared by the API (names them) and the products status guard (refuses ON_SALE).
lock_category_tree—voidP2-01. Transaction-scoped lock for category tree shape and product leaf assignment (P2-02).
manager_roles—text[]P2-01 role mirror of matrix CAT-01/02 (GAP-19). Since U12-FU-58 no access predicate reads it: catalog access follows the catalog.read / catalog.write grants.
map_legacy_product_unitsp_unit_id uuidinteger
name_keyvalue texttextP2-01 Rule #8 key: trim + NFC + Unicode lower (pg_c_utf8). No diacritic or inner-space folding (gap).
product_blockersp_ids uuid[]TABLE(product_id uuid, kind text, ref_id uuid, ref_name text, ref_state text)definerU6-P2-19, U6-P7-09, U12-FU-58. Unfinished campaigns and ON_SALE/DRAFT combos (a DISCONTINUED or deleted combo does not block) that block discontinuing/deleting each of <= 500 products (Rule #5, SP-US-04); catalog.read holders only. Definer, fails closed if the owner is not RLS-exempt.
product_campaignsp_product_id uuidTABLE(campaign_id uuid, name text, campaign_type text, state text, sku text)definerP2-06, U12-FU-58. Campaigns a product joined (SP-US-03 view only); catalog.read holders only, empty for everyone else.
product_column_codes—text[]U12-P2-19. The 16 product-list column codes in the fixed order (SKU, BARCODE, NAME first: owner answer GAP-COL-01).
product_columns_validp_columns text[]booleanU12-P2-19. Canonical column set: known codes, locked present, no duplicate, fixed order.
product_combo_countp_product_id uuidbigint
product_default_columns—text[]U12-P2-19. Default product-list columns: the 8 columns of the current table (2 locked + 6).
product_history_actorsp_product_id uuidTABLE(account_id uuid, display_name text, event_count integer)definerU12-P3-09, U12-FU-58. Distinct actors of a product with event counts and names, catalog.read holders only.
product_history_export_rowsp_product_id uuid, p_actor_ids uuid[], p_types text[], p_fields text[], p_from timestamp with time zone, p_to timestamp with time zone, p_limit integerSETOF catalog.product_history_rowdefinerU12-P3-09, U12-FU-60. Same rows as the list for the export; only a live holder of catalog.history.export (matrix CAT-04, super_admin; MFA is the API step-up); at most p_limit (<= 50001) events.
product_history_fields—text[]
product_history_gatep_export boolean, p_product_id uuidvoid
product_history_guard—trigger
product_history_readp_product_id uuid, p_actor_ids uuid[], p_types text[], p_fields text[], p_from timestamp with time zone, p_to timestamp with time zone, p_limit integer, p_offset integerSETOF catalog.product_history_rowdefinerU12-P3-09, U12-FU-58. One page of a product's change events (catalog.read holders), newest first, total in every row, 24-month window. Definer (the table has no privilege); returns stored values, masking is the API's step.
product_history_rowsp_product_id uuid, p_actor_ids uuid[], p_types text[], p_fields text[], p_from timestamp with time zone, p_to timestamp with time zone, p_limit integer, p_offset integerSETOF catalog.product_history_row
product_locked_columns—text[]U12-P2-19. Always-shown product-list columns (SKU, NAME).
product_open_campaign_countp_product_id uuidbigintdefinerP2-06 (replaces the P2-02 stub): unfinished campaigns (DRAFT/REVIEW/ACTIVE/CLOSING) containing the product.
product_unit_in_usep_unit_id uuidtextPSW-P1-01, PSW-P1-04, PSW-P1-06. Why a unit cannot be soft-deleted (constraint product_units_in_use): PRODUCTS | BASE_OF_UNITS | ACCESSORIES | ATTRIBUTES | ATTRIBUTE_VALUES, null = free. A replacement keeps every branch.
product_unit_unmatched—TABLE(label_key text, spellings text[], live_product_count bigint, deleted_product_count bigint, reason text)U12-P2-16. Old products.unit labels with no canonical unit (status "chua ghep"): spellings, live/deleted product counts, reason NO_MATCH | OVER_LENGTH | UNIT_INACTIVE | DELETED_ONLY. Units are never auto-created from these labels (G-UNIT).
purge_product_historyp_batch integerintegerdefinerU12-P2-18 (G-HISTORY 24 months). Deletes product_change_events older than 24 months (oldest first, batched). The only deletion path; pi_worker only. A scheduler job calling it is a follow-up.
record_product_historyp_operation text, p_request_id text, p_correlation_id text, p_source text, p_occurred_at timestamp with time zone, p_events jsonbTABLE(product_id uuid, event_id uuid, replayed boolean)definerU12-P2-18. Appends one event per product to product_change_events in the product transaction; actor from the acting principal (catalog manager), idempotent per (actor, operation, request, product). Definer; fails closed if the owner is not RLS-exempt.
restore_productsp_ids uuid[], p_expected_versions integer[]TABLE(product_id uuid, outcome text, version_after integer, category_cleared boolean, brand_cleared boolean)U12-P2-17 (G-RESTORE). All-or-nothing restore of soft-deleted products as DISCONTINUED; needs catalog.actor_can_manage() (= the Delete permission). Optimistic version per id, ALREADY_LIVE is a no-op, dead category/brand cleared to NULL. U12-FU-57: a deleted unit is cleared and an unlinked label is linked to the ACTIVE unit of the same name_key.
staff_display_namesp_ids uuid[]TABLE(account_id uuid, display_name text)definerU6-P2-19, U12-FU-58. profiles.full_name of WEB_ADMIN staff ids (<= 1000) for catalog.read holders only; no row when the account has no profile (NEW-SP-17). Definer, fails closed if the owner is not RLS-exempt.

schema customer ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
accounts_by_referralp_code textSETOF uuiddefinerU6-P2-23. Customers whose profile referral code equals the whole given code (exact); customer readers.
accounts_in_provincep_province textSETOF uuiddefinerU6-P7-61 / U6-P7-44. Account ids with a live address whose province text contains the unit name as whole words (case/diacritic insensitive), for customer readers; empty otherwise. The key is folded once per distinct stored text, not per address.
accounts_in_tierp_tier uuidSETOF uuiddefinerU6-P2-23, U28-P7-01. Customers whose current USER Tier (customer.tier_heads) is the given definition.
active_rank_ofp_account uuidbigintdefinerU6-P2-23. Active USER rank points of a customer (for the remaining-to-next figure); NULL unless a customer reader.
actor_can_manage—boolean
actor_can_read—boolean
actor_holdsroles text[]booleanP2-04. Acting principal holds one of these WEB_ADMIN roles right now (ACTIVE account and membership).
addresses_ofp_account uuidTABLE(id uuid, address_type text, recipient_name text, recipient_phone_masked text, province text, district text, ward text, address_line_masked text, is_default boolean, recipient_phone text, address_line text)definerU6-P2-23. Every live delivery address of a customer, full recipient phone and street line (masked columns kept for compatibility), default first, for customer readers.
assign_codep_account uuidtextdefinerU6-P7-61 Q-3. Existing customer code, else the next one (KH + ddmmyyyy + 6 digits, global counter) written to customer_codes; PT409 customer_code_exhausted past 999999; P0002 for a non-customer. Owner only.
column_codes—text[]U6-P2-23. The 16 customer-list column codes in the fixed PRD order.
columns_validp_columns text[]booleanU6-P2-23. Canonical column set: known codes, locked present, no duplicate, fixed order.
completed_states—text[]P2-05. Order states counted as Completed in customer aggregates: FULFILLED only (delivered and fully paid).
default_addresses_forp_accounts uuid[]TABLE(account_id uuid, address_id uuid, address_type text, recipient_name text, recipient_phone text, province text, district text, ward text, address_line text)definerU6-P2-23. The live default delivery address of each given customer, full form; customer readers.
default_columns—text[]U6-P2-23. Default customer-list columns (3 locked + 5), KH-US-01.
directory—TABLE(account_id uuid, full_name text, phone_masked text, user_status text, account_status text, is_sale boolean, joined_at timestamptz, customer_code text, phone text, phone_e164 text, email text, date_of_birth date, gender text, referral_code text, sale_id uuid, sale_code text, login_email text, login_email_masked text)definerU6-P2-23, #299, PPI-P3-07. Customer directory (APP_USER accounts) for customer readers, full personal data (X-05, NFR #4): code, phone, profile email, birth date, gender, referral code, Sale id/code (sale_codes) only when the APP_SALE account is ACTIVE or LOCKED (#299); login email (accounts.email_normalized, B-05) and its mask; phone_masked kept for compatibility (DEV-KH-01). Empty otherwise.
format_codep_joined_at timestamp with time zone, p_number integertextU6-P7-61 Q-3. KH + ddmmyyyy (Vietnam date of the join instant) + 6-digit counter. The only place of the code shape.
issue_code—triggerdefiner
lock_groups—voidP2-04. Transaction lock for default switch, group delete/move, transfers and customer group edits.
locked_columns—text[]U6-P2-23. Always-shown customer-list columns (Ma KH, Ten, SDT).
manager_roles—text[]P2-04 / FU-OPSGRANTS. WEB_ADMIN roles that read and manage customers and groups at ALL: operations, admin (matrix O-01, OPS-03..05; DEC-OPS-CUSTOMER-READ, interim GAP-2015).
mask_address_lineline texttextFU-L3-CUSTOMER-DETAIL. Staff display mask of a street line; single place to change once O-05 is decided (GAP-2120).
mask_phonephone texttextP2-04. Staff display mask of an E.164 phone (Admin SPEC format; GAP-06 open).
name_keyvalue texttext
open_order_countp_account uuidintegerdefinerFU-L3-CUSTOMER-DETAIL. Open orders of a customer for customer readers; NULL otherwise (never 0).
open_order_states—text[]FU-L3-CUSTOMER-DETAIL. Order states that are not terminal (derived from ordering.transition_allowed).
point_link_refp_account uuidtextdefinerP2-05. PiPoint link reference of a customer for the server-side balance read; null unless a customer reader.
province_keyp_value texttextU6-P7-61 NEW-KH-13. Comparison key of a province text: case, diacritics, punctuation and a leading Thanh pho/TP/Tinh folded away.
purchase_historyp_account uuid, p_limit integer, p_offset integerTABLE(order_id uuid, campaign_type text, committed_cycle_count integer, product_id uuid, sku text, product_name text, line_count integer, v0_vnd bigint, final_total_vnd bigint, state text, created_at timestamptz, total_count bigint, delivered_cycles integer, code text)definerP2-05 / FU-44-06. One page of a customer's orders, all statuses, newest first, for customer readers; empty otherwise. delivered_cycles = periods of a Recurring order whose shipment is DELIVERED (NULL for Group Buy). #298: code = the order code.
purchase_summary—TABLE(account_id uuid, completed_order_count integer, products_purchased bigint, last_purchase_at timestamptz, total_spend_vnd bigint, spend_complete boolean)definerP2-05. Completed-only aggregates per buyer (count, units, last purchase, final-price spend) for customer readers; empty otherwise.
purchase_summary_forp_accounts uuid[]TABLE(account_id uuid, completed_order_count integer, products_purchased bigint, last_purchase_at timestamptz, total_spend_vnd bigint, spend_complete boolean)definerFU-PERF-E. customer.purchase_summary() restricted to the given accounts (same aggregate, same gate); empty unless a customer reader.
reader_roles—text[]P2-04. Extra WEB_ADMIN roles with customer.read at ALL. Empty: M-01 TEAM has no row source (no widening).
search_accountsp_keyword textSETOF uuiddefinerU6-P2-23 KH-US-01 AC04. Customers whose code, name or phone contains the keyword; customer readers only.
search_hitp_code text, p_full_name text, p_phone_e164 text, p_keyword textbooleanU6-P2-23 KH-US-01 AC04. Keyword contained in the customer code, name key or phone (E.164 or 0-national); blank = true.
self_action_guard—triggerdefinerPPI-P1-04 (DEC-PPI-OWN02-COI-SELF). BEFORE ROW trigger: refuses (customer_self_action, 42501) an Admin edit of description / tags or a TRANSFER group move of the actor's own customer account (identity.same_person).
set_user_statusp_account uuid, p_status texttextdefinerP2-04. KH-US-03 lock/unlock of the APP_USER membership for customer managers; account lock wins.
tags_validtags text[]boolean
tier_headsp_accounts uuid[], p_at timestamp with time zoneTABLE(account_id uuid, definition_id uuid, legacy_version_id uuid, achieved_at timestamptz)U28-P7-01. Current USER Tier head of User App customers (new history head, else legacy head, else Standard) and its instant (NULL on the default Standard). Internal.
tier_ofp_accounts uuid[]TABLE(account_id uuid, tier_id uuid, tier_version_id uuid, tier_code text, tier_name text, rank_order integer, is_standard boolean, achieved_at timestamptz, next_tier_name text, next_rank_threshold bigint)definerU6-P2-23, U28-P7-01. Current USER Tier per customer, achieved_at, next Tier; the customer Tier set when a set version is in force (renamed / deleted Tiers by their last name), the legacy ladder otherwise; customer readers.
tier_options—TABLE(tier_id uuid, tier_version_id uuid, code text, name text, rank_order integer, is_standard boolean)definerU6-P2-23, U28-P7-01. USER Tiers of the ladder in force (set version, else legacy versions), Standard included, by rank, for the Tier filter; customer readers.

schema mission ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
actor_canp_action textbooleanP4-02. Acting principal may read/write/pause/assign Missions (matrix MS-01..MS-04) right now.
actor_has_rolep_roles text[]boolean
add_contributionsp_account uuid, p_app app_code, p_metric text, p_amount bigint, p_source_type text, p_source_id text, p_occurred_at timestamp with time zone, p_event_id uuid, p_event_type text, p_correlation_id text, p_exclude uuidintegerdefinerP4-04. Internal: CONTRIBUTE rows for the in-window assignments of (account, app); idempotent per source.
affiliate_metrics—text[]
assigner_roles—text[]P4-02 mirror of matrix MS-04 mission.assign: GAP-45, empty.
assignment_progressp_assignments uuid[], p_at timestamp with time zoneSETOF mission.progress_rowP4-06. Internal derivation of state + criterion figures from the evidence at p_at (a test may pass a past/future instant).
contribute_affiliate_orderp_order_id uuid, p_order_version integer, p_event_id uuid, p_event_type text, p_correlation_id textTABLE(outcome text, contributed integer, reversed integer)definerP4-04. pi_worker only: Affiliate qualified order (one unit) and one-cycle base from a confirmed deposit of an ATTRIBUTED order; a cancellation writes inverse rows referencing them.
contribute_completed_recurring_orderp_order uuid, p_event_id uuid, p_correlation_id textintegerdefinerU19-R20 (GAP-W-VD-06). DELIVERED_ORDER_COUNT / VALUE once for a completed Recurring order, source ORDER.
contribute_delivered_shipmentp_shipment_id uuid, p_shipment_version integer, p_event_id uuid, p_event_type text, p_correlation_id textTABLE(outcome text, contributed integer, excluded integer)definerU19-R20 + U19-R34. Applied DELIVERED fact -> DELIVERED_* of its Group Buy orders and RECURRING_CYCLE_DELIVERED_COUNT 1 per COMMITTED Recurring cycle (buyer + attributed Sale), COD collected or not (Word B186.R02, OWN-20-03), also for a cycle kept by the shortage cancel of its order (OWN-21-02).
contribute_referral_milestonep_referral_id uuid, p_milestone text, p_referrer uuid, p_referee uuid, p_event_id uuid, p_event_type text, p_correlation_id textTABLE(outcome text, metric text, contributed integer)definerP4-04. pi_worker only: one unit per referred person on the referrer's Referral metric, from the P4-11 row.
counted_contributionsp_assignment uuidSETOF mission_contributions
criterion_progressp_assignment uuidTABLE(criterion_id uuid, metric text, threshold bigint, contributed bigint, reversed bigint, contribution_count integer, reversal_count integer, last_contribution_id uuid, last_recorded_at timestamptz)
mask_refp_ref texttext
metric_sourcep_metric textTABLE(source_status text, gap text, reason text)P4-06. Whether a metric has a wired source (READY) or none (UNAVAILABLE + GAP + reason). Never 0 for UNAVAILABLE.
order_refund_metrics—text[]
pause_impactp_version_id uuidTABLE(assigned_count bigint, completed_count bigint, in_progress_count bigint, with_progress_count bigint, contribution_count bigint, reversal_count bigint, as_of timestamptz)definerP4-02. Read-only pause preview counts for one Mission version; requires mission.actor_can('pause').
pauser_roles—text[]P4-02 mirror of matrix MS-03 mission.pause (PROPOSED, GAP-45).
progress_after_contribution—triggerdefiner
progress_after_version_change—triggerdefiner
progress_evidencep_assignment uuid, p_criterion uuid, p_limit integer, p_offset integerTABLE(contribution_id uuid, criterion_id uuid, metric text, kind text, amount bigint, reverses_contribution_id uuid, counted boolean, source_type text, source_ref text, source_masked boolean, source_event_type text, occurred_at timestamptz, recorded_at timestamp with time zone, reversed_amount bigint, drift boolean, reversal_evidence jsonb, total bigint)definer
progress_listp_account uuid, p_purpose text, p_limit integer, p_offset integerSETOF mission.progress_rowdefiner
progress_reader_roles—text[]P4-06 mirror of matrix MPR-02 mission_progress.read (WEB_ADMIN, PROPOSED, GAP-174).
progress_scope—textdefiner
progress_scope_idsp_account uuid, p_purpose textTABLE(assignment_id uuid, assigned_at timestamptz)definer
progress_snapshot_drift—TABLE(assignment_id uuid, criterion_id uuid, reason text)
progress_totalp_account uuid, p_purpose textbigintdefiner
progress_visiblep_assignment uuidbooleandefiner
reader_roles—text[]P4-02 mirror of matrix MS-01 mission.read (PROPOSED, GAP-45).
rebuild_progressp_assignment uuidintegerdefinerP4-06. Operator/owner rebuild of the snapshot cache from the evidence (one assignment, or all). No role is granted it.
refresh_progressp_assignment uuidvoiddefinerP4-06. Internal: re-derive the snapshot and the set-once completed_at of one assignment from mission_contributions.
refund_fence_contribution—triggerdefiner
reverse_affiliate_orderp_order_id uuid, p_occurred_at timestamp with time zone, p_event_id uuid, p_event_type text, p_correlation_id textintegerdefiner
reverse_order_contributionsp_order uuid, p_reason text, p_case uuid, p_decision uuid, p_at timestamp with time zone, p_event_id uuid, p_event_type text, p_correlation_id text, p_only uuidTABLE(reversed integer, recorded integer)definer
reverse_order_refundp_order uuid, p_event_id uuid, p_event_type text, p_correlation_id text, p_only uuidTABLE(outcome text, reversed integer, recorded integer)definer
reverse_refunded_orderp_aggregate_type text, p_aggregate_id uuid, p_event_id uuid, p_event_type text, p_correlation_id textTABLE(outcome text, reversed integer, recorded integer)definerP4-05. pi_worker only: inverse Mission contributions of an Order whose refund case is REFUNDED or whose latest cancellation decision is REFUND_FULL; exact amounts, one per original, evidence per reason; never touches a Tier, reward or rank lot.
shortage_kept_cyclep_cycle textbooleandefinerU19-R34 (OWN-21-02). True for a cycle kept by the whole-order shortage cancel of its Recurring order (not Đã hủy).
writer_roles—text[]P4-02 mirror of matrix MS-02 mission.write (PROPOSED, GAP-45).

schema privacy ​

P1-14. Privacy helpers: matrix mirrors, masking, consent/request/hold/export/erasure functions.

HàmTham sốTrả vềMô tả
actor_can_hold—boolean
actor_can_review—boolean
actor_has_staff_rolep_roles text[]booleandefiner
actor_is_subjectp_apps text[]booleandefiner
assert_owner_bypasses_rls—void
close_accountp_account uuid, p_reason text, p_release_pipoint booleanjsonbdefinerPPI-P3-09 closure, factored by PPI-P3-15. Closes a CUSTOMER account: memberships LOCKED, sessions revoked and live pipoint link dead (p_reason ACCOUNT_DELETED | PIPOINT_ACCOUNT_DELETED; released when p_release_pipoint), password credential deleted, live wallet link ended, phone / email NULL, LOCKED + deleted_at. Idempotent. Internal; the caller audits.
close_deleted_account—triggerdefinerPPI-P3-09 (DEC-PPI-GAP-04 c). Deferred AFTER UPDATE trigger of privacy_requests on a SELF_SERVICE deletion: memberships LOCKED, sessions revoked (ACCOUNT_DELETED), PiPoint link dead + released, password credential deleted, phone / email NULL, account LOCKED + deleted_at; audit privacy.account_deleted.
complete_exportp_request_id uuid, p_expected_version integer, p_export_id uuid, p_run_id uuid, p_file_name text, p_size integer, p_sha256 text, p_row_counts jsonbTABLE(outcome text, export_id uuid, expires_at timestamptz, version integer)definerP1-14. privacy.export job: records the package (expiry from PRIVACY_EXPORT_PACKAGE) and completes.
consent_purpose_guard_status—trigger
delete_own_accountp_request_id text, p_correlation textTABLE(id uuid, status text, version integer, created_at timestamptz, job_slot text)definerPPI-P3-09 (D-12, DEC-PPI-GAP-04). requestPrivacyDeletion of the acting APP_USER subject: refused under an ACTIVE legal hold (legal_hold_active); else the DELETION request is APPROVED by SELF_SERVICE and the erasure job enqueued; the account is closed at commit (trigger privacy_requests_close_deleted_account).
erase_profile_piip_account uuid, p_actor uuidintegerdefinerU6-P7-44. PROFILE_PII handler of privacy.erase_subject: profiles, Sale profile + change history, customer admin fields and the subject's files. Refuses a held subject and any call outside an approved erasure window.
erase_subjectp_request_id uuid, p_run_id uuidTABLE(outcome text, request_status text, version integer, purged_paths text[])definerP1-14 / U6-P7-44 / G1S-P1-16. privacy.erasure job: hold check, per-category anonymise/delete/retain from retention_policies; PROFILE_PII covers profile, Sale profile + change history, customer admin fields and the subject's files; SEARCH_HISTORY deletes the search keywords.
erasing_subject—uuiddefinerU6-P7-44. The subject of the APPROVED DELETION request that privacy.erase_subject is executing in this transaction, else null. Opens the immutability guards of sale_profile_changes / media for the anonymisation only.
erasure_job_name—text
export_job_name—text
export_sourcep_request_id uuidTABLE(outcome text, account_id uuid, request_version integer, package jsonb)definerP1-14. privacy.export job: the APPROVED EXPORT subject's own data (masked), or why not.
hold_record_event—trigger
hold_roles—text[]
mask_emailp texttextPPI-P3-07. n***@domain (audit/mask.ts maskMailAddress shape); **** when there is no local part; null stays null.
mask_phonep texttext
purge_expired_exportsp_run_id uuidTABLE(outcome text, purged integer, held integer, purged_paths text[])definerP1-14. privacy.export_purge job: expired packages purged under an APPROVED policy; held subjects kept.
purge_job_name—text
record_consentp_purpose text, p_action text, p_purpose_version integer, p_expected_seq integer, p_request_id text, p_correlation textTABLE(record_id uuid, seq integer, action text, purpose_version integer, changed boolean)definerP1-14. grantConsent/withdrawConsent: appends one consent_records row for the acting subject.
release_holdp_id uuid, p_expected_version integer, p_reason textTABLE(id uuid, account_id uuid, status text, version integer, released_at timestamptz)definer
request_guard_transition—trigger
request_record_event—trigger
retention_guard_status—trigger
review_requestp_id uuid, p_expected_version integer, p_decision text, p_reason text, p_request_id textTABLE(id uuid, status text, version integer, job_slot text)definer
reviewer_roles—text[]
set_holdp_scope_kind text, p_account_id uuid, p_order_id uuid, p_reason text, p_request_id text, p_correlation textTABLE(id uuid, account_id uuid, status text, version integer, set_at timestamptz)definer
subject_on_holdp_account_id uuidbooleandefiner
submit_requestp_kind text, p_request_id text, p_correlation textTABLE(id uuid, status text, version integer, created_at timestamptz)definerP1-14 / PPI-P3-09. Files an EXPORT request (SUBMITTED, reviewed) of the acting APP_USER subject; a DELETION is privacy.delete_own_account (self-service, approved at once). One open request per kind.

schema report ​

P4-20. Source-tied report read models (functions only); see schema-ownership s5bs.

HàmTham sốTrả vềMô tả
accessp_kind texttextdefiner
assert_inp_name text, p_value text, p_allowed text[]void
assert_windowp_from timestamp with time zone, p_to timestamp with time zonevoid
campaign_cohortp_cohort text, p_from timestamp with time zone, p_to timestamp with time zone, p_type textTABLE(campaign_type text, campaigns bigint, confirmed bigint, failed bigint, rate_numerator bigint, rate_denominator bigint, success_rate numeric)definerP4-20. Closed (outcome recorded) vs open campaigns; rate = numerator / denominator, NULL not 0.
campaign_funnelp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_type textTABLE(campaign_id uuid, campaign_type text, campaign_name text, campaign_state text, orders bigint, buyers bigint, deposit_confirmed bigint, deposit_failed bigint, locked bigint, fulfilled bigint, cancelled bigint, forfeited bigint, is_total boolean)definerP4-20. Orders per campaign by milestone reached for ONE explicit date basis; SQL totals row; READ scope.
codp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_value_basis textTABLE(day_vn date, delivered bigint, delivered_due_vnd bigint, collected bigint, collected_vnd bigint, remitted bigint, remitted_vnd bigint, not_collected bigint, not_collected_vnd bigint, awaiting_remittance bigint, awaiting_remittance_vnd bigint, is_total boolean)definerP4-20. COD cohort by ONE explicit stage date: delivered / collected / remitted apart plus the two gaps; MONEY scope.
cod_statusp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_value_basis textSETOF report.source_rowdefiner
cohort_statusp_cohort text, p_from timestamp with time zone, p_to timestamp with time zone, p_type textSETOF report.source_rowdefiner
ended_daysp_from timestamp with time zone, p_to timestamp with time zoneSETOF date
figurep_value numeric, p_complete booleannumericP4-20. Zero becomes NULL while a feeding source is INCOMPLETE.
funnel_statusp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_type textSETOF report.source_rowdefiner
order_cohortp_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_type textTABLE(order_id uuid, campaign_id uuid, campaign_type text, state text, buyer_id uuid, v0_vnd bigint, deposit_vnd bigint, points_used integer, points_value_vnd bigint)
order_events_statusp_campaign uuid, p_to timestamp with time zoneSETOF report.source_row
ordersp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_type text, p_value_basis textTABLE(campaign_type text, order_state text, orders bigint, committed_vnd bigint, deposit_vnd bigint, points_used bigint, points_value_vnd bigint, locked_orders bigint, final_total_vnd bigint, is_total boolean)definerP4-20. Committed Order value by state (V0, deposit, points value, close total: MC = LOCK row, ĐK = Σ cycle close values, DEC-U28-16); MONEY scope; basis only echoed.
orders_statusp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_type text, p_value_basis textSETOF report.source_rowdefiner
payment_atp_basis text, p_provider_at timestamp with time zone, p_recorded_at timestamp with time zonetimestamptzP4-20. PROVIDER_TIME | RECORDED bucket instant.
paymentsp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_mode text, p_value_basis textTABLE(day_vn date, provider_mode text, kind text, status text, transactions bigint, amount_vnd bigint, is_total boolean)definerP4-20. Provider transactions per VN day x kind x status (captured / refunded / FAILED / UNKNOWN apart); MONEY scope.
payments_statusp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_mode text, p_value_basis textSETOF report.source_rowdefiner
point_atp_basis text, p_id uuid, p_operation text, p_business_date date, p_provider_at timestamp with time zone, p_requested_at timestamp with time zonetimestamptz
pointsp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zoneTABLE(operation text, adjust_direction text, target_bucket text, rate_snapshot_vnd numeric, rate_policy_version text, requests bigint, points bigint, value_vnd numeric, is_total boolean)definerP4-20. ACCEPTED point requests per operation / bucket at their OWN rate snapshot; totals per operation; VND needs MONEY.
points_statusp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zoneSETOF report.source_rowdefiner
policy_undecidedp_report text, p_value_basis textTABLE(policy text, decision_ref text)P4-20 + FU-636. Open decisions behind a report (GAP-199): VALUE_BASIS (not for Sale performance under GROSS), DATE_BASIS, COHORT_DEFINITION; never decided here.
requirep_kind texttextdefinerP4-20. Scope of the live grant for READ | MONEY | SALE, else 42501.
sale_attribution_pendingp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zonebigint
sale_gatep_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_team uuidtextdefiner
sale_performancep_group text, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_team uuid, p_value_basis textTABLE(team_id uuid, sale_account_id uuid, current_team_id uuid, attributed_customers bigint, attributed_orders bigint, qualified_orders bigint, qualified_base_vnd bigint, cancelled_qualified_orders bigint, cancelled_qualified_base_vnd bigint, fulfilled_qualified_orders bigint, referral_customers bigint, unique_customers bigint, moved_orders bigint, gross_orders bigint, gross_value_vnd bigint, is_total boolean)definerP4-20 + FU-636. Sale performance by attribution-time team (HISTORICAL_SNAPSHOT) or Sale, with the GROSS order count and value by order creation time (DEC-S-GMV-BASIS); TEAM (M-03) or ALL (B-01) scope.
sale_scanp_scope text, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_team uuidTABLE(assignment_id uuid, order_id uuid, buyer_account_id uuid, sale_account_id uuid, attributed_team_id uuid, current_team_id uuid, order_state text, qualification text, base_vnd bigint, in_created boolean, in_basis boolean, v0_vnd bigint)
sale_statusp_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_team uuid, p_value_basis textSETOF report.source_rowdefiner
vn_dayp_at timestamp with time zonedate
vn_daysp_from timestamp with time zone, p_to timestamp with time zoneSETOF date

schema attribution ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
actor_can_disable—booleandefiner
actor_is_link_owner—booleandefinerP4-11. Matrix S-03/S-04/ATR-01..03 mirror: ACTIVE account + ACTIVE membership + base role in the claimed app.
actor_is_referral_claimant—booleandefiner
assign_orderp_order_id uuid, p_event_id uuid, p_event_type text, p_correlation_id textTABLE(assignment_id uuid, outcome text, policy_version_id uuid, created boolean)definerP4-11 + FU-716/719. Last-Touch (72 h inclusive, versioned) decision per order.created: own and bound anonymous touches, OWNER_LOCKED for a non-ACTIVE owner; first row wins.
buyer_affiliate_touchesp_buyer uuid, p_at timestamp with time zoneSETOF attribution_touchesdefiner
claim_affiliate_touchesp_visitor_key text, p_correlation_id textTABLE(outcome text, bound_count integer)definerFU-716 SPEC-02. The caller binds its anonymous Affiliate touches of the last 72 h to itself (ATR-06); first claim wins per touch.
claim_referral_signupp_visitor_key text, p_correlation_id textTABLE(milestone_id uuid, milestone text, outcome text, referral_id uuid, referral_link_id uuid, referrer_account_id uuid, referrer_app text, referrer_team_id uuid, referred_account_id uuid, occurred_at timestamptz)definerP4-12. The caller binds itself to its sign-up Last-Touch Referral (once; ATR-06); identity_mismatch refused.
create_affiliate_linkp_campaign_id uuid, p_campaign_product_id uuid, p_correlation_id textTABLE(link_id uuid, created boolean)definer
create_referral_linkp_correlation_id textTABLE(link_id uuid, created boolean)definer
disable_affiliate_linkp_id uuid, p_expected_version integer, p_reason textTABLE(link_id uuid, version integer)definer
first_paid_factp_account uuidTABLE(order_id uuid, paid_at timestamptz)definer
guard_link_update—trigger
link_admin_roles—text[]P4-11. WEB_ADMIN roles that may stop an Affiliate link. Empty: matrix ATR-04 is a GAP (GAP-58).
link_owner_activep_owner uuid, p_app textbooleandefiner
masked_buyerp_assignment uuidtextdefiner
masked_referredp_milestone uuidtextdefiner
milestone_factp_id uuid, p_milestone text, p_outcome textTABLE(milestone_id uuid, milestone text, outcome text, referral_id uuid, referral_link_id uuid, referrer_account_id uuid, referrer_app text, referrer_team_id uuid, referred_account_id uuid, occurred_at timestamptz)definer
new_code—text
open_linkp_kind text, p_code text, p_visitor_key text, p_request_id text, p_correlation_id textTABLE(outcome text, target_kind text, campaign_id uuid, campaign_product_id uuid, touch_id uuid)definerP4-12. Public link open (ATR-05): safe in-app target kind only, no owner data; records a touch when OPENED.
owner_rolep_app texttext
policy_atp_at timestamp with time zoneattribution_policy_versions
preview_referrer—TABLE(code text, masked_name text)definerG2I-P3-01. Read-only preview of attribution.assign_order for an order of the actor created now: link code + masked owner name when it would be ATTRIBUTED, else no row.
public_sale_companionp_code textTABLE(display_name text, rank_name text, successful_orders bigint, phone text, zalo_phone text, referral_code text, avatar_path text)definerG1S-P1-10 (R9, BR-KP-08). Sale đồng hành card of a link code: name, Hạng, LOCK-closed attributed orders, phone, Zalo (= phone, GAP-G1S-09), Mã giới thiệu, public avatar path. One row only for an ACTIVE link (Affiliate: Campaign still open) owned by an ACTIVE named Sale; otherwise no row and no reason. pi_api only.
qualify_affiliate_orderp_order_id uuidTABLE(outcome text, assignment_id uuid, buyer_account_id uuid, recipient_account_id uuid, recipient_app app_code, deposit_at timestamptz, window_ends_at timestamp with time zone, base_vnd bigint, base_basis text)definerP4-13. Single Affiliate qualification rule set shared by Mission contributions (P4-04) and reward requests (P4-13): Last-Touch winner, self-order excluded, deposit inside the window, one-cycle base. Definer-only.
record_ekyc_verifiedp_account uuid, p_identity_ref text, p_occurred_at timestamp with time zone, p_source_type text, p_source_id text, p_correlation_id textTABLE(milestone_id uuid, milestone text, outcome text, referral_id uuid, referral_link_id uuid, referrer_account_id uuid, referrer_app text, referrer_team_id uuid, referred_account_id uuid, occurred_at timestamptz)definerP4-12. EKYC_VERIFIED once per referred person; one hashed eKYC identity per referred account; pi_worker only.
record_first_paidp_order uuid, p_correlation_id textTABLE(milestone_id uuid, milestone text, outcome text, referral_id uuid, referral_link_id uuid, referrer_account_id uuid, referrer_app text, referrer_team_id uuid, referred_account_id uuid, occurred_at timestamptz)definerP4-12. FIRST_PAID from PIDEAL state (earliest SETTLED REMAINING of the order owner); pi_worker only.
record_referral_milestonep_account uuid, p_milestone text, p_occurred_at timestamp with time zone, p_source_type text, p_source_id text, p_correlation_id textTABLE(milestone_id uuid, outcome text)definer
record_referral_signupp_account uuid, p_visitor_key text, p_source_type text, p_source_id text, p_correlation_id textTABLE(milestone_id uuid, outcome text)definer
record_touchp_kind text, p_code text, p_visitor_key text, p_request_id text, p_correlation_id textTABLE(touch_id uuid, touched_at timestamptz, recorded boolean)definerP4-11. Record one link open (server time; account or opaque visitor key); retried request id = same row.

schema pipoint_adjust ​

P3-21. PiPoint ADJUST proposals (maker/checker): role lists, definer commands and worker reads.

HàmTham sốTrả vềMô tả
actor_canp_action textboolean
actor_has_rolep_roles text[]boolean
checker_roles—text[]P3-21 + PPI-P5-07 mirror of matrix F-07 point_adjust.approve: finance (GAP-PPI-06b = a; GAP-08 closed).
compensated_redeemp_corrects uuid, p_recon uuiduuid
compensation_conflicts—TABLE(redeem_request_id uuid, redeemed_points integer, returned_points bigint, reversal_points bigint, adjust_points bigint)definerFU-1822. Detection of a double compensation (reversals + live CREDIT adjustments > redeemed). Owner only.
counted_reversalsp_redeem uuidTABLE(points bigint, unresolved boolean)
decidep_id uuid, p_expected_version integer, p_decision text, p_payload_hash bytea, p_note text, p_correlation_id correlation_refSETOF point_adjustmentsdefinerP3-21. Checker approves or rejects a PENDING proposal: never the maker, version and payload hash bound.
decide_rank_debitp_id uuid, p_expected_version integer, p_decision text, p_payload_hash bytea, p_note text, p_correlation_id correlation_refSETOF rank_adjustmentsdefinerPPI-P5-07 (W-03 b). Checker (F-07) decides: never the maker, version and payload hash bound. APPROVED writes one SIGNED rank_debits row and evaluates the customer; nothing is sent to PiPoint.
delivery_statesp_ids uuid[]TABLE(adjustment_id uuid, status text, result_code text, provider_recorded_at timestamptz, result_available integer)definer
dispatch_inputp_id uuidTABLE(id uuid, account_id uuid, role text, direction text, points integer, reason_code text, related_order_id uuid, requested_by uuid, decided_by uuid, decided_at timestamptz, business_date text, rate_snapshot_vnd text, rate_policy_version text, request_id text, correlation_id text, recall_link_id uuid)definerP3-21. What the ADJUST dispatch (pi_worker) reads about one APPROVED adjustment. PPI-P3-14, #479 A: recall_link_id = the slip's link for a system recall slip (RETURN_RECALL, FAILED_DELIVERY_RECALL; the send is pinned to it, live or ended), null for a MANUAL slip (live link).
dispatch_job_name—textP3-21. Job name of the ADJUST dispatch run (slot adjust:<point_adjustments.id>).
history_wallet_refp_account uuidtextdefinerPPI-P8-02. PiPoint uid of the account's live wallet link (null = not linked) for the ADJ-01 readers only (PT403 forbidden otherwise), so the API can read the customer's PiPoint history. Never returned to a client.
is_approved_requestp_operation text, p_source text, p_request_id text, p_account uuid, p_points integer, p_direction text, p_maker uuid, p_checker uuidbooleandefiner
live_credit_pointsp_redeem uuid, p_exclude uuidbigint
maker_roles—text[]P3-21 + PPI-P5-07 mirror of matrix F-06 point_adjust.request: operations (GAP-PPI-06b = a).
payload_hashp_account uuid, p_link uuid, p_role text, p_direction text, p_points integer, p_reason_code text, p_reason_text text, p_evidence uuid[], p_recon uuid, p_corrects uuid, p_order uuid, p_rate numeric, p_rate_version text, p_maker uuidbytea
proposep_account uuid, p_role text, p_direction text, p_points integer, p_reason_text text, p_recon uuid, p_corrects uuid, p_order uuid, p_correlation_id correlation_refSETOF point_adjustmentsdefiner
propose_rank_debitp_source uuid, p_reason_text text, p_correlation_id correlation_refSETOF rank_adjustmentsdefinerPPI-P5-07 (W-03 b) + PPI-P7-05. Maker (F-06) proposes the rank-only debit of a customer ADJUST DEBIT slip PiPoint refused for insufficient points: the slip's account and points, reason code RANK_ONLY_DEBIT, one per slip. Nothing is written to the rank yet.
rank_payload_hashp_account uuid, p_points integer, p_reason_code text, p_reason_text text, p_evidence uuid[], p_source uuid, p_maker uuidbytea
reader_roles—text[]P3-21 + PPI-P5-07 mirror of matrix ADJ-01 point_adjust.read: operations + finance (maker and checker).
recall_failed_deliveryp_order uuid, p_failed uuid, p_component text, p_correlation textintegerdefiner#479 A (owner 11/11 decisions 2-4). Internal, the caller holds the order reward lock. The PENDING system ADJUST DEBIT slip (origin / reason FAILED_DELIVERY_RECALL, no maker, finance decides) of the Available reward share a failed cycle (p_failed) or the stop (null) takes back: floor((ISSUE - close / shortage cuts) x lost value / order value) less what the failed series took, never above what is still Available; one per (order, cycle | stop, component); the link that received the points. Returns the slips written (0 or 1).
recall_ratep_order uuidTABLE(rate_vnd numeric, policy_version text)definerPPI-P7-05. Rate snapshot of a system return-recall slip: the APPROVED POINT_RATE in force now, else the order's frozen rate. Internal (no grant).
recall_returnp_order uuid, p_cycle_no integer, p_correlation_id correlation_refintegerdefinerPPI-P5-08 (E-09a..c) + PPI-P7-05. The PENDING ADJUST DEBIT slips of one return (whole Group Buy order or one Recurring cycle), written by the system (no maker, no evidence): Available order / pay-now / spin / Affiliate points x returned value / order value, rounded down; finance decides them. PPI-P3-14: the slip's link is the wallet link that received the points (live or ended), never a newer link.
recipientsp_ids uuid[]TABLE(account_id uuid, full_name text, phone_masked text)definerPPI-P7-05. Name (profiles.full_name) and staff-masked phone (customer.mask_phone) of point-slip / rank-debit accounts, for the ADJ-01 readers only (empty otherwise). Never the whole phone.
refusep_code text, p_reason text, p_detail textvoid
request_discrepanciesp_id uuidTABLE(id uuid, run_id uuid, run_date date, discrepancy_type text, status text, compensates boolean, created_at timestamptz, resolved_at timestamp with time zone)definerPPI-P8-01. Reconciliation items that name one point command (point_request_id) or that it compensated (adjustment_request_id, compensates = true), newest first, for the ADJ-01 readers only. No evidence, no notes.
request_rowsp_account uuid, p_operations text[], p_statuses text[], p_from timestamp with time zone, p_to timestamp with time zone, p_ids uuid[], p_original uuid, p_limit integer, p_offset integerTABLE(id uuid, request_id text, operation text, status text, account_id uuid, role text, points integer, adjust_direction text, target_bucket text, reason_code text, business_date date, source_event_id text, source_kind text, source_component text, related_order_id uuid, related_transaction_id uuid, adjustment_id uuid, spin_result_id uuid, original_request_id uuid, result_code text, result_available integer, provider_ref text, provider_recorded_at timestamptz, requested_at timestamp with time zone, check_count integer, next_check_at timestamp with time zone, escalated_at timestamp with time zone, attempts integer, reconciliation_status text, open_discrepancies integer, created_at timestamp with time zone, updated_at timestamp with time zone, total bigint)definerPPI-P8-01. Point commands PIDEAL sent to PiPoint (point operations only), filtered and paged newest first (<= 100), for the ADJ-01 readers only (empty otherwise). Never provider_body, payload_hash, the link or the PiPoint uid.
reversal_conflictp_redeem uuid, p_points integer, p_exclude uuidtext

schema cms ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
actor_canp_action textbooleanP4-17. Acting principal may read/manage/publish CMS content (matrix MK-01/MK-02) right now.
actor_has_rolep_roles text[]boolean
article_image_mimes—text[]
articles_visible_atp_at timestamp with time zoneTABLE(id uuid, slug text, locale text, version_id uuid, version integer, title text, excerpt text, body_html text, cover_media_id uuid, cover_path text, category_id uuid, category_slug text, category_name text, keywords text[], seo_title text, seo_description text, publish_at timestamptz)definer
banner_image_mimes—text[]
banners_visible_atp_app text, p_placement text, p_at timestamp with time zoneTABLE(id uuid, version_id uuid, version integer, title text, alt_text text, image_media_id uuid, image_path text, target_kind text, target_campaign_id uuid, target_product_id uuid, target_article_id uuid, target_url text, sort_order integer, starts_at timestamptz, ends_at timestamp with time zone)definer
body_has_contentp_body jsonbboolean
body_types_allowed—text[]
is_slugp_value textboolean
keyword_usagep_keyword uuidbigintdefiner
keyword_usage_countp_keyword uuidbigintdefiner
lock_category_tree—void
manager_roles—text[]P4-17 mirror of matrix MK-01 cms.manage (DEFINED).
media_attachablep_media uuid, p_mimes text[]booleandefinerP4-17. True when the media is READY, undeleted, public CMS_MEDIA of an allowed MIME type.
pages_visible_atp_at timestamp with time zoneTABLE(id uuid, slug text, locale text, version_id uuid, version integer, title text, publish_at timestamptz)definer
public_articlep_slug textTABLE(id uuid, slug text, locale text, version_id uuid, version integer, title text, excerpt text, body_html text, cover_media_id uuid, cover_path text, category_id uuid, category_slug text, category_name text, keywords text[], seo_title text, seo_description text, publish_at timestamptz)definerP4-17. One published, in-schedule article by slug with sanitized body_html. For P4-18; matrix A-04.
public_article_docp_slug text, p_locale textTABLE(id uuid, slug text, locale text, version integer, title text, excerpt text, cover_media_id uuid, category_slug text, category_name text, keywords text[], seo_title text, seo_description text, seo_canonical_url text, seo_share_media_id uuid, seo_indexable boolean, publish_at timestamptz, body_json jsonb)definerP4-18 + FU-CMS. One published, in-schedule article (published version only) with its sanitized body_json and SEO.
public_article_listp_locale text, p_limit integer, p_offset integerTABLE(id uuid, slug text, locale text, title text, excerpt text, cover_media_id uuid, category_slug text, category_name text, publish_at timestamptz)definer
public_article_totalp_locale textbigintdefiner
public_articlesp_limit integer, p_offset integerTABLE(id uuid, slug text, title text, excerpt text, cover_media_id uuid, cover_path text, category_slug text, category_name text, publish_at timestamptz, total bigint)definerP4-17. Published, in-schedule articles (list, no body). For P4-18 publicContent; matrix A-04.
public_banner_feedp_placement textTABLE(id uuid, title text, alt_text text, image_media_id uuid, target_kind text, target_campaign_id uuid, target_article_slug text, target_page_slug text, target_screen text, target_ok boolean, sort_order integer)definerP4-18 + FU-CMS. Published in-window banners of the request app with target availability (article, page, screen, campaign).
public_bannersp_app text, p_placement textTABLE(id uuid, version_id uuid, version integer, title text, alt_text text, image_media_id uuid, image_path text, target_kind text, target_campaign_id uuid, target_product_id uuid, target_article_id uuid, target_url text, sort_order integer, starts_at timestamptz, ends_at timestamp with time zone)definerP4-17. Published banners of one app/placement inside [starts_at, ends_at) now. For P4-18; matrix A-04.
public_mediap_ids uuid[]TABLE(id uuid, storage_path text)definerP4-18. Public READY CMS image media only; returns the object path inside the public bucket.
public_page_docp_slug text, p_locale textTABLE(id uuid, slug text, locale text, version integer, title text, seo_title text, seo_description text, seo_canonical_url text, seo_share_media_id uuid, seo_indexable boolean, publish_at timestamptz, body_json jsonb)definerFU-CMS. One published, in-schedule content page (published version only) with its stored sanitized body_json.
public_reader—booleanP4-18. A-04 mirror: true for a request in a known app (scope PUBLIC).
publisher_roles—text[]P4-17 mirror of matrix MK-02 cms.publish (PROPOSED, GAP-02).

schema finance_policy ​

P3-07. Versioned Finance policy (G-FIN): kinds, versions, maker/checker approval, fail-closed evaluators.

HàmTham sốTrả vềMô tả
actor_canp_action textbooleanP3-07. Acting principal may read/write/submit/approve Finance policy versions (matrix FPL-01..04) right now.
actor_has_rolep_roles text[]boolean
applicable_versionp_kind text, p_at timestamp with time zoneSETOF finance_policy_versions
approvep_version_id uuid, p_expected_version integer, p_correlation_id correlation_refSETOF finance_policy_versionsdefinerP3-07. Checker records an owner decision: SUBMITTED -> APPROVED (immutable). Never the author, editor or maker.
author_roles—text[]P3-07 mirror of matrix FPL-02 finance_policy.write: GAP-71, empty.
body_problemp_kind text, p_body jsonbtextP3-07. NULL when the body is a well-formed rule set of the kind (shape only, no value), else a problem code.
body_rolesp_body jsonbtext[]
checker_roles—text[]P3-07 mirror of matrix FPL-04 finance_policy.approve: GAP-71, empty.
decidep_kind text, p_at timestamp with time zone, p_pinned uuid, p_input jsonbjsonb
evaluate_funds_voucherp_fund_code text, p_voucher_kind text, p_at timestamp with time zone, p_pinned_version_id uuidjsonbdefiner
evaluate_reconciliation_tolerancep_provider_vnd bigint, p_local_vnd bigint, p_at timestamp with time zone, p_pinned_version_id uuidjsonbdefiner
evaluate_refund_thresholdp_amount_vnd bigint, p_at timestamp with time zone, p_pinned_version_id uuidjsonbdefiner
guard_body_roles—trigger
guard_version_update—trigger
is_vndp jsonbboolean
keys_arep jsonb, p_keys text[]boolean
kinds_fixed—trigger
maker_roles—text[]P3-07 mirror of matrix FPL-03 finance_policy.submit: GAP-71, empty.
no_delete—trigger
overlaps_approvedp_kind text, p_from timestamp with time zone, p_to timestamp with time zone, p_self uuidboolean
payload_hashv finance_policy_versionsbytea
reader_roles—text[]P3-07 mirror of matrix FPL-01 finance_policy.read: GAP-71, empty.
refusep_code text, p_reason text, p_detail textvoid
role_list_okp jsonbboolean
save_draftp_version_id uuid, p_expected_version integer, p_kind text, p_status text, p_body jsonb, p_effective_from timestamp with time zone, p_effective_to timestamp with time zone, p_source_ref text, p_correlation_id correlation_refSETOF finance_policy_versionsdefiner
submitp_version_id uuid, p_expected_version integer, p_correlation_id correlation_refSETOF finance_policy_versionsdefiner

schema notification ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
announce_deal_tierp_campaign_product uuid, p_source_event_id uuid, p_source_event_type text, p_correlation_id textintegerdefinerG1S-P1-11 TB-07 / G2S-P1-11 TB-21. pi_worker only: the reached tier of an OPEN Deal (Mua chung) or basket product (Mua định kỳ), thật + ảo against the current price tiers; when >= 2, one TIER_REACHED per PLACED order priced below it and not told about it (or a higher tier) for that product. Count written.
bonus_credit_failed_emit—triggerdefinerPPI-P5-10 (DEC-PPI-OWN02-TB13-FAIL). AFTER UPDATE of job_runs: the pipoint.reward.dispatch run of a Mua chung pay-now / Mua định kỳ prepay bonus ISSUE ended without a credit (DEAD, or SUCCEEDED with SKIPPED / NO_PIPOINT_ACCOUNT) -> one order.bonus_credit_failed (TB-13 / TB-28 without points). Internal.
capture_unapplied_emit—triggerdefinerG1S-P1-11 TB-06 / G2S-P1-11 TB-20. At commit: a SUCCEEDED capture of a Mua chung or Mua định kỳ deposit left (partly) unapplied and unrefunded appends order.payment_unapplied (aggregate ORDER, id <orderId>:unapplied:<txn>, v1).
feed_since—timestamptzU19-P2-16. When the in-app feed started (the migration time): events recorded before it are never announced.
g1s_feed_since—timestamptzG1S-P1-11. When the G1S notices started (the migration time): G1S event types recorded before it are never announced.
g1s_pay_now_awaits_creditp_order_id uuidbooleandefinerPPI-P5-04 (W-05) / PPI-P5-10. True while the pay-now bonus (Mua chung) or prepay bonus (Mua định kỳ) of an order is still to be credited at PiPoint: its ISSUE is SENT / UNKNOWN / BLOCKED WALLET_LOOKUP_UNAVAILABLE with no DEAD dispatch run, or not bound yet and the reward policy gives > 0 points. TB-13 / TB-28 then wait for that credit's ACCEPTED or its failure for good. Internal.
g1s_pay_now_pointsp_order_id uuidintegerdefinerG1S-P1-11b TB-13 rewardPoints: the pay-now bonus of a Group order as the reward dispatch fixes it (bound ISSUE points, else the RewardAmountPolicy over campaign_reward_facts + point_rate_at); null without a bonus or a credit. Internal.
g2s_basket_keysp_order_id uuidjsonbG2S-P1-11 (G2S-P0-02, DR-07). Internal: { campaignType RECURRING, orderCode, basketName = Tên chiến dịch, cycles = Số kỳ cam kết } of a Mua định kỳ order, {} for any other order. Every Mua định kỳ notice merges it.
g2s_feed_since—timestamptzG2S-P1-11. When the Mua định kỳ notices started (the migration time): a RECURRING order's event recorded before it is never announced by record_g1s_event.
g2s_prepay_bonus_pointsp_order_id uuid, p_credited booleanintegerG2S-P1-11 TB-24 / TB-28 prepayBonusPoints. Internal: the Thưởng khi trả trước toàn bộ of a RECURRING order as the reward dispatch fixes it (campaign-reward.ts ONLINE_REMAINING over campaign_reward_facts + point_rate_at). credited: the bound ISSUE points, else the policy when the remainder was paid online and the buyer is linked (TB-28); offer: the policy before payment (TB-24). null without a bonus or when an input is undecided.
is_recipientp_account uuidboolean
kinds—text[]
pay479_feed_since—timestamptz#479 D. When the four order notices started (the migration time): their events recorded before it are never announced.
record_cycle_forfeitp_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id textTABLE(outcome text, reason text, in_app_event_id uuid)definerFU-AC-TRIAGE L7 A-OPS-03 HC02. pi_worker only: one in-app notice (kind CYCLE_FORFEITED, no text) for the owner of an order whose cycle was forfeited by an approved review, verified against order_cycles and recurring_forfeit_effects; idempotent per event.
record_g1s_eventp_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id textTABLE(outcome text, reason text, in_app_event_id uuid)definerG1S-P1-11 / G2S-P1-11 BR-APP-18. pi_worker only: the Mua chung notices TB-01, 03-07, 12-14 and the Mua định kỳ notices TB-15, 17-21, 27-29 from their events, facts read back from the database (a RECURRING payload adds campaignType, orderCode, basketName, cycles); a non-deposit order.cancelled goes to record_order_outcome. Idempotent per event and per order (deposit pending: per attempt). PPI-P5-04 (W-05) / PPI-P5-10 (DEC-PPI-OWN02-TB13-FAIL): TB-13 / TB-28 of a payment with a bonus credit coming wait for that credit: its ACCEPTED (point_request.available) writes the notice with rewardPoints / prepayBonusPoints = the credited points, its failure for good (order.bonus_credit_failed) writes it with null; without a credit coming it is written at the payment (null, or the credited points when already ACCEPTED). One notice per order.
record_order_outcomep_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id textTABLE(outcome text, reason text, in_app_event_id uuid)definerP4-19, U19-P2-16, G2S-P1-11, PAF-P1-13. pi_worker only: one in-app notification for the owner of an order closed by its campaign (Group outcome, or Recurring close values), with what remains to pay on a lock; a Mua định kỳ one adds the basket keys and TB-24 prepayBonusPoints / TB-25 metCount, productCount / TB-26 refundVnd, refundPoints; a Mua chung one adds productName and TB-10 finalPriceVnd, milestoneNo, prepayBonusPoints (Thưởng thanh toán online) / TB-11 refundVnd, refundPoints. Idempotent per source event and per (order, kind).
record_pay479_eventp_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id textTABLE(outcome text, reason text, in_app_event_id uuid)definer#479 D (Q6). pi_worker only: ORDER_CANCELLED_OUT_OF_STOCK (order.shortage_cancelled), ORDER_DEPOSIT_FORFEITED (order.failed; the deposit kept, net of the cọc dư it funds), COD_COLLECTED (payment.cod_collected), RETURN_RECORDED (refund_case.return_recorded), EXCESS_DEPOSIT_CLAIM_OPENED (refund_case.excess_claim_opened) to the order owner, every fact read back, Mua định kỳ payloads with the basket keys, the claim notice with the claim id (refundCaseId); idempotent per event and per fact; events before pay479_feed_since() are skipped.
record_refund_completedp_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id textTABLE(outcome text, reason text, in_app_event_id uuid)definerU19-P2-16 DH-US-17. pi_worker only: one in-app notice (REFUND_COMPLETED / REFUND_PARTIALLY_COMPLETED, masked snapshot) for the owner of the order whose refund Operations confirmed, verified against the settling transfer; one per case, idempotent per event.
record_refund_info_updatep_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id textTABLE(outcome text, reason text, in_app_event_id uuid)definerU19-P2-15 DH-US-16 AC02; G2I-P1-03 O6a. pi_worker only: one in-app notice (REFUND_INFO_UPDATE_REQUESTED: reason code, the note only when marked for the customer) for the owner of the order whose refund request Operations sent back, verified against refund_info_update_requests; idempotent per event. #479: refundCaseId in the payload when the case is a cọc dư claim (origin EXCESS_DEPOSIT).
reminder_spins_lefts spin_sessions, p_now timestamp with time zoneintegerVQM-P1-08 TB-08 / TB-22. Spins the session can still use at p_now, else null: NOT_ENTERED, or ACTIVE with no window condition (BR-VQ-08, DEC-VQM-18) unless entered and past the presence threshold T at p_now (already over, DEC-VQM-07).
scan_remindersp_now timestamp with time zone, p_correlation_id textTABLE(kind text, written integer)definerG1S-P1-12 / G2S-P1-11 BR-APP-18. pi_worker only: the timed notices due at now, Mua chung and Mua định kỳ (TB-02 / TB-16 120 min before the deposit is due, TB-08 / TB-22 and TB-09 / TB-23 24 h before the close) and the TB-07 / TB-21 tier scan for the virtual growth; one notice per (order, kind); returns the count written per kind.
skip_reasons—text[]
staff_eventp_id uuidTABLE(id uuid, state text, skip_reason text, kind text, recipient_account_id uuid, recipient_app text, recipient_phone_masked text, order_id uuid, campaign_id uuid, in_app_event_id uuid, source_event_id uuid, source_event_type text, correlation_id text, recorded_at timestamptz, created_at timestamp with time zone, read_at timestamp with time zone)definerFU-455 (NTF-03). One ledger entry with its in-app row (masked recipient); no row for an unknown id.
staff_eventsp_app text, p_kind text, p_state text, p_from timestamp with time zone, p_to timestamp with time zone, p_limit integer, p_offset integerTABLE(id uuid, state text, skip_reason text, kind text, recipient_account_id uuid, recipient_app text, recipient_phone_masked text, order_id uuid, campaign_id uuid, in_app_event_id uuid, source_event_id uuid, source_event_type text, correlation_id text, recorded_at timestamptz, created_at timestamp with time zone, read_at timestamp with time zone, total bigint)definerFU-455 (NTF-03). One page of the in-app ledger for notification_event.read holders (42501 otherwise) with the unpaged total; recipient phone masked in the database; filters app, kind, state, recorded_at window [from, to).
staff_require—voiddefiner
write_order_noticep_kind text, p_order uuid, p_payload jsonb, p_source_event_id uuid, p_source_event_type text, p_correlation_id textuuiddefinerG1S-P1-11. pi_worker only: one in-app notice of kind to the owner of the order (campaign from the order); null when the same notice exists (source event + kind, or the per-order key of the G1S kinds). Reused by P1-12.

schema pipoint_reward ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
affiliate_rate_atp_role text, p_at timestamp with time zoneTABLE(rate_bp integer, policy_version text)definerL9 / DEC-AFFILIATE-REWARD. The APPROVED REWARD_POLICY in force at the instant: Affiliate rate (basis points) and its snapshot ref; no row = none approved (reward stays BLOCKED); pi_worker only.
base_factsp_order_id uuidTABLE(deposit_cash_vnd bigint, points_redeemed_vnd bigint, remaining_paid_vnd bigint, remaining_due_vnd bigint)definerFU-715. Cash facts of an order for the reward base (settled DEPOSIT, ONLINE REMAINING, close remaining); pi_worker only.
campaign_reward_factsp_order_id uuidTABLE(campaign_type text, reward_unit text, order_value_vnd bigint, order_reward_value integer, online_bonus_value integer, final_total_vnd bigint, remaining_paid_online_vnd bigint, partial_final_vnd bigint)definerU19-P2-36, U28-P1-08, G2S-P1-06 (DR-11). pi_worker only: the campaign facts of an order reward (Word CD B006.R09): unit, V0, milestone/package value, pay-now/prepay-all bonus, final price, cash paid online for the remainder, and the kept final value of a partially closed Mua định kỳ order (CD-US-12 AC17 = FuncSpec BR-MD-09, the % base).
close_cancel_planp_order uuid, p_correlation textintegerdefinerU19-R31, U28-P1-08, CV3-P4-09. Queues the recalculation of the Pending package reward of a Mua định kỳ order locked by a Thành công một phần close (PERCENT_ORDER, every kept order, DEC-CV3-31 / BR-DK-09; DH-US-11 AC03) on the kept final value: the row cancels V0 - Σ cycle close value; nothing when that is >= V0; idempotent; pi_worker only.
close_remaining_vndp_order_id uuidTABLE(remaining_vnd bigint)definerFU-715. Remaining amount of the order's LOCK close outcome (0 = nothing to pay online); no row when none; pi_worker only.
dispatch_job_name—textP3-20. Job name of the reward dispatch run (slot reward:<point_reward_actions.id>).
failed_delivery_cutp_order uuid, p_failed uuid, p_correlation textintegerdefiner#479 A (owner 11/11 decisions 2-4). Internal. The reward share a failed cycle (p_failed) or the stop of the order (null) takes off the buyer's order reward and the order's Affiliate reward: a partial CANCEL_ISSUE row while Pending, a FAILED_DELIVERY_RECALL slip once Available; idempotent per (order, cycle | stop, component).
failed_delivery_lost_valuep_order uuid, p_failed uuidTABLE(lost_vnd bigint, order_vnd bigint)definer#479 A (owner 11/11 decisions 2-4). Internal. Value (actual price, order_cycle_close_values) of the cycles of a Mua định kỳ order that lose their reward share as of one failed-delivery settlement (p_failed: the cycles settled up to it) or of the stop (p_failed null: every settled one); for a stop, or a settlement after it, also every cycle the stop cancelled and every cycle the customer skipped (owner 11/11: only the delivered keep theirs). With the value of every cycle.
is_reward_requestp_operation text, p_source text, p_order uuidboolean
log_release—triggerdefinerU19-P2-20. One PIPOINT pipoint.release activity row when a RELEASE is accepted (pending -> available).
log_returned_cancel—triggerdefinerU19-P2-18. One PIPOINT pipoint.cancel activity row when the CANCEL_ISSUE of a returned order is accepted.
order_reward_pointsp_order uuidjsonbdefinerU28-FU-API-B. Reward points of an order: pending (accepted ISSUE not to Available, not released nor cancelled) and available (ISSUE to Available, or released). Read by shortage.order_cancel_gate and the COD collect preview.
order_subjectp_order_id uuidTABLE(owner_account_id uuid, campaign_type text, state text)definerP3-20. Reward recipient (order owner), campaign type and state of one order; pi_worker only.
partial_cancel_bindp_id uuid, p_date datejsonbdefiner
partial_cancel_planp_case uuid, p_correlation textintegerdefinerFU-SHORTAGE2. One QUEUED partial-cancel row per PARTIAL_UNITS row of a recorded case (idempotent); pi_worker only.
partial_cancel_settlep_id uuid, p_status text, p_provider_ref text, p_reason textvoiddefiner
partial_statep_order uuid, p_component textTABLE(points bigint, in_flight boolean, queued boolean)definerFU-SHORTAGE2, G2S-P4-05-fix, #479 A. Points the partial cancels of one reward of an order (component, default the order reward; AFFILIATE_ORDER since #479 A) took off the Pending residual, whether one is in flight, and whether one is still queued (a RELEASE waits for it).
point_rate_atp_at timestamp with time zoneTABLE(rate_vnd numeric, policy_version text)definerP3-20. AS-03 rate snapshot: APPROVED POINT_RATE in force at the instant; no row when none; pi_worker only.
record_first_paid_cyclep_order_id uuid, p_cycle_no integer, p_paid_at timestamp with time zone, p_source text, p_event_id uuidTABLE(is_first boolean, cycle_no integer, paid_at timestamptz)definerFU-AC-TRIAGE L7. pi_worker only: records the first actually paid cycle of a Recurring order once (first writer wins) and answers the stored fact; no row for a Group Buy order.
recurring_partial_final_vndp_order uuidbigintU28-P1-08, CV3-P4-09 (BR-DK-09, DEC-CV3-31). Mua định kỳ order locked by a Thành công một phần close: Σ cycle close value (kept products at the final price, every cycle), whether or not the order lost a product; null otherwise (Mua chung, before the close, Thành công toàn phần). Internal (SECURITY DEFINER callers).
released_pointsp_order uuid, p_component textbigintdefiner#479 A. Internal. Available points of the order-level reward (ISSUE without a cycle) of one component: the accepted RELEASE, or an ISSUE accepted straight to Available; 0 while Pending.
returned_unitp_order_id uuid, p_cycle_no integerbooleandefinerU19-P2-18. True when the order (cycle null) or its cycle is in order status RETURNED; pi_worker only.
tier_multiplier_atp_account_id uuid, p_audience text, p_activity text, p_at timestamp with time zoneTABLE(multiplier numeric, tier_version_id uuid, benefit_policy_ref text)definerU28-P3-10 DEC-U28-07. Tier factor of a reward at its ISSUE instant: USER after the customer set activation = the common coefficient of the Tier held then (NULL = no row); SALE / before activation = legacy per-activity multiplier.

schema rbac ​

P1-06. RBAC catalog/grant functions. Not exposed to the Data API; pi_api may execute the api functions only.

HàmTham sốTrả vềMô tả
actor_can_read—booleandefiner
actor_grants—TABLE(permission text, scope text)definerP1-06. Live (permission, scope) grants of the acting principal in the claimed app; empty without an actor, a role, an ACTIVE membership or an ACTIVE account. Source of the evaluator principal grants.
actor_holdsp_permission textbooleandefiner
actor_holds_rolep_role_id uuidbooleandefiner
approve_changep_id uuid, p_expected_version integerSETOF role_change_requestsdefiner
bootstrap_first_adminsp_super_admin_phone text, p_admin_phone text, p_operator text, p_reason text, p_super_admin_name text, p_admin_name text, p_super_admin_hash text, p_admin_hash textTABLE(run_id uuid, outcome text, super_admin_account_id uuid, admin_account_id uuid)definerP1-06, PPI-P2-06. Operator-only, audited, idempotent creation of the first super_admin + admin pair on STAFF accounts (created from name + temporary password hash when missing); refuses when a usable super_admin exists. Runbook: docs/technical/14-rbac-operator-bootstrap.md.
break_glass_super_adminp_phone text, p_mfa_reset boolean, p_password_hash text, p_operator text, p_reason textTABLE(run_id uuid, account_id uuid, factors_removed integer, sessions_revoked integer, credential_expires_at timestamptz)definerPPI-P2-06 E-06 break-glass: operator-only MFA reset and/or temporary credential (72 h) of ONE usable super_admin STAFF account; logs rbac_bootstrap_runs (BREAK_GLASS) + audit rbac.break_glass. Runbook: docs/technical/14-rbac-operator-bootstrap.md.
capture_role_version—triggerdefiner
change_payload_hashp_kind text, p_app text, p_role_id uuid, p_role_version integer, p_account_id uuid, p_assignment_id uuid, p_grants jsonbtext
change_requestsp_status text, p_id uuidTABLE(id uuid, kind text, app text, role_id uuid, role_code text, role_version integer, account_id uuid, assignment_id uuid, grants jsonb, payload_hash text, current_hash text, reason text, status text, requested_by uuid, requested_at timestamptz, approved_by uuid, approved_at timestamp with time zone, applied_version integer, version integer)definer
create_rolep_code text, p_name text, p_description textTABLE(id uuid, version integer)definer
grants_atp_role_id uuid, p_version integerjsonbdefiner
guard_change_request—trigger
guard_grant—trigger
is_last_super_adminp_assignment_id uuidbooleandefiner
normalize_grantsp_app text, p_grants jsonbjsonbdefiner
permission_catalog—TABLE(id uuid, code text, description text, risk_level text, allowed_scopes text[], deprecated_at timestamptz)definer
request_changep_kind text, p_role_id uuid, p_account_id uuid, p_grants jsonb, p_expected_version integer, p_reason text, p_correlation_id textSETOF role_change_requestsdefiner
requirep_permission textvoiddefiner
role_catalog—TABLE(id uuid, app text, code text, name text, description text, is_system boolean, version integer, holder_count integer, grants jsonb, updated_at timestamptz)definer
role_historyp_role_id uuidTABLE(version integer, name text, description text, changed_by uuid, change_request_id uuid, recorded_at timestamptz, grants jsonb)definer
update_rolep_role_id uuid, p_expected_version integer, p_name text, p_description textTABLE(version integer)definer

schema report_export ​

P4-21. Report export jobs (definer functions); see schema-ownership s5bu.

HàmTham sốTrả vềMô tả
actor_canp_what textbooleandefinerP4-21. RLS gate: the live report.export / report_money.export grant.
assert_filtersp_code text, f jsonb, p_from timestamp with time zone, p_to timestamp with time zonevoid
auditj report_export_jobs, p_action text, p_result text, p_reason text, p_metadata jsonbvoid
claimp_job uuid, p_attempt integer, p_run uuidTABLE(o_outcome text)definerP4-21. QUEUED -> PROCESSING for the enqueued attempt.
completep_job uuid, p_attempt integer, p_run uuid, p_file_id uuid, p_file_name text, p_size integer, p_sha256 text, p_row_count integer, p_cutoff timestamp with time zone, p_source_status text, p_sources jsonb, p_policies jsonbTABLE(o_outcome text, o_expires_at timestamptz)definerP4-21. DONE (file recorded, expiry from the job ttl) or NO_DATA, plus the audit row, one transaction.
download_refp_id uuidTABLE(o_outcome text, o_id uuid, o_report_code text, o_file_name text, o_size_bytes integer, o_sha256 text, o_bucket text, o_path text, o_expires_at timestamptz, o_row_count integer, o_data_cutoff timestamp with time zone)definerP4-21. Own DONE file reference after re-deciding the permission.
enqueue—triggerdefiner
failp_job uuid, p_attempt integer, p_run uuid, p_code textTABLE(o_outcome text)definerP4-21. PROCESSING -> FAILED with a stable code, audited.
filters_okp jsonbboolean
guard_transition—trigger
kindp_code texttext
my_access—TABLE(can_read boolean, can_read_money boolean, can_export boolean, can_export_money boolean)definer
permitp_code textbooleandefinerP4-21. Live read + export grant of the acting principal for a report, else 42501.
purge_expired—TABLE(o_path text)definerP4-21. Expired DONE files -> EXPIRED; paths returned for removal.
refusep_code text, p_reason text, p_detail textvoid
requestp_code text, p_filters jsonb, p_from timestamp with time zone, p_to timestamp with time zone, p_money boolean, p_correlation correlation_refTABLE(o_outcome text, o_id uuid)definerP4-21. Queues an export job (one active per requester and filter set); POLICY_UNDECIDED without a file lifetime.
retryp_id uuid, p_expected_version integerTABLE(o_id uuid, o_version integer)definerP4-21. FAILED job of the caller back to QUEUED (same snapshot parameters).
snapshotp_job uuid, p_max_rows integerjsonbdefinerP4-21. The P4-20 report of a PROCESSING job read as its requester in one snapshot: rows, sources, open decisions.

schema sale_profile ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
actor_is_reviewer—booleanFU-718. Acting principal may read and decide PROFILE_CHANGE requests now.
actor_is_sale—booleanFU-718. Matrix U-07 mirror for the Sale profile functions.
casp_account uuid, p_expected integer, p_create booleanvoid
changep_id uuidSETOF sale_profile.change_rowdefinerFU-718. One request for a reviewer (SPC-01), masked, never the reviewer's own.
change_viewc sale_profile_changes, p_total bigintsale_profile.change_row
changes_guard—trigger
decide_changep_id uuid, p_expected integer, p_decision text, p_reason textTABLE(change_id uuid, sale_account_id uuid, new_state text, new_version integer)definerFU-718. Reviewer decision (SPC-02): approval applies the new values atomically; reject keeps the reason.
mask_tailp_value texttextFU-718. ****1234 mask of ID number / bank account (GAP-06 open).
mine—TABLE(full_name text, phone_masked text, phone_verified boolean, avatar_media_id uuid, contact_email text, contact_address text, id_number_masked text, bank_account_masked text, version integer, updated_at timestamptz, approved_at timestamp with time zone)definerFU-718 + FU-SALEPROF2. The acting Sale's own profile; ID number and bank account masked; approved_at = the APP_SALE membership approval (null when none).
my_changesp_limit integer, p_offset integerSETOF sale_profile.change_rowdefinerFU-718. The acting Sale's own PROFILE_CHANGE requests, masked.
queuep_state text, p_limit integer, p_offset integerSETOF sale_profile.change_rowdefinerFU-718. Reviewer queue (SPC-01), masked, never the reviewer's own.
reviewer_roles—text[]FU-718. Mirror of matrix SPC-01/SPC-02 (WEB_ADMIN admin, super_admin; PROPOSED).
save_contactp_expected integer, p_email text, p_address textintegerdefinerFU-718. DIRECT edit of contact email/address (SPEC-06).
set_avatarp_expected integer, p_media uuidintegerdefinerFU-718. DIRECT edit of the avatar: own READY AVATAR media (GAP-873).
submit_changep_expected integer, p_full_name text, p_id_number text, p_bank_account textuuiddefinerFU-718. PROFILE_CHANGE request for full name / ID number / bank account; never overwrites the effective value.

schema pipoint_report ​

P3-23. Monthly PiPoint report: role lists, selection helpers, definer build/correct/settle commands.

HàmTham sốTrả vềMô tả
accepted_atp_request uuid, p_requested_at timestamp with time zonetimestamptz
actor_canp_action textboolean
build_draftp_month date, p_cutoff timestamp with time zone, p_correlation correlation_refTABLE(o_id uuid, o_version integer, o_outcome text)definerP3-23 + PPI-P5-03. One DRAFT version of a VN month at each request's own rate snapshot, ISSUE lines per target bucket (E-08); SETTLED months are LOCKED.
month_ofp_operation text, p_business_date date, p_recorded_at timestamp with time zone, p_requested_at timestamp with time zonedate
open_discrepanciesp_month dateinteger
open_monthsp_cutoff timestamp with time zoneTABLE(o_month date)definer
rate_basis—text
reader_roles—text[]P3-23 mirror of matrix PRP-01 point_report.read.
refusep_code text, p_reason text, p_detail textvoid
selectionp_month date, p_cutoff timestamp with time zoneTABLE(id uuid, request_id text, operation text, adjust_direction text, target_bucket text, points integer, rate_snapshot_vnd numeric)
selection_hashp_month date, p_cutoff timestamp with time zone, p_open integerbytea
settlep_id uuid, p_expected_version integer, p_note text, p_correlation correlation_refSETOF point_report_versionsdefinerP3-23 / PPI-P7-06. Offline SETTLED marker on an ended month DRAFT; open discrepancy lines do not block, their count stays on the version (DEC-PPI-OWN03-SETTLE-OPEN-LINES). Marker only: no transfer, no ledger.
settler_roles—text[]P3-23 mirror of matrix PRP-02 point_report.settle.
sweep_correctionsp_now timestamp with time zone, p_correlation correlation_refTABLE(o_request_id uuid, o_report_id uuid, o_month date)definerP3-23 + FU-DEF151. Late ACCEPTED requests (RELEASE included, count-only RELEASE_COUNT) of a SETTLED month become CORRECTION rows in the current month; settled rows untouched.

schema shortage ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
actor_in_rolesp_roles text[]boolean
cancel_refund_figuresp_order uuid, p_cancel integer[]jsonbdefinerU19-R23 + U28-P2-11 (ASSUME-01), PAF-P1-21 (DEC-PAF-22), PAF-P1-23 (DEC-PAF-26, DEC-PAF-27), PAF-P1-25 (DEC-PAF-29, finding A). Cash and Pi-Point a whole-order refund pays: the cycles given minus the skipped and FORFEITED ones (kept: never refunded; a FORFEITED one whose forfeit case was REJECTED is refunded); with kept cycles, per refunded cycle the deposit share of the current allocation (payment.recurring_cycle_alloc), the points share of the close and the collected part (payment.recurring_order_money), each capped by its own captures; else every refundable capture and REDEEM; the cash never above the refundable captures minus the cọc dư cases funded from them (payment.overpayment_cases_captured = casesVnd).
case_types—text[]
cumulative_sharesp_unit_price bigint, p_deposit_bp integer, p_deposit bigint, p_points integer, p_qty integer, p_cancelled integerTABLE(cash_vnd bigint, points integer)FU-575. Cumulative deposit (kept part rounded up) and points (rounded down) refunded after N cancelled units.
cumulative_value_sharesp_deposit_bp integer, p_deposit bigint, p_points integer, p_v0 bigint, p_cancelled_value bigintTABLE(cash_vnd bigint, points integer)FU-SHORTAGE2. Cumulative deposit refund (kept part rounded up) and points (rounded down) once p_cancelled_value of p_v0 is cancelled.
impactp_campaign_product uuid, p_cycle_no integer, p_orders uuid[], p_limit integerjsonbdefinerP2-19. Readers/managers: per-Order owed/delivered/undelivered units, refund snapshot and eligibility.
manager_roles—text[]P2-19 / FU-OPSGRANTS. WEB_ADMIN roles that record shortage cases: operations, admin (matrix SHR-02, ALL; DEC-OPS-ADMIN-ALL).
ops_cancel_orderp_order uuid, p_note text, p_source textjsonbdefinerU19-P2-17, G2I-P2-02, U28-P2-11. Ops cancel for "Hết hàng / thiếu hàng" of the WHOLE order (Word B048.R02): order Đã hủy (OUT_OF_STOCK, Chờ hoàn tiền when paid), ĐK cycles not in a shipment Đã hủy, unpaid OPEN obligations cancelled, one WHOLE_ORDER shortage row whose units are the quantities of each cancelled cycle.
order_cancel_gatep_order uuid, p_apply booleanjsonbdefinerU13-P2-05d + U19-P2-17 + U19-R23 + U28-P2-07 + U28-P2-11 + U28-FU-API-B + PAF-P1-23. Facts for the Ops shortage cancel (Word axes): MC packing past Chờ đóng gói, ĐK cycles in a shipment / to cancel (a skipped or forfeited one included: cancelled, not refunded) / refunded / kept, payment pending, refund figures = shortage.cancel_refund_figures (the ĐK hold / refund obligations, minus the cọc dư cases funded from the captures: casesVnd), statusVersion (AC09 CAS), kept cycles' collected money and the Available reward (kept); apply = true locks NOWAIT. Writes nothing.
order_unitsp_order uuid, p_campaign_product uuid, p_cycle_no integerjsonbdefinerFU-SHORTAGE2, G2I-P2-02. The shortage facts of one order line: ordered units = order_lines.units, the units left per undelivered cycle from the quantity of that cycle (ordering.cycle_lines), the order value rule and shares.
partial_policy_version—textFU-575. Versioned label of DEC-CP-SHORTAGE (2026-10-05): a partial quantity shortage is cancelled and refunded partially.
reader_roles—text[]P2-19 / FU-OPSGRANTS. WEB_ADMIN roles that read shortage cases: operations, admin (matrix SHR-01, ALL; DEC-OPS-ADMIN-ALL).
record_casep_case_type text, p_campaign_product uuid, p_cycle_no integer, p_reason text, p_evidence uuid[], p_items jsonb, p_source_event_id textjsonbdefinerP2-19 + FU-575 + U19-R34. Managers only: records one Group Buy shortage case (the whole Order LOCKED -> CANCELLED, AS-02; the quantity branch is refused by the API, RM-DH-08). A Recurring product is refused: shortage.ops_cancel_order.

schema pipoint_ekyc ​

PPI-P4-01. PiPoint eKYC snapshot sync (status pull by the pipoint.account_event job; exchange enqueue).

HàmTham sốTrả vềMô tả
customer_uidp_account uuidTABLE(customer boolean, uid text)definerPPI-P9-01 customerIdentity. customer = a CUSTOMER account; uid = its live pipoint link (null: not linked). ekyc.read, else PT403.
redeem_snapshotp_uid textTABLE(ekyc_status text, via text)definerPPI-P7-06. The stored eKYC (status, via) of a PiPoint uid with a live link, read right before a REDEEM debit instead of calling ekycPlatform-review status. No row = no snapshot = not verified. D-06: nothing identifying.
request_review_syncp_uid text, p_correlation_id correlation_reftextdefinerPPI-P9-01. After decideEkycRequest: one synthetic account.ekyc_request_changed receipt pideal:review:<uuid> + pipoint.account_event slot (the PPI-P4-01 status pull), unless a PENDING run of the uid exists. ekyc.review, else PT403. NO_LINK | PENDING | ENQUEUED.
request_syncp_account_id uuid, p_uid text, p_claim_ekyc text, p_claim_via text, p_correlation_id correlation_reftextdefinerPPI-P4-01, PPI-P4-05 (04 s3). Exchange / refresh: the ekyc / ekyc_via claims differ from the held state (snapshot, default none) -> one synthetic account.ekyc_changed receipt + pipoint.account_event slot, unless a live run of the uid is waiting. NO_LINK | IN_SYNC | PENDING | ENQUEUED.
review_peoplep_uids text[]TABLE(uid text, account_id uuid, own boolean)definerPPI-P9-01. For each PiPoint uid (<= 100): the CUSTOMER accounts with a live pipoint link and own = the caller is that person (identity.same_person). ekyc.read or ekyc.review, else PT403. Nothing identifying is returned.
reviewer_uid—textdefinerPPI-P9-01. PiPoint uid of the caller's person (live pipoint link of an account with the same phone), sent as reviewer.pipointUid so PiPoint also refuses a self review; null when none. ekyc.read or ekyc.review, else PT403.
sync_ackp_slot_key textjsonbdefinerPPI-P4-01, PPI-P4-05. status answered account-not-found: the receipt is processed; an account of the uid without a snapshot gets none (marks null).
sync_applyp_slot_key text, p_pulled_at timestamp with time zone, p_ekyc_status text, p_via text, p_method text, p_verified_at timestamp with time zone, p_ekyc_changed_at timestamp with time zone, p_request_status text, p_request_platform text, p_reject_code text, p_request_changed_at timestamp with time zonejsonbdefinerPPI-P4-01. Upserts the snapshot of every account with a live pipoint link of the receipt uid from one status pull, per watermark (ekyc.changedAt / request.changedAt; stale parts ignored); marks the covered eKYC receipts processed. first_verified lists the accounts that became verified for the first time (referral milestone).
sync_beginp_slot_key textjsonbdefinerPPI-P4-01. eKYC receipt of the slot: NO_RECEIPT | ALREADY_PROCESSED | NO_ACCOUNT (no live pipoint link: acked) | OPEN + uid (pull status once).
sync_failp_slot_key text, p_code textjsonbdefinerPPI-P4-05. status refused for good (4xx except 429, malformed answer): the receipt is processed with failure_code; nothing else changes. NO_RECEIPT | ALREADY_PROCESSED | CLOSED.

schema identity ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
app_memberships_deleted_account_guard—triggerdefiner
end_pipoint_wallet_link—triggerdefinerPPI-P3-12 (DEC-PPI-OWN02-UNLINK-WALLET). Trigger: the update that releases a pipoint identity subject (support unlink, account deletion) ends the account's live wallet link with the same reason. Internal.
identity_links_subject_guard—trigger
person_accountsp_account uuiduuid[]definerPPI-P1-03 (B-02), PPI-P7-02 (DEC-PPI-OWN03-DROP-STAFF-LINK). The accounts of one person: the account and the other-kind account with the same phone. Internal to definer functions (no grant).
pipoint_support_unlinkp_account uuid, p_uid text, p_operator text, p_reason text, p_correlation_id correlation_refjsonbPPI-P7-04 (DEC-PPI-OWN03-UNLINK-OPERATOR). Operator only (scripts/operator/pipoint-unlink.sql): ends the live PiPoint link of a CUSTOMER account (account and uid must agree) with SUPPORT_UNLINK, releases the uid, ends the wallet link, revokes the APP_USER sessions (PIPOINT_UNLINKED), audits pipoint.operator_unlink.
same_personp_a uuid, p_b uuidbooleandefinerPPI-P1-03 (B-02), PPI-P7-02 (DEC-PPI-OWN03-DROP-STAFF-LINK). True when two accounts are one person: the same account or the same phone (CUSTOMER and STAFF). Every conflict-of-interest check in a SQL function body compares with it.
staff_accountsp_membership_status text, p_awaiting_role boolean, p_limit integer, p_offset integerTABLE(account_id uuid, masked_phone text, full_name text, account_status text, membership_status text, membership_version integer, roles text[], pending_role_code text, pending_role_change_id uuid, pending_role_change_version integer, pending_role_requested_by uuid, credential_status text, temporary_expires_at timestamptz, provisioned_by uuid, created_at timestamp with time zone, total integer)definerPPI-P2-04 / PPI-P7-01 staffAccounts (AD-05 staff.read, MASKED): STAFF accounts with their WEB_ADMIN membership, credential state (NONE | TEMPORARY | TEMPORARY_EXPIRED | ACTIVE, DB clock), pending ASSIGN_ROLE request (id, version, maker) and creator; phone masked. p_awaiting_role: only people waiting for their first role.
staff_provisionp_account uuid, p_phone text, p_full_name text, p_role_code text, p_note text, p_correlation_id textTABLE(account_id uuid, membership_version integer, role_change_request_id uuid)definerPPI-P2-04 / PPI-P7-01 createStaffAccount (03 s3.1, D-14, DEC-PPI-OWN03-STAFF-ADD-FLOW): a NEW STAFF account (phone unverified, provisioned_by, link (staff,pideal,id), profile name), WEB_ADMIN membership ACTIVE (approved_by = creator), no credential (the auth function issues it), ASSIGN_ROLE request (maker = actor). Needs staff.create; super_admin only by a super_admin; staff_phone_taken when a STAFF account has the phone.
staff_rejectp_account uuid, p_expected_version integer, p_reason textTABLE(membership_version integer, rejected_requests integer, sessions_revoked integer)definerPPI-P7-01 rejectMembership (AD-11 membership.reject, DEC-PPI-OWN03-STAFF-ADD-FLOW): every PENDING role request of a STAFF person without a role -> REJECTED (rejected_by = actor, never its maker), WEB_ADMIN membership PENDING / ACTIVE -> REJECTED with the reason, live WEB_ADMIN sessions revoked (ACCESS_DENIED), open sign-in challenges locked.

schema sale_team ​

P1-13. Sale team source (current/historical team, actor team ids) and the team transfer function.

HàmTham sốTrả vềMô tả
actor_holds_teamp_permission textbooleandefinerP1-13. The acting WEB_ADMIN principal holds a live grant of the permission at scope TEAM.
actor_in_teamp_team uuidbooleandefinerP1-13. TEAM-scope RLS predicate: team in actor_team_ids().
actor_team_ids—uuid[]definerP1-13. Principal.teamIds: managed ACTIVE teams (WEB_ADMIN) or own current team (APP_SALE); empty otherwise.
assignment_versionp_sale uuidintegerdefiner
current_teamp_sale uuiduuiddefinerP1-13. Current team of a Sale (CURRENT basis); see team_at.
may_resolvep_sale uuidbooleandefiner
team_atp_sale uuid, p_at timestamp with time zoneuuiddefinerP1-13. Team of a Sale at an instant (HISTORICAL_SNAPSHOT); null without a team or for an actor who may not resolve it.
team_at_uncheckedp_sale uuid, p_at timestamp with time zoneuuid
transferp_sale uuid, p_to_team uuid, p_expected_version integer, p_reason text, p_correlation_id textTABLE(history_id uuid, from_team uuid, to_team uuid, version integer, effective_from timestamptz, changed boolean)definerP1-13 A-TEAM-02 transfer (matrix M-04 TEAM): source and destination managed by the actor, destination ACTIVE, expected assignment version, immediate effect, append-only history; same team = no-op.

schema sale_application_access ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
applicant_document_room—booleanFU-PENDINGUPLOAD. MD-09 plus the cap of 10 not-deleted SUPPORTING_DOCUMENT objects per applicant (GAP-2030).
is_applicant_app—booleanP1-12. Matrix S-06/U-10 mirror: claimed APP_SALE membership (any status) or ACTIVE APP_USER with role user.
is_pending_applicant—booleanFU-PENDINGUPLOAD. Matrix MD-09..MD-11 mirror: claimed APP_SALE, membership PENDING, account ACTIVE (DEC-S-APPLICATION-UPLOAD).
may_review—booleanP1-12. Matrix AD-07/AD-08 mirror: WEB_ADMIN with an effective reviewer role (admin, super_admin since FU-SALEREVIEWER).
may_submit—booleanP1-12. Matrix S-05/U-09 mirror plus ACTIVE account and, from APP_SALE, a PENDING membership.
reviewer_roles—text[]FU-SALEREVIEWER. WEB_ADMIN roles that review Sale applications: mirror of matrix AD-07/AD-08 (admin, super_admin; DEC-S-APPLICATION-REVIEWER). The MFA step-up is enforced by the API guard.
source_for_app—text

schema sale_qualification ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
evaluatep_account uuid, p_at timestamp with time zoneTABLE(status text, rank_points bigint, fingerprint text, evidence jsonb)P4-10. Three-valued AND over the become-Sale Missions in force; rank and Tier are evidence only (GAP-238); no Mission in force or an unmet paused Mission is POLICY_UNDECIDED (GAP-237).
livep_applications uuid[]TABLE(application_id uuid, status text, rank_points bigint, fingerprint text, evidence jsonb)definerP4-10. Live qualification of PENDING User-to-Sale applications the caller may see (own, or reviewer); others omitted.
may_readp_application sale_applicationsboolean
mine—TABLE(status text, rank_points bigint, fingerprint text, evidence jsonb)definerP4-10. The acting User's own live qualification (UA-26 AC01); 42501 for anyone else.
mission_statep_account uuid, p_definition uuid, p_at timestamp with time zoneTABLE(status text, assignment_count integer, states jsonb, gaps jsonb)
recordp_application uuid, p_kind text, p_decision textTABLE(id uuid, status text, rank_points bigint, fingerprint text, evidence jsonb, evaluated_at timestamptz)definerP4-10. Stores the database-derived qualification at submission or decision (applicant / deciding reviewer only); an APPROVE snapshot is QUALIFIED or the insert fails.
recordsp_applications uuid[]TABLE(id uuid, application_id uuid, application_version integer, kind text, decision text, status text, fingerprint text, active_rank bigint, evaluated_at timestamptz)definer

schema sale_view ​

P4-14. Scoped, masked read model of Sale customers, orders and performance.

HàmTham sốTrả vềMô tả
basep_scope text, p_perm text, p_basis text, p_team uuid, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_state textTABLE(assignment_id uuid, order_id uuid, buyer_account_id uuid, campaign_id uuid, sale_account_id uuid, attributed_team_id uuid, current_team_id uuid, order_created_at timestamptz, deposit_at timestamp with time zone, order_state text, v0_vnd bigint, committed_cycle_count integer, qualification text, base_vnd bigint, base_basis text)definerP4-14. Scoped ATTRIBUTED Sale assignments with both teams and the shared P4-13 qualification (private).
customersp_scope text, p_basis text, p_team uuid, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_state text, p_limit integer, p_offset integerTABLE(id uuid, sale_account_id uuid, attributed_team_id uuid, current_team_id uuid, order_count bigint, qualified_order_count bigint, campaign_count bigint, first_order_at timestamptz, last_order_at timestamp with time zone, masked_phone text, total bigint)definerP4-14. Scoped attributed customers (buyer x Sale x attribution team), masked, with order counts.
ordersp_scope text, p_basis text, p_team uuid, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_state text, p_limit integer, p_offset integer, p_campaign_type textTABLE(assignment_id uuid, order_id uuid, campaign_id uuid, sale_account_id uuid, attributed_team_id uuid, current_team_id uuid, order_created_at timestamptz, deposit_at timestamp with time zone, order_state text, v0_vnd bigint, committed_cycle_count integer, qualification text, base_vnd bigint, base_basis text, masked_phone text, total bigint, campaign_type text, product_name text, line_count integer)definerP4-14 + P5-S06. Scoped attributed Sale orders, newest first, buyer masked, both teams, shared P4-13 qualification, with the campaign type (filterable) and the first line's product name.
performancep_scope text, p_team uuid, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zoneTABLE(team_id uuid, attributed_customers bigint, attributed_orders bigint, qualified_orders bigint, qualified_base_vnd bigint, cancelled_qualified_orders bigint, cancelled_qualified_base_vnd bigint, fulfilled_qualified_orders bigint, referral_customers bigint, unique_customers bigint, gross_orders bigint, gross_value_vnd bigint)definerP4-14 + FU-636. Period totals per team key from the same row set as the lists (TEAM = attribution-time team, M-03), plus the GROSS order count and value by order creation time (DEC-S-GMV-BASIS).
performance_statusp_scope text, p_team uuid, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zoneTABLE(attribution_pending boolean, payment_pending boolean, qualification_undecided boolean, gross_total_orders bigint, gross_total_value_vnd bigint)definerP4-14 + FU-636. Incomplete-source flags (attribution not consumed, deposit not confirmed, base undecided) and the period gross total of the scope.
scope_okp_scope text, p_perm textbooleandefinerP4-14. OWN (APP_SALE owner), TEAM (live grant at TEAM) or ALL (staff_all_roles, empty: GAP-137).
staff_all_roles—text[]

schema mfa ​

P1-07. pi_api entry points for MFA step-up grants and the MFA reset case.

HàmTham sốTrả vềMô tả
live_grantp_session_id uuid, p_action textuuid
reset_approvep_id uuid, p_expected_version integer, p_correlation_id correlation_refSETOF mfa_reset_requestsdefiner
reset_getp_id uuidSETOF mfa_reset_requestsdefiner
reset_requestp_target uuid, p_reason text, p_ttl_seconds integer, p_correlation_id correlation_refSETOF mfa_reset_requestsdefiner
step_up_consumep_session_id uuid, p_action textbooleandefiner
step_up_validp_session_id uuid, p_action textbooleandefiner

schema affiliate_reward ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
backfill_candidates—TABLE(order_id uuid, deposit_at timestamptz)definerU19-P2-20. Deposited, undelivered, attributed orders without an Affiliate row (backfill of the deposit-time Pending); pi_worker only.
deliveriesp_shipment_id uuid, p_shipment_version integerTABLE(outcome text, order_id uuid, cycle_no integer, gross_vnd bigint, basis text, delivered_at timestamptz)definerF2 DEC-AFFILIATE-ROUND-TIMING. pi_worker only: the delivered (order, cycle) rows of one shipment version with the gross value of what was delivered (after cancelled units, delivery fee excluded, never reduced by a later refund); read from the fulfillment event, never a payload.
grant_for_deliveryp_order_id uuidTABLE(outcome text, recipient_account_id uuid, role text, assignment_id uuid, base_vnd bigint, base_basis text, campaign_type text, order_state text, cycle_count integer)definerF2. pi_worker only: Affiliate qualification of one order (shared P4-04 rules; the base is the delivered value, so POLICY_UNDECIDED qualifies) plus the committed cycle count.
grant_for_orderp_order_id uuidTABLE(outcome text, recipient_account_id uuid, role text, assignment_id uuid, base_vnd bigint, base_basis text, campaign_type text, order_state text)definerP4-13. pi_worker only: Affiliate qualification of one order (shared P4-04 rules) + recipient wallet role.
my_rewardsp_limit integer, p_offset integerTABLE(id uuid, order_id uuid, campaign_id uuid, campaign_type text, assignment_id uuid, state text, issue_status text, reason_code text, undecided_ref text, base_vnd bigint, base_basis text, points integer, created_at timestamptz, masked_phone text, total bigint, reward_vnd bigint, rate_bp integer, policy_version text, tier_multiplier numeric, vnd_per_point numeric)definerP4-13 / L9. pi_api only: the caller's own Affiliate reward entries with a derived state, a masked buyer and the stored amount evidence (rate, policy version, multiplier, VND-per-point); nothing is recomputed.

schema pipoint_events ​

PPI-P3-05. PiPoint account events (Pub/Sub push): receipt + job enqueue, and the account.deleted job steps.

HàmTham sốTrả vềMô tả
account_deleted_applyp_slot_key textjsonbdefinerPPI-P3-05 job step 2, PPI-P3-15 (DEC-PPI-OWN03-PIPOINT-DELETED-NEW-PERSON): live pipoint links of the uid dead (PIPOINT_ACCOUNT_DELETED), the CUSTOMER accounts of the uid closed (pipoint_events.close_deleted_uid_accounts: phone / email NULL, every session revoked, memberships LOCKED, deleted_at), audit pipoint.account_deleted, processed_at.
account_event_beginp_slot_key textjsonbdefinerPPI-P3-05 job step 1. NO_RECEIPT | ALREADY_PROCESSED | OPEN (+ tombstone NEW / EXISTS for account.deleted, written and committed before step 2).
close_deleted_uid_accountsp_uid text, p_correlation_id correlation_ref, OUT accounts uuid[], OUT memberships_closed integer, OUT sessions_revoked integer, OUT credentials_removed integer, OUT wallet_links_ended integerrecorddefinerPPI-P3-15 (DEC-PPI-OWN03-PIPOINT-DELETED-NEW-PERSON). Closes (privacy.close_account, PIPOINT_ACCOUNT_DELETED) every CUSTOMER account not yet deleted whose latest pipoint link is the dead link of the deleted uid; audit privacy.account_deleted per account. Internal (account_deleted_apply, backfill).
receivep_event_id text, p_type text, p_uid text, p_occurred_at timestamp with time zone, p_correlation_id correlation_reftextdefinerPPI-P3-05. Receipt of one PiPoint account event + its pipoint.account_event job slot, in one transaction. RECORDED, or DUPLICATE (eventId already received: nothing written).

schema auth ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
jwt—jsonb
role—text
uid—uuid

schema profile_access ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
actor_apps—text[]definerP1-10. App codes of the acting account (claimed app must be a membership); for SPEC-06 fail-closed gating.
address_provinces—TABLE(code text, name text)definerG2I-P3-04. Province / City catalogue for the U-12 address form (profile.manage actors only), by name.
may_manage—booleanP1-10. Matrix U-07 mirror for profile/address policies: own ACTIVE user/sale membership in the claimed app.

schema settings ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
get_intp_key text, p_default integerintegerdefinerU19-P1-03. Integer system parameter; p_default when the key is missing; raises 22023 on a non-integer value.
get_textp_key text, p_default texttextdefinerU19-P1-03. Text system parameter; p_default when the key is missing; raises 22023 on a non-string value.

schema pipoint_access ​

Chưa có COMMENT ON SCHEMA

HàmTham sốTrả vềMô tả
may_use_wallet—booleanP3-18. Matrix U-06/U-11 mirror: own ACTIVE user/sale membership in the claimed app.

Sinh từ ad83b0aea · 820 migration · PostgreSQL 17