Giao diện
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
| Schema | Hàm | SECURITY DEFINER | Có mô tả |
|---|---|---|---|
public | 239 | 133 | 55 |
payment | 209 | 155 | 123 |
campaign | 152 | 80 | 134 |
ordering | 127 | 94 | 113 |
tier | 79 | 33 | 37 |
fulfillment | 73 | 61 | 49 |
identity_flow | 54 | 43 | 23 |
spin | 49 | 30 | 41 |
sale_admin | 46 | 29 | 38 |
catalog | 39 | 9 | 29 |
customer | 39 | 19 | 34 |
mission | 37 | 22 | 18 |
privacy | 32 | 17 | 12 |
report | 30 | 17 | 11 |
attribution | 29 | 24 | 12 |
pipoint_adjust | 28 | 15 | 16 |
cms | 26 | 15 | 12 |
finance_policy | 26 | 6 | 7 |
notification | 26 | 16 | 22 |
pipoint_reward | 23 | 20 | 20 |
rbac | 22 | 19 | 3 |
report_export | 18 | 12 | 10 |
sale_profile | 15 | 8 | 12 |
pipoint_report | 14 | 4 | 5 |
shortage | 13 | 6 | 11 |
pipoint_ekyc | 10 | 10 | 10 |
identity | 9 | 7 | 7 |
sale_team | 9 | 8 | 6 |
sale_application_access | 7 | 0 | 6 |
sale_qualification | 7 | 4 | 4 |
sale_view | 7 | 6 | 6 |
mfa | 6 | 5 | 0 |
affiliate_reward | 5 | 5 | 5 |
pipoint_events | 4 | 4 | 4 |
auth | 3 | 0 | 0 |
profile_access | 3 | 2 | 3 |
settings | 2 | 2 | 2 |
pipoint_access | 1 | 0 | 1 |
schema public
standard public schema
| Hàm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
accounts_identity_change_guard | — | trigger | ||
addresses_reject_deleted_update | — | trigger | ||
api_actor_admin_roles | — | text[] | definer | P1-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 | — | text | P1-09. Claimed app from app.app (transaction-local), NULL if unset/unknown. | |
api_actor_id | — | uuid | P1-09. Acting account from app.actor_id (transaction-local), NULL if unset/invalid. | |
api_guest_throttle_begin | p_key_hash bytea, p_total integer, p_quotes integer, p_max_total integer, p_max_quotes integer, p_window_seconds integer | jsonb | definer | #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_active | p_sid uuid, p_account_id uuid, p_app app_code | boolean | definer | AF-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[]) | definer | P1-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 | — | trigger | PPI-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_names | p_ids uuid[] | TABLE(account_id uuid, display_name text) | definer | CV3-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) | definer | CV3-P4-17 (DEC-CV3-33). Every action in audit_events with the category / severity of its newest row; audit.read only. |
audit_event_count | p_filter jsonb | bigint | definer | CV3-P4-17 (DEC-CV3-33). Number of audit_events matching the filter; audit.read only. |
audit_event_detail_insertable | p_audit_event_id uuid | boolean | definer | CV3-P4-02. True for an audit_events row of the acting principal flagged metadata.hasDetail. |
audit_event_detail_reader | — | boolean | definer | CV3-P4-02. True while the acting principal holds audit.read at ALL (Z-01). |
audit_event_filter_sql | p_filter jsonb | text | CV3-P4-17. WHERE text (format %L literals) of the audit list filter; owner-only helper of the audit reads. | |
audit_event_one | p_id uuid | TABLE(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) | definer | CV3-P4-17 (DEC-CV3-33). One audit_events row with before / after / metadata as JSON text, as stored; audit.read only. |
audit_event_page | p_filter jsonb, p_limit integer, p_offset integer | TABLE(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) | definer | CV3-P4-17 (DEC-CV3-33). One page of audit_events, newest first, as stored (masked at write); audit.read only. |
audit_event_read_require | — | void | definer | CV3-P4-17. Raises 42501 unless the definer owner is RLS-exempt and the acting principal holds audit.read (Z-01). |
campaign_children_guard | — | trigger | definer | |
campaign_outcomes_guard | — | trigger | definer | |
campaign_point_config_versions_guard | — | trigger | ||
campaign_policy_versions_guard | — | trigger | definer | |
campaign_state_events_guard | — | trigger | definer | U19-P1-01. Campaign history: no update; delete only by the cascade of its deleted campaign. |
campaigns_after_change | — | trigger | definer | One 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 | — | trigger | definer | U19-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 | — | trigger | definer | U19-P1-01. Hard delete only in DRAFT/PENDING_PUBLISH/UPCOMING and without orders (B006.R04, B198.R02). |
campaigns_enqueue_outcome | — | trigger | definer | |
campaigns_enqueue_recurring_close | — | trigger | definer | |
campaigns_guard | — | trigger | U19-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 | — | trigger | U19-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 | — | trigger | definer | U19-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 | — | trigger | definer | |
cancellation_decisions_guard_insert | — | trigger | definer | |
cashbook_entries_guard_insert | — | trigger | definer | |
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 | — | trigger | definer | |
catalog_attribute_values_highlight_limit | — | trigger | definer | |
catalog_attribute_values_options_required | — | trigger | definer | |
catalog_attribute_values_position | — | trigger | definer | |
catalog_attribute_values_shape | — | trigger | definer | |
catalog_attribute_values_validate | — | trigger | definer | |
catalog_attributes_rules | — | trigger | ||
catalog_brands_guard | — | trigger | ||
catalog_categories_tree_guard | — | trigger | U6-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 | — | trigger | definer | |
catalog_product_accessories_unit_guard | — | trigger | definer | |
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 | — | trigger | definer | |
catalog_products_combo_complete | — | trigger | ||
catalog_products_guard | — | trigger | ||
catalog_products_status_guard | — | trigger | ||
catalog_products_unit_guard | — | trigger | ||
cms_articles_close_uses | — | trigger | definer | |
cms_articles_guard | — | trigger | ||
cms_banners_guard | — | trigger | ||
cms_categories_tree_guard | — | trigger | ||
cms_keywords_delete_guard | — | trigger | definer | |
cms_keywords_state_guard | — | trigger | ||
cms_pages_guard | — | trigger | ||
cms_parent_has_version | — | trigger | ||
cms_publish_ready_guard | — | trigger | definer | |
cod_collections_guard_insert | — | trigger | definer | |
cod_collections_guard_update | — | trigger | definer | |
cod_remittances_guard_insert | — | trigger | definer | |
content_versions_insert_guard | — | trigger | definer | |
content_versions_record_uses | — | trigger | definer | |
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 | — | trigger | definer | |
deposit_checkouts_insert_guard | — | trigger | ||
deposit_checkouts_rearm_close | — | trigger | definer | PAF-P1-19 (DEC-PAF-18). A deposit checkout of an order of a CLOSING campaign ended: the close runs again. |
deposit_checkouts_tender_snapshot | — | trigger | definer | |
deposit_checkouts_transition_guard | — | trigger | ||
event_actor_snapshot | — | trigger | definer | |
fulfillment_events_guard_insert | — | trigger | definer | |
fulfillment_exceptions_guard_insert | — | trigger | definer | |
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_image | p_media uuid | boolean | definer | U6-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_bytes | p_purpose text | bigint | U6-P3-38. Largest object of a purpose in bytes (1 MB = 1 MiB; <= 20 MiB); null for an unknown purpose. | |
media_purpose_mimes | p_purpose text | text[] | 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_attached | p_media uuid, p_purpose text | boolean | definer | U6-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 | — | trigger | definer | |
mfa_reset_requests_guard | — | trigger | ||
mfa_step_up_grants_guard | — | trigger | ||
mission_assignments_completed_event | — | trigger | definer | |
mission_assignments_insert_guard | — | trigger | ||
mission_contributions_insert_guard | — | trigger | ||
mission_criteria_guard | — | trigger | ||
mission_versions_guard | — | trigger | ||
order_close_outcomes_guard | — | trigger | definer | P2-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 | — | trigger | definer | U19-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 | — | trigger | definer | |
order_cycles_guard | — | trigger | definer | |
order_lines_insert_guard | — | trigger | ||
order_periods_guard_mutation | — | trigger | G2S-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 | — | trigger | definer | |
order_quotes_basket_guard | — | trigger | definer | |
order_quotes_group_cutoff | — | trigger | definer | |
order_quotes_guard | — | trigger | definer | |
order_remaining_methods_guard | — | trigger | definer | |
order_return_cases_guard | — | trigger | definer | |
orders_after_change | — | trigger | definer | |
orders_commit_recurring | — | trigger | definer | |
orders_copy_lines | — | trigger | definer | |
orders_deposit_rounding_from_quote | — | trigger | definer | G1S-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 | — | trigger | definer | |
orders_guard_insert | — | trigger | definer | BEFORE 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 | — | trigger | definer | #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 | — | trigger | definer | P3-01. Records the DEPOSIT (and PI_POINT when points are used) obligation in the order insert transaction. |
orders_recurring_package | — | trigger | definer | U19-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 | — | trigger | definer | U19-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 | — | trigger | definer | |
payment_allocations_settle | — | trigger | definer | |
payment_events_guard_insert | — | trigger | definer | |
payment_hold_releases_guard | — | trigger | ||
payment_intents_guard_insert | — | trigger | definer | |
payment_intents_guard_update | — | trigger | definer | |
payment_intents_rearm_close | — | trigger | definer | PAF-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 | — | trigger | definer | PAF-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 | — | trigger | definer | |
payment_obligations_cod_end_case | — | trigger | definer | PAF-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 | — | trigger | definer | P3-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 | — | trigger | definer | |
payment_overpayment_cases_guard | — | trigger | definer | |
payment_overpayment_cases_open_claim | — | trigger | definer | #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 | — | trigger | definer | |
point_adjustments_insert_guard | — | trigger | ||
point_adjustments_reverse_fence | — | trigger | definer | FU-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 | — | trigger | definer | PPI-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 | — | trigger | definer | #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 | — | trigger | definer | |
point_requests_debited_event | — | trigger | definer | |
point_requests_insert_guard | — | trigger | definer | |
point_requests_recall_rank_debit | — | trigger | definer | PPI-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 | — | trigger | definer | FU-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 | — | trigger | definer | |
point_reward_actions_insert_guard | — | trigger | ||
point_reward_actions_transition_guard | — | trigger | ||
point_reward_partial_cancels_enqueue | — | trigger | definer | |
point_reward_partial_cancels_guard | — | trigger | ||
price_tiers_guard | — | trigger | definer | |
provider_transactions_guard_insert | — | trigger | definer | |
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 | — | trigger | definer | |
recurring_basket_lines_guard | — | trigger | definer | |
recurring_baskets_cycle_empty | — | trigger | definer | G2S-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 | — | trigger | definer | |
recurring_baskets_guard | — | trigger | definer | |
recurring_cycles_skip_cutoff_guard | — | trigger | definer | |
recurring_forfeit_effects_follow_payment | — | trigger | definer | PAF-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 | — | trigger | definer | PAF-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 | — | trigger | definer | |
recurring_skip_requests_guard | — | trigger | definer | P2-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 | — | trigger | definer | |
refund_branches_exec_enqueue | — | trigger | definer | |
refund_branches_guard_insert | — | trigger | definer | |
refund_branches_guard_update | — | trigger | definer | |
refund_branches_manual_fence | — | trigger | definer | |
refund_cases_check_legs | — | trigger | definer | |
refund_cases_exec_enqueue | — | trigger | definer | |
refund_cases_guard_insert | — | trigger | definer | |
refund_cases_guard_update | — | trigger | definer | |
refund_cases_record_history | — | trigger | definer | |
refund_cases_refund_ordered | — | trigger | definer | CV3-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 | — | trigger | definer | U19-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 | — | trigger | definer | |
shipment_order_links_skip_guard | — | trigger | definer | |
shipments_guard_update | — | trigger | ||
shipments_unresolved_handover_guard | — | trigger | definer | |
spin_draws_after_insert | — | trigger | definer | |
spin_draws_before_insert | — | trigger | definer | |
spin_draws_roll_guard | — | trigger | P4-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 | — | trigger | definer | |
spin_rule_versions_guard | — | trigger | definer | |
spin_sessions_guard | — | trigger | ||
staff_credentials_account_guard | — | trigger | ||
stock_shortage_case_orders_guard | — | trigger | definer | |
system_settings_touch | — | trigger | ||
tier_assignments_guard | — | trigger | ||
tier_children_guard | — | trigger | ||
tier_definitions_no_delete | — | trigger | ||
tier_reevaluations_guard | — | trigger | definer | |
tier_set_items_guard | — | trigger | definer | |
tier_set_versions_check | — | trigger | definer | |
tier_set_versions_guard | — | trigger | definer | |
tier_set_versions_rules | — | trigger | definer | |
tier_set_versions_serialize | — | trigger | ||
tier_versions_guard | — | trigger |
schema payment
P3-01. Payment helpers (obligations, intents, transactions, allocations).
| Hàm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_in_roles | p_roles text[] | boolean | ||
actor_is_reader | — | boolean | P3-01. Matrix F-01 mirror (PROPOSED): ACTIVE WEB_ADMIN membership with a payment.reader_roles() role. | |
assert_next_version | p_table text, p_old integer, p_new integer, p_old_source text, p_new_source text | void | ||
attempt_core | p_system boolean, p_request_id text, p_to text, p_session_ref text, p_result_code text, p_source text, p_source_id text | payment.intent_change | definer | P3-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) | definer | U19-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_lease | p_request_id text, p_purpose text, p_holder uuid, p_seconds integer | boolean | definer | #479 T4. pi_api, the buyer of the order: payment.lease_core. |
buyer_deposit_due_at | p_obligation_id uuid | timestamptz | definer | #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_claims | p_order uuid | TABLE(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_observe | 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 text | payment.intent_change | definer | |
buyer_open_checkout | p_obligation_id uuid, p_expected_version integer, p_source_id text, p_cash_request_id text, p_redeem_date date, p_correlation_id text | payment.checkout_state | definer | P3-04 / #377 / G1S-P1-05. The 7-argument write-ahead with method MOMO_WALLET. |
buyer_open_checkout | p_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 text | payment.checkout_state | definer | P3-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_intent | p_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 text | payment.intent_change | definer | P3-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_intent | p_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 text | payment.intent_change | definer | P3-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_attempt | p_request_id text, p_to text, p_session_ref text, p_result_code text, p_source text, p_source_id text | payment.intent_change | definer | |
buyer_record_session | p_request_id text, p_pay_url text, p_deeplink text, p_qr_data text, p_expires_at timestamp with time zone | boolean | definer | #479 T5. pi_api, the buyer of the order: records the session of its PENDING intent (payment.session_core). |
buyer_refund_account | p_order uuid | TABLE(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_rejections | p_order uuid | TABLE(refund_case_id uuid, reason_code text, customer_note text, requested_at timestamptz, superseded boolean) | definer | G2I-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_transfers | p_order uuid | TABLE(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_lease | p_request_id text, p_purpose text, p_holder uuid | boolean | definer | #479 T4. pi_api, the buyer of the order: payment.lease_release_core. |
buyer_remaining_method | p_order uuid | TABLE(method text, version integer) | definer | U19-P2-21. Order.paymentMethod (pi_api): method and choice version of the caller's own order; nothing otherwise. |
buyer_remaining_switch | p_order uuid | jsonb | definer | U28-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_method | p_order_id uuid, p_method text, p_expected_version integer, p_source_id text | jsonb | definer | U19-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_touch | p_system boolean, p_obligation_id uuid | boolean | ||
cancel_decide | p_order uuid, p_source_type text, p_source_id text | jsonb | definer | |
cancel_decision_json | p_id uuid | jsonb | definer | |
cancel_evaluate | p_cause text, p_campaign_type text, p_timing text | jsonb | ||
cancel_policy_version | — | text | ||
cashbook_manual_guard | p cashbook_entries | cashbook_entries | definer | |
change_of | p_outcome text, p_intent uuid, p_prior_version integer, p_prior_status text, p_order_prior_version integer, p_order_prior_state text | payment.intent_change | ||
checkout_settle_manual_compensation | p_id uuid | payment.checkout_state | definer | #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_of | p_outcome text, p_id uuid | payment.checkout_state | ||
close_covered_paid | — | trigger | definer | U19-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_evidence | p_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 text | jsonb | definer | |
cod_change | p_cod uuid, p_kind text | jsonb | definer | |
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_ok | p_media uuid | boolean | definer | |
cod_lock_for_command | p_cod uuid, p_expected_version integer | cod_collections | definer | |
cod_reconciliation_items_guard | — | trigger | ||
cod_reconciliation_local | p_end timestamp with time zone | TABLE(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) | definer | P3-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_collection | p_carrier_code text, p_carrier_ref text, p_event_id text, p_amount bigint, p_collected_at timestamp with time zone, p_payload_hash text | jsonb | definer | |
cod_record_remittance | p_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 text | jsonb | definer | |
cod_record_shipment_collection | p_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 text | jsonb | definer | U19-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_collection | p_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 text | jsonb | definer | |
cod_remittance_gaps_guard | — | trigger | ||
cod_remitter_roles | — | text[] | P3-06. Matrix COD-02 cod.remit mirror (PROPOSED, GAP-77): finance. | |
cod_settle | p_cod uuid, p_source text, p_source_id text | void | definer | P3-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_shipment | p_shipment uuid, p_source_id text | jsonb | definer | |
cod_transition_allowed | p_from text, p_to text | boolean | P3-06. COD machine: DUE -> ASSIGNED -> DELIVERED -> COLLECTED -> REMITTED (collected is never remitted). | |
cycle_failed_delivery | p_order_cycle uuid | boolean | definer | #479 A. Internal: the cycle was settled by Operations as a failed delivery (any outcome). |
cycle_forfeit_dropped | p_order_cycle uuid | boolean | definer | PAF-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_rejected | p_order_cycle uuid | boolean | definer | PAF-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_locked | p_shipping text | boolean | U28-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_skipped | p_order uuid, p_cycle integer | boolean | definer | U19-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_at | p_created_at timestamp with time zone | timestamptz | definer | #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_paid | p_order uuid, p_cycle integer, p_milestone boolean, p_source text, p_actor uuid | void | definer | U19-P2-20. Outbox order.paid {orderId, cycleNo, isRewardMilestone, source}, aggregate <order>:paid, once. |
excess_refund_state | p_case uuid | text | definer | #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_campaign | p_campaign_id uuid | TABLE(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) | definer | U19-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_order | p_order uuid, p_reason text, p_source text, p_skip_locked boolean | jsonb | definer | U19-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_orders | p_limit integer, p_correlation_id text | TABLE(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) | definer | U19-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_order | p_order_id uuid, p_kind text, p_source_id text | void | #377 D1(a). No-op: a failed DEPOSIT attempt leaves the order DEPOSIT_PENDING (retry on the same order). | |
funds_guard | — | trigger | ||
funds_model_status | p_at timestamp with time zone | text | definer | |
group_pay_now_points | p_order uuid | integer | definer | PAF-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_switch | p_order uuid | jsonb | definer | PAF-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_open | p_intent uuid | boolean | definer | #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_allowed | p_from text, p_to text | boolean | P3-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_request | p_operation text, p_source text, p_order uuid | boolean | ||
is_refund_point_request | p_operation text, p_source text, p_order uuid | boolean | ||
lease_core | p_system boolean, p_request_id text, p_purpose text, p_holder uuid, p_seconds integer | boolean | definer | #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_core | p_system boolean, p_request_id text, p_purpose text, p_holder uuid | boolean | definer | #479 T4. Ends the lease of p_holder (false when it is not the holder any more). Internal: buyer_/system_release_intent_lease. |
mark_paid | p_order uuid, p_cycle integer, p_source text, p_actor uuid | boolean | definer | U19-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_ok | p_kind text, p_method text | boolean | ||
obligation_settled_paid | — | trigger | definer | U19-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_allowed | p_from text, p_to text | boolean | P3-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_core | p_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 text | payment.intent_change | definer | P3-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_remaining | p_order_id uuid, p_final_total_vnd bigint, p_close_outcome_id uuid, p_source_id text | TABLE(obligation_id uuid, remaining_vnd bigint, excess_vnd bigint, case_id uuid) | definer | P3-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_collected | p_order uuid | boolean | definer | U19-R13. True when the order ever collected cash (a SUCCEEDED capture or a COD collection). |
order_excess_refund_requests | p_scope text, p_orders uuid[] | jsonb | definer | #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_blocked | p_order uuid | boolean | definer | U19-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_requests | p_scope text, p_orders uuid[] | jsonb | definer | U19-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_outcomes | p_scope text, p_orders uuid[] | jsonb | definer | #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_for | p_created_at timestamp with time zone | TABLE(window_id uuid, window_minutes integer) | definer | |
order_window_guard | — | trigger | definer | |
overpayment_case_cycle_no | p_case uuid | integer | definer | #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_deposit | p_source text | boolean | PAF-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_captured | p_order uuid | bigint | definer | PAF-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_attention | p_unknown_before timestamp with time zone, p_kind text, p_limit integer, p_offset integer | jsonb | definer | #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_rows | p_ids uuid[], p_money boolean | 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) | definer | FU-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_points | p_order uuid | integer | definer | U28-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_ok | p_provider text, p_mode text | boolean | ||
reader_roles | — | text[] | ||
receipt_post | p_txn uuid, p_posted_by text | jsonb | definer | |
receipt_reader_roles | — | text[] | ||
receipt_sweep | p_limit integer, p_posted_by text | jsonb | definer | |
receipt_sync_intent | p_intent uuid, p_posted_by text | jsonb | definer | |
reconcile_reader_roles | — | text[] | ||
reconcile_resolver_roles | — | text[] | ||
reconciliation_items_guard | — | trigger | ||
reconciliation_local | p_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) | definer | P3-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_refund | p_order uuid, p_cycle_no integer, p_expected_version integer, p_reason text, p_returned_on date, p_note text, p_source_id text | jsonb | definer | #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_balance | p_basis text[], p_due bigint[], p_cod bigint[], p_kept boolean[], OUT cod_vnd bigint[], OUT excess_vnd bigint | record | PAF-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_case | p_order uuid, p_source text | bigint | definer | PAF-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_rounding | p_order uuid, OUT planned_vnd bigint, OUT collected_vnd bigint, OUT recognized_vnd bigint | record | definer | PAF-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_alloc | p_order uuid | TABLE(order_cycle_id uuid, cycle_no integer, cash_vnd bigint, due_vnd bigint, cod_vnd bigint, respread boolean) | definer | PAF-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_cod | p_order uuid | TABLE(order_cycle_id uuid, cycle_no integer, due_vnd bigint, cod_vnd bigint) | definer | U28-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_legs | p_order uuid | TABLE(refund_case_id uuid, amount_vnd bigint) | definer | U28-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_rebalance | p_review uuid, p_order uuid, p_order_cycle uuid | jsonb | definer | PAF-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_money | p_order uuid | jsonb | definer | U28-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_follow | p_order uuid, p_change_source text, p_source_id text, p_reason text | boolean | definer | PAF-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_followed | p_order uuid | boolean | definer | PAF-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_resync | p_order uuid, p_source_id text | boolean | definer | PAF-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 | — | trigger | definer | PAF-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_target | p_order uuid | bigint | definer | U28-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_basis | p_order uuid | TABLE(order_cycle_id uuid, cycle_no integer, value_vnd bigint, net_vnd bigint, basis text, cash_vnd bigint, due_vnd bigint, cod_vnd bigint) | definer | PAF-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_respread | p_skip uuid | jsonb | definer | PAF-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_online | p_order uuid, p_source text, p_reason text | integer | definer | #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_obligations | p_order uuid | boolean | definer | PAF-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_back | p_redeem uuid | boolean | definer | #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_record | p_branch uuid, p_expected_version integer, p_to text, p_refund_transaction uuid, p_reverse_request uuid, p_result_code text, p_source_id text | jsonb | definer | |
refund_case_json | p_case uuid | jsonb | definer | |
refund_cash_by_ops | p_case uuid | boolean | definer | U19-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_settled | p_case uuid | boolean | definer | U19-P2-15. True when the Operations confirm settled the cash of the case (its cash legs are not executed). |
refund_changes | p_case uuid, p_after_version integer | jsonb | definer | |
refund_evidence_ok | p_media uuid[], p_max integer | boolean | definer | |
refund_exec_job_name | — | text | ||
refund_exec_load | p_case uuid | jsonb | definer | |
refund_exec_record | p_branch uuid, p_provider_txn text, p_amount bigint, p_payload_hash bytea, p_source_id text, p_correlation_id text | uuid | definer | P3-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_name | p_value text | text | ||
refund_mask_tail | p_value text | text | ||
refund_name_key | p_value text | text | U19-P2-14. Accent-, case- and blank-insensitive key of a person name (holder name vs name on the CCCD). | |
refund_open_automatic | p_order uuid, p_origin text, p_request_key text, p_rule_versions text[], p_source_type text, p_source_id text | jsonb | definer | |
refund_open_case | p_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 text | jsonb | definer | P3-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_forfeit | p_review uuid, p_source_id text | jsonb | definer | FU-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_partial | p_case uuid, p_order uuid, p_request_key text, p_source_type text, p_source_id text | jsonb | definer | FU-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_excess | p_case uuid, p_order uuid, p_request_key text, p_source_type text, p_source_id text | jsonb | definer | FU-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_confirm | p_order uuid, p_case uuid, p_expected_version integer, p_code text, p_transferred_on date, p_note text, p_source_id text | jsonb | definer | U19-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_lock | p_order uuid, p_case uuid, p_expected_version integer | refund_cases | definer | |
refund_ops_request_update | p_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 boolean | jsonb | definer | U19-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_json | p refund_receiver_profiles | jsonb | ||
refund_reader_roles | — | text[] | ||
refund_record_view | p_cases uuid[] | jsonb | definer | |
refund_recover_roles | — | text[] | ||
refund_retry_branch | p_branch uuid, p_expected_version integer, p_reason text, p_evidence uuid[], p_source_id text | jsonb | definer | |
refund_submit_excess_request | p_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 text | jsonb | definer | #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_request | p_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 text | jsonb | definer | U19-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_json | t refund_transfer_records | jsonb | ||
refund_unresolved | p_order uuid | text | definer | |
refundable_cash | p_capture uuid, p_exclude_case uuid | bigint | definer | |
refundable_points | p_redeem uuid, p_exclude_case uuid | integer | definer | |
remaining_effective | p_obligation uuid | bigint | definer | FU-SHORTAGE2. The REMAINING amount in force: the latest recalculation, else the obligation amount. |
remaining_method_of | p_order uuid | text | definer | U19-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_recalculate | p_case uuid, p_order uuid, p_source_type text, p_source_id text | jsonb | definer | FU-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_switch | p_order uuid | jsonb | definer | U28-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_target | p_case uuid, p_order uuid | bigint | definer | FU-SHORTAGE2. DEC-CP-SHORTAGE-FOLLOWUP (2): remaining quantity x final unit price - deposit kept - points kept (may be <= 0). |
return_kept_amounts | p_order uuid, p_cycle_id uuid, OUT cash_vnd bigint, OUT points integer | record | definer | #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_milestone | p_order uuid, p_cycle integer | boolean | definer | U19-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_core | p_system boolean, p_request_id text, p_pay_url text, p_deeplink text, p_qr_data text, p_expires_at timestamp with time zone | boolean | definer | #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_allocations | p_order uuid | TABLE(allocation_id uuid, transaction_id uuid, obligation_id uuid, amount_vnd bigint, created_at timestamptz, provider_ref_tail text) | definer | FU-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_periods | p_order 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) | definer | FU-AC-TRIAGE L5 A-OD-02 AC02. Finance (F-01 payment.read) periods of one order with obligation / paid / remaining. |
staff_order_tenders | p_order uuid | TABLE(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) | definer | FU-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_deposit | p_id uuid | payment.checkout_state | definer | |
system_cancel_points | p_id uuid | payment.checkout_state | definer | |
system_checkout | p_id uuid | payment.checkout_state | definer | |
system_checkout_move | p_id uuid, p_expected_version integer, p_to text, p_reason text, p_reverse_date date | payment.checkout_state | definer | |
system_checkout_of_cash | p_cash_request_id text | uuid | definer | #479 T14. pi_worker: the deposit checkout whose cash leg is this provider request id (null when none). Read only. |
system_checkout_tender | p_id uuid | payment.checkout_tender | definer | |
system_claim_hold_release | p_request_id text, p_holder uuid, p_seconds integer | boolean | definer | #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_lease | p_request_id text, p_purpose text, p_holder uuid, p_seconds integer | boolean | definer | #479 T4. pi_worker: payment.lease_core. |
system_close_capped_intents | p_campaign_id uuid, p_wait_minutes integer, p_limit integer | TABLE(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_intents | p_limit integer | TABLE(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_release | p_now timestamp with time zone, p_stale_before timestamp with time zone, p_not_before timestamp with time zone, p_limit integer | TABLE(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_intent | p_request_id text | TABLE(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) | definer | P3-02. pi_worker read of one intent by provider request id (callback binding, recovery). |
system_note_hold_release | p_request_id text, p_result text, p_at timestamp with time zone, p_next_at timestamp with time zone, p_max_attempts integer | text | definer | #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_check | p_request_id text, p_checked_at timestamp with time zone, p_next_check_at timestamp with time zone | integer | definer | #479 T8. pi_worker: the sweep checked this intent (attempts + 1) and may check it again from p_next_check_at. |
system_observe | 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 text | payment.intent_change | definer | P3-02. pi_worker: verified callback / status lookup -> payment.observe_core (system). |
system_open_cash_intent | p_id uuid, p_provider text, p_mode text, p_payload_hash bytea, p_correlation_id text | payment.intent_change | definer | P3-04. pi_worker: the one cash intent of a checkout in its cash stage (request id fixed at insert). |
system_place_zero_deposit | p_id uuid | TABLE(outcome text, order_id uuid, obligation_id uuid, order_prior_version integer, order_version integer, order_state text, policy_version_id uuid) | definer | U19-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_attempt | p_request_id text, p_to text, p_session_ref text, p_result_code text, p_source text, p_source_id text | payment.intent_change | definer | |
system_record_session | p_request_id text, p_pay_url text, p_deeplink text, p_qr_data text, p_expires_at timestamp with time zone | boolean | definer | #479 T5. pi_worker: records the session of a PENDING intent (payment.session_core). |
system_recoverable_intents | p_now timestamp with time zone, p_stale_before timestamp with time zone, p_not_before timestamp with time zone, p_limit integer | TABLE(request_id text, intent_status text, status_changed_at timestamptz, check_attempts integer, last_checked_at timestamp with time zone) | definer | FU-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_lease | p_request_id text, p_purpose text, p_holder uuid | boolean | definer | #479 T4. pi_worker: payment.lease_release_core. |
system_reverse_points | p_id uuid | payment.checkout_state | definer | #377. pi_worker: the PI_POINT tender settled by this checkout -> REVERSED once its REVERSE_REDEEM is ACCEPTED. |
system_settle_points | p_id uuid | payment.checkout_state | definer | |
unapplied_captures | p_reason text, p_state text, p_limit integer, p_intent uuid | TABLE(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) | definer | FU-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_context | p_voucher_id uuid | TABLE(maker_id uuid, status text, payload_hash bytea) | definer | |
voucher_approve | p_voucher_id uuid, p_expected_version integer, p_payload_hash text, p_correlation_id correlation_ref | SETOF vouchers | definer | P3-09. Checker approves SUBMITTED -> APPROVED (immutable) and posts one cashbook entry. Never the maker/editor. |
voucher_cancel | p_voucher_id uuid, p_expected_version integer, p_correlation_id correlation_ref | SETOF vouchers | definer | |
voucher_checker_roles | — | text[] | ||
voucher_drafter_roles | — | text[] | ||
voucher_evidence_problem | p_ids uuid[] | text | ||
voucher_maker_roles | — | text[] | ||
voucher_payload_hash | p_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 uuid | bytea | ||
voucher_reader_roles | — | text[] | ||
voucher_refuse | p_code text, p_reason text, p_detail text | void | ||
voucher_reject | p_voucher_id uuid, p_expected_version integer, p_reason text, p_correlation_id correlation_ref | SETOF vouchers | definer | FU-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_draft | p_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_ref | SETOF vouchers | definer | |
voucher_submit | p_voucher_id uuid, p_expected_version integer, p_correlation_id correlation_ref | SETOF vouchers | definer | |
vouchers_fund_registered | — | trigger | definer | |
vouchers_guard_update | — | trigger | ||
vouchers_no_delete | — | trigger |
schema campaign
Chưa có COMMENT ON SCHEMA
| Hàm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
activate_cycle_skip | p_basket_id uuid, p_cycle_no integer, p_request_id text | void | definer | P2-09. Owner-only skip activation gate: policy_undecided DEC-CP-SKIP; records nothing (P2-18 owns recording). |
actor_can_manage | — | boolean | P2-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 | — | boolean | CV3-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 | — | boolean | CV3-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 | — | boolean | P2-09. Matrix U-01/U-02 mirror: APP_USER caller, ACTIVE account + membership, role user. | |
actual_price_split | p_total bigint, p_qty bigint | TABLE(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_obligations | p_campaign_id uuid, p_outcome_id uuid | TABLE(status text, locked_orders integer, cycles integer, obligations integer, excess_orders integer, cancelled_orders integer, orders jsonb) | definer | FU-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_prices | p_campaign_id uuid, p_outcome_id uuid | TABLE(status text, applied_orders integer, applied_rows integer) | definer | FU-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_open | p_campaign_id uuid, p_term integer | uuid | definer | P2-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_writable | p_campaign_id uuid | text | definer | U19-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_ready | p_campaign_id uuid | void | definer | U19-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_transition | p_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 zone | void | definer | U19-P1-01. Readiness/policy gates when a campaign leaves DRAFT (create) or CLOSING (outcome). |
basket_snapshot | p_basket_id uuid | jsonb | definer | P2-09. Owner-only basket preview data (lines, policy items; tiers + schedule while the campaign is ACTIVE). |
campaign_participant_count | p_campaign_id uuid, p_at timestamp with time zone, p_joining uuid | bigint | DEC-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 | — | trigger | definer | CV3-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_skip | p_skip uuid, p_expected_version integer, p_source_id text | jsonb | definer | P2-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_run | p_run_id uuid, p_version integer | boolean | definer | U19-P2-05. Settles one PENDING run as cancelled (PENDING -> LEASED -> SUCCEEDED, code cancelled). |
close_allocate | p_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_payment | p_campaign_id uuid | boolean | definer | PAF-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 | — | text | U19-P2-05. Job name of the close run (slot campaign:<id>:close:v<n>); was campaign.group_close (P2-07). | |
close_payment_wait | p_campaign_id uuid, p_wait_minutes integer | jsonb | definer | #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_registration | p_campaign_id uuid, p_run_id uuid | TABLE(outcome text, campaign_type text, version integer, policy_version_id uuid, opens_at timestamptz, closes_at timestamp with time zone) | definer | U19-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) | definer | U19-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_version | p_campaign_id uuid | uuid | ||
cycle_reminder_facts | p_order uuid, p_cycle_no integer | jsonb | definer | P2-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_count | p_campaign_product_id uuid, p_at timestamp with time zone, p_joining uuid | bigint | DEC-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_forfeit | p_review uuid, p_expected_version integer, p_decision text, p_payload_hash text, p_note text, p_correlation_id correlation_ref | jsonb | definer | FU-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_late | p_order_id uuid, p_closes_at timestamp with time zone | boolean | definer | PAF-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 | — | trigger | definer | G2S-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_status | p_state text, p_opens_at timestamp with time zone, p_closes_at timestamp with time zone | text | U19-P1-01. Admin status = state; internal CLOSING shows as OPEN (GAP-W-CD-10 resolved by B006.R03). | |
finalize_group_outcome | p_campaign_id uuid, p_expected_version integer, p_run_id uuid | TABLE(status text, campaign_type text, version integer, policy_version_id uuid, outcome_id uuid, detail jsonb, orders jsonb, expired jsonb) | definer | P2-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_overlap | p_type text, p_opens timestamp with time zone, p_closes timestamp with time zone, p_exclude uuid | TABLE(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_initials | p_seed text | text | ||
forfeit_approval_context | p_review uuid | TABLE(maker_id uuid, status text, payload_hash bytea) | definer | |
forfeit_cycle_event_ref | p_review uuid | TABLE(order_cycle_id uuid, cycle_version integer, policy_version_id uuid) | definer | FU-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_share | p_order uuid, p_cycle_no integer | TABLE(cash_vnd bigint, points integer) | definer | FU-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_json | r recurring_forfeit_reviews | jsonb | definer | |
forfeit_payload_hash | p_order uuid, p_cycle_no integer, p_reason text | bytea | ||
forfeit_pool_split | p_deposit bigint, p_points_value bigint, p_points integer, p_value bigint, p_cycles integer, p_cycle_no integer | TABLE(cash_vnd bigint, points integer) | ||
forfeit_refuse | p_constraint text, p_message text, p_detail text | void | ||
forfeit_roles | — | text[] | ||
form_product_facts | p_ids uuid[] | TABLE(id uuid, name text, product_type text) | definer | CV3-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_results | p_campaign_id uuid, p_policy_version_id uuid | jsonb | definer | U19-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_facts | p_campaign_id uuid | jsonb | definer | U19-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_lookup | p_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) | definer | CV3-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_delivery | p_campaign_id uuid | TABLE(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_product | p_product_id uuid | text | definer | CV3-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_product | p_product_id uuid | text | definer | P2-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_initials | p_name text | text | ||
next_code | p_at timestamp with time zone | text | definer | PAF-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_code | p_scope text, p_prefix text, p_width integer, p_at timestamp with time zone | text | definer | PAF-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 | — | text | U19-P2-05. Job name of the open run (slot campaign:<id>:open:v<n>). | |
order_forfeit_reviews | p_order uuid | SETOF jsonb | definer | |
order_skip_state | p_order uuid, p_lock boolean | jsonb | definer | P2-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 | — | text | P2-15. Job name of the Group close outcome run (slot campaign:<id>:v<CLOSING version>). | |
outcome_results_ok | p_outcome text, p_results jsonb | boolean | U19-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_reward | p_unit text, p_value integer, p_v0 bigint, p_rate numeric, p_order_id uuid | TABLE(cfg bigint, released bigint) | definer | U28-P1-09. Internal: configured % milestone reward of one order (floor per order) and its points already Available. |
overview_released_points | p_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_cfg | p_unit text, p_value integer, p_v0 bigint, p_rate numeric | bigint | CV3-P1-02. Internal: configured % milestone reward of one order, floor per order (U28-P1-09 rule). | |
package_snapshot | — | trigger | definer | U19-P1-05. Baskets/orders: skip_max and package_reward_value are copied from campaign_term_packages on package_no. |
participant_counts | p_campaign_id uuid, p_at timestamp with time zone | TABLE(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_brands | p_search text, p_limit integer, p_offset integer | jsonb | definer | CV3-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) | definer | CV3-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_facts | p_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_products | p_search text, p_product_type text, p_category_id uuid, p_brand_id uuid, p_added uuid[], p_limit integer, p_offset integer | jsonb | definer | CV3-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_actor | p_kind text | boolean | P2-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 | — | trigger | definer | FU-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) | definer | P2-10. Effective APPROVED cap + rate (refs <key>@v<n>:<id>) for activation; managers only; else no row. |
points_excess_pending | p_campaign_id uuid | TABLE(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) | definer | G1S-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_facts | p_campaign_id uuid | TABLE(product_id uuid, brand_name text, unit text, category_path text[], image jsonb) | definer | CV3-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_lines | p_campaign_ids uuid[] | TABLE(campaign_product_id uuid, campaign_id uuid, product_id uuid, moq_qty integer, sku text, name text, product_type text) | definer | P2-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 | — | trigger | definer | |
product_qtys | p_campaign_id uuid, p_at timestamp with time zone | TABLE(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_forfeit | p_order uuid, p_cycle_no integer, p_reason text, p_source_id text, p_correlation_id correlation_ref | jsonb | definer | FU-RECCLOSE. Operations maker proposes the forfeit review of one committed period of a LOCKED Recurring order. |
public_campaign_categories | p_campaign_id uuid | jsonb | definer | G2S-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_ids | p_search text, p_statuses text[], p_from date, p_to date, p_limit integer, p_offset integer | jsonb | definer | P2-08 / G1S-P1-09. {total, ids} of published Group Buy campaigns: the 7-argument form with no category. |
public_campaign_ids | p_search text, p_statuses text[], p_from date, p_to date, p_limit integer, p_offset integer, p_category_id uuid | jsonb | definer | G1S-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_json | p_id uuid, p_status text, p_version uuid | jsonb | U19-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_campaigns | p_ids uuid[] | jsonb | definer | P2-08. Allow-listed public projection (products, tiers, progress, images, milestones) of published ids. |
public_categories | — | jsonb | definer | G1S-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_savings | p_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_json | p_campaign_product_id uuid | jsonb | G1S-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_categories | p_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_specs | p_product_id uuid | jsonb | ||
public_milestone_shares_json | p_campaign_product_id uuid | jsonb | PAF-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_json | p_campaign_id uuid | jsonb | G1S-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_json | p_campaign_product_id uuid, p_status text, p_version uuid | jsonb | U19-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_json | p_campaign_product_id uuid, p_status text, p_version uuid, p_total_units bigint | jsonb | CV3-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_category | p_campaign_id uuid, p_category_id uuid | uuid[] | definer | G1S-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 | — | boolean | P2-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_campaigns | p_ids uuid[] | jsonb | definer | #286. Allow-listed public projection (products, tiers, progress, images, cycles, rule numbers) of published Recurring ids. |
public_recurring_ids | p_search text, p_statuses text[], p_limit integer, p_offset integer | jsonb | definer | U28-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_json | p_id uuid, p_status text, p_version uuid, p_cutoff_hours integer | jsonb | U19-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_facets | p_keyword text, p_kind text, p_category_ids uuid[] | jsonb | definer | G1S-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_items | p_keyword text, p_kind text, p_category_ids uuid[] | TABLE(kind text, campaign_id uuid, campaign_product_id uuid, category_id uuid, ord bigint) | definer | G1S-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 uuid | G2S-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_json | p_campaign_id uuid, p_spin_enabled boolean | jsonb | G2I-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_status | p_state text, p_opens_at timestamp with time zone, p_closes_at timestamp with time zone | text | U19-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_json | p_terms_set_id uuid | jsonb | U19-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_ts | p_at timestamp with time zone | text | ||
publish_job_name | — | text | U19-P2-05. Job name of the publish run (slot campaign:<id>:publish:v<n>). | |
rearm_close_for_order | p_order_id uuid, p_tag text | void | definer | PAF-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_cycles | p_campaign_id uuid | integer | U19-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_jobs | p_campaign_id uuid | text[] | definer | U19-P2-05. Enqueues the publish/open/close runs the campaign wants at its version and cancels its other QUEUED runs. |
record_cycle_skip | p_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 text | jsonb | definer | P2-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_refund | p_order_id uuid, p_point_request_id uuid | boolean | definer | G1S-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_outcome | p_campaign_id uuid, p_expected_version integer, p_run_id uuid, p_rule_code text, p_rule_version text, p_outcome text, p_products jsonb | TABLE(status text, version integer, outcome_id uuid, detail jsonb) | definer | P2-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_ordered | p_campaign uuid | boolean | definer | CV3-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_lines | p_points_value bigint, p_cells jsonb | TABLE(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_allocate | p_deposit bigint, p_points_value bigint, p_points integer, p_values bigint[], p_round_cod boolean | TABLE(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_actual | p_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 | — | trigger | definer | CV3-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_blockers | p_campaign_id uuid, p_policy_version_id uuid, p_closes_at timestamp with time zone | TABLE(pending integer, late integer, odd integer, excluded integer, placed integer) | definer | P2-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_cells | p_outcome_id uuid, p_order_id uuid | jsonb | U28-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_inputs | p_campaign_id uuid, p_expected_version integer, p_run_id uuid | TABLE(status text, campaign_type text, version integer, closes_at timestamptz, closes_at_vn date, policy jsonb, detail jsonb, products jsonb, expired jsonb) | definer | P2-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 | — | text | P2-16. Job name of the Recurring close run (slot campaign:<id>:v<CLOSING version>). | |
recurring_close_obligations_open | — | boolean | definer | FU-F3. True only while the G-CP gate is open (the close job asks; a closed gate keeps the FU-L7 behaviour). |
recurring_close_progress | p_campaign_id uuid | TABLE(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) | definer | P2-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 | — | boolean | definer | #286. G-CP retired 2026-10-16 (team decision): always true. Kept as the seam earlier callers read. |
recurring_overview_facts | p_campaign_id uuid | jsonb | definer | U19-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_today | p_campaign_id uuid | integer | G2S-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_share | p_cap bigint, p_before bigint, p_weight bigint, p_total bigint | bigint | U19-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_policy | p_policy_version_id uuid, p_need text | text | P2-06. APPROVED/INTERIM, or raises campaign_policy_undecided (DETAIL = decision id) for an UNDECIDED policy. | |
reward_policy_valid | p jsonb | boolean | L9 / 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_step | p_step text, p_campaign_id uuid, p_slot_version integer, p_run_id uuid | TABLE(outcome text, campaign_type text, version integer, policy_version_id uuid, from_state text, to_state text, cloned_from_id uuid) | definer | U19-P2-05. One scheduled run as pi_worker: publish / open / close of a campaign, idempotent per slot (B006.R03). |
schedule_close_wait_rerun | p_campaign_id uuid | timestamptz | definer | #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_jobs | p_campaign_id uuid | text[] | definer | U19-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) | definer | FU-RECCLOSE. The approved skip cutoff version that applies now, or no row (DEC-CP-SKIP-CUTOFF undecided). |
spin_wheel_ref | p_wheel uuid | jsonb | definer | CV3-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_names | p_ids uuid[] | TABLE(account_id uuid, display_name text) | definer | U19-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_name | p_step text | text | U19-P2-05. publish | open | close -> its job name. | |
total_qty | p_campaign_product_id uuid, p_at timestamp with time zone | bigint | U19-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_products | p_product_ids uuid[] | SETOF uuid | definer | P2-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_qty | p_campaign_product_id uuid, p_at timestamp with time zone | integer | U19-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_value | p_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 zone | integer | CV3-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_date | p_at timestamp with time zone | date | P2-09. Vietnam calendar date (UTC+07:00, no DST) of a UTC instant. | |
wheel_options | p_search text, p_limit integer | TABLE(id uuid, code text, name text, max_points integer) | definer | CV3-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_begin | p_max_calls integer, p_window_seconds integer | jsonb | definer | CV3-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_reads_period_money | — | boolean | definer | FU-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_allocation | p_scope text, p_order_id uuid | jsonb | definer | U28-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_detail | p_scope text, p_order_id uuid | TABLE(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) | definer | U19-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_payment | p_scope text, p_order_id uuid | TABLE(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) | definer | U19-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_recurring | p_scope text, p_order_id uuid | TABLE(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) | definer | U19-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_shipments | p_scope text, p_order_id uuid | TABLE(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) | definer | U19-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_money | p_scope text, p_order_id uuid | jsonb | definer | U28-P2-02. adminOrder(id).recurring money (order.read, TEAM/ALL): payment.recurring_order_money of a visible order. |
apply_no_receive | p_order_id uuid, p_cycle_id uuid, p_shipment_event_id uuid | text | definer | U19-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_return | p_order uuid, p_cycle_id uuid, p_shipment_event_id uuid | text | definer | U19-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_now | p_campaign_id uuid, p_constraint text | void | definer | P2-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_schedule | p_campaign_id uuid, p_term integer | void | U19-P2-37. A package covers cycles 1..Số kỳ of the schedule (B208.R05); missing cycles -> recurring_schedule_short. | |
assign_participant_ordinal | — | trigger | definer | G1S-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 | — | trigger | definer | G2S-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_axes | p_batch integer | integer | definer | U19-P1-07. Fills the axes of orders that have none, in batches; idempotent (0 when nothing is missing). |
backfill_shipping_axis | p_batch integer | integer | definer | U19-P1-08. Fills the shipping axis of orders and the axes of cycles that have none, in batches; idempotent. |
basket_matches_cycle_lines | p_basket_id uuid, p_cycle_lines jsonb | boolean | G2I-P2-01 (G2-06). True when the quote overrides are exactly the basket's recurring_basket_cycle_lines. | |
basket_matches_lines | p_basket_id uuid, p_lines jsonb | boolean | ||
buyer_cancel_reason | p_order uuid, p_state text, p_campaign_state text, p_closes_at timestamp with time zone | text | definer | #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_order | p_order uuid, p_expected_version integer, p_reason text, p_source_id text, p_reason_code text | jsonb | definer | P2-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_pending | p_order uuid | boolean | definer | #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_reason | p_state text, p_campaign_state text, p_closes_at timestamp with time zone | text | P2-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_eligibility | p_order uuid | jsonb | definer | P2-20. Buyers: server-computed cancellation eligibility of an OWN order (NULL for unknown/foreign), no lock. |
committed_states | — | text[] | ||
committed_units | p_campaign_product_id uuid | bigint | ||
cycle_empty_after_moq | p_order uuid, p_cycle integer | boolean | U28-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_cancelled | p_order uuid, p_cycle integer | boolean | definer | FU-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_goods | p_order uuid | TABLE(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_goods | p_order uuid, p_cycle integer | boolean | G2I-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_empty | p_order uuid, p_cycle integer | boolean | G2I-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_lines | p_order uuid | TABLE(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_money | p_order uuid | TABLE(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_at | p_delivers_from timestamp with time zone | timestamptz | definer | G2I-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_points | p_order_id uuid, p_deposit_vnd bigint, p_source_id text | jsonb | definer | G1S-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_periods | p_order uuid | TABLE(cycle_no integer, value_vnd bigint, cancelled_vnd bigint, prepaid_vnd bigint) | definer | FU-SHORTAGE2. PAY-BRULE-26 after the partial cancellations: cycle value less cancelled units, prepaid allocated from the last cycle backwards. |
effective_v0_vnd | p_order uuid | bigint | definer | |
failed_delivery_count | p_order uuid | integer | definer | #479 A. Cycles of the order Operations settled as failed deliveries; counted with ordering.skips_used against n. |
group_policy_approved | p_policy_version_id uuid | boolean | definer | P2-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 | — | trigger | definer | U19-P1-09. NOTIFICATION activity row (SYSTEM) for every in-app notification about an order. |
is_buyer | — | boolean | P2-11. Matrix U-01/U-02 mirror: ACTIVE APP_USER membership with role user, ACTIVE account, claimed app. | |
legacy_cycle_axes | p_cycle uuid, OUT order_status text, OUT payment_status text | record | definer | U19-P1-08. Order / payment axes of a cycle from its stored facts (backfill); writes nothing. |
legacy_order_axes | p_order uuid, OUT order_status text, OUT payment_status text, OUT cancel_reason text, OUT confirmed_at timestamp with time zone | record | definer | U19-P1-07. Axes of an order computed from its stored facts (backfill and reconciliation); writes nothing. |
legacy_unit_shipping | p_order uuid, p_cycle uuid | text | definer | U19-P1-08. Shipping axis of an order (cycle null) or cycle from its stored facts (backfill); writes nothing. |
lines_ok | p_lines jsonb, p_v0 bigint, p_cycles integer | boolean | ||
log_activity | p_order uuid, p_category text, p_action text, p_actor uuid, p_from text, p_to text, p_note text, p_cycle_no integer | bigint | definer | U19-P1-09. Appends one order activity row; actor null = SYSTEM, owner = CUSTOMER, else OPERATIONS (name snapshot). |
mark_cycles_due | p_at timestamp with time zone, p_batch integer | TABLE(order_id uuid, cycle_id uuid, cycle_no integer, delivery_date date) | definer | U19-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_ok | p_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 text | boolean | U19-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_ok | 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 | boolean | P2-11. Deposit = V0 x rate exactly (never reduced by points); max points = floor(cap x V0 / rate). | |
my_order_bucket | p_order uuid | text | definer | G2I-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_activity | p_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integer, p_limit integer, p_offset integer | TABLE(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) | definer | U19-P1-09. Staff order history from the activity log (legacy rows flagged), newest first, server-filtered. |
order_activity_count | p_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integer | bigint | definer | U19-P1-09. Row count of the same filter; null when the order is missing or out of staff scope. |
order_activity_view | p_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integer | TABLE(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) | definer | U19-P1-09. Activity log rows + legacy history rows before each branch cutover, filtered; private. |
order_axes | p_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) | definer | U19-P1-07/P1-08. Stored order/payment/shipping axes, cancel reason, confirmed_at of staff-visible orders (TEAM/ALL). |
order_axes_changed | p_order uuid, p_from_order text, p_to_order text, p_from_payment text, p_to_payment text, p_actor uuid, p_note text | void | definer | U19-P1-07 hook, U19-P1-09 body: one ORDER_STATUS and/or PAYMENT activity row per axis change (actor null = SYSTEM). |
order_code_of | p_order uuid | text | definer | #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_label | p_order uuid | text | definer | |
order_event_count | p_scope text, p_order uuid | bigint | definer | P2-14. History row count of a visible order; null when missing or out of scope (API: not_found). |
order_events | p_scope text, p_order uuid, p_limit integer, p_offset integer | TABLE(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) | definer | P2-14. Order history in stable order (recorded_at, order_version, id); buyer view without actor/reason. |
order_excess_deposits | p_scope text, p_ids uuid[] | TABLE(order_id uuid, reference_code text, excess_vnd bigint, kind text, cycle_no integer, created_at timestamptz) | definer | PAF-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_facts | p_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) | definer | U13-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_facts | p_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) | definer | P2-14. Close outcome + delivery/payment/refund labels of visible orders (OWN/TEAM/ALL). |
order_history | p_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integer, p_limit integer, p_offset integer | TABLE(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) | definer | U13-P1-03d / FU-06. Staff order history, newest first, server-filtered; actor label/roles SNAPSHOT when stored, else read-time. |
order_history_count | p_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integer | bigint | definer | U13-P1-03d. Row count of the same filter; null when the order is missing or out of staff scope. |
order_history_rows | p_order uuid | TABLE(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[]) | definer | U13-P1-03d / FU-06. Unscoped union of order state, payment, delivery and buyer points facts + stored actor snapshot; private. |
order_history_view | p_scope text, p_order uuid, p_category text, p_actor_kind text, p_cycle integer | TABLE(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) | definer | U13-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_code | p_code text | uuid | definer | #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_counts | p_scope text, p_filter jsonb | TABLE(campaign_type text, n bigint) | definer | U19-P2-10. Staff-visible orders per campaign_type under the list filter without the type (tab counts). |
order_list_facts | p_scope text, p_ids uuid[] | TABLE(order_id uuid, final_value_vnd bigint, paid_cash_vnd bigint, campaign_status text) | definer | U19-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_page | p_scope text, p_filter jsonb, p_limit integer, p_offset integer | TABLE(order_id uuid) | definer | U19-P2-10. One page of staff-visible order ids (TEAM/ALL), newest first, under the list filter. |
order_list_where | p_scope text, p_filter jsonb, p_with_type boolean | text | U19-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_method | p_order uuid | text | definer | U19-P2-21. AdminOrder.method / list filter: payment.remaining_method_of with NOT_CHOSEN read as NONE. |
order_point_adjustment_link | p_scope text, p_ids uuid[] | TABLE(order_id uuid, buyer_account_id uuid, role text, account_id uuid, available_points integer) | definer | U19-P2-18. pi_api only: buyer / Referral / Affiliate accounts and Available points from a RETURNED order (TEAM/ALL). |
order_reward_entries | p_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) | definer | U13-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_tier | p_policy_version_id uuid, p_campaign_product_id uuid, p_basis bigint | TABLE(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 | — | trigger | definer | U19-P1-09. order.created activity row of a submitted order. |
own_current_cycles | p_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) | definer | G2I-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_moq | p_order uuid | integer[] | definer | U28-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_at | p_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_facts | p_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) | definer | G2I-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_referrers | p_ids uuid[] | TABLE(order_id uuid, code text, masked_name text) | definer | G2I-P3-01. ATTRIBUTED Affiliate referrer of the buyer's OWN orders: link code + masked owner name; nothing else. |
own_order_reward_entries | p_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) | definer | G2I-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_label | p_order uuid, p_decision text, p_remaining bigint | text | definer | P2-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_ref | p_campaign_id uuid, p_campaign_cap_bp integer, p_policy_ref text | text | U19-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_periods | p_campaign_id uuid, p_window_no integer, p_term integer, p_cells jsonb, p_deposit bigint | SETOF jsonb | definer | G2S-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_source | p_campaign_id uuid | jsonb | definer | G2S-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_cells | p_lines jsonb, p_cycle_lines jsonb, p_cycles integer | jsonb | U28-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_grid | p_lines jsonb, p_cycle_lines jsonb, p_cycles integer | TABLE(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_problem | p_lines jsonb, p_cycle_lines jsonb, p_cycles integer | text | G2I-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_values | p_lines jsonb, p_cycle_lines jsonb, p_cycles integer | bigint[] | 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_cycle | p_lines jsonb, p_cycle_lines jsonb, p_cycles integer | integer | G2S-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_source | p_campaign_id uuid | jsonb | definer | |
read_visible | p_scope text, p_ids uuid[] | TABLE(order_id uuid) | definer | P2-14. Ids of p_ids the actor reads at scope OWN (buyer) / TEAM / ALL; missing and out of scope look the same. |
recurring_periods | p_campaign_id uuid, p_window_no integer, p_term integer, p_cells jsonb, p_deposit bigint, p_points_value bigint, p_points integer | TABLE(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) | definer | U19-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_periods | p_campaign_id uuid, p_window_no integer, p_term integer, p_cells jsonb, p_deposit bigint, p_points_value bigint, p_points integer | SETOF jsonb | definer | U19-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 | — | integer | definer | U28-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_source | p_basket_id uuid | jsonb | definer | P2-13. Own basket as an ordering source (lines + on-sale state, whole schedule while ACTIVE); else NULL. |
refund_label | p_order uuid, p_state text, p_points integer | text | definer | P2-14. Refund status of a CANCELLED order; REFUNDED only after every capture is refunded (+ points reversed). |
set_cycle_axes | p_cycle uuid, p_order_status text, p_payment_status text, p_shipping_status text, p_actor uuid, p_note text | integer | definer | U19-P1-08. Writes the axes of one cycle (null = keep, status_version + 1, idempotent); one log row per moved axis. |
set_order_axes | p_order uuid, p_order_status text, p_payment_status text, p_cancel_reason text, p_actor uuid | integer | definer | U19-P1-07. Writes the order/payment axes (null = keep) as one axis-only update, status_version + 1; idempotent. |
set_order_shipping | p_order uuid, p_status text, p_actor uuid, p_note text | integer | definer | U19-P1-08. Writes orders.shipping_status (axis-only, status_version + 1, idempotent) and logs one SHIPPING row. |
settle_failed_delivery_cycle | p_order uuid, p_cycle_no integer, p_expected_version integer, p_note text, p_source_id text | jsonb | definer | #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_value | p_order uuid, p_cycle integer | bigint | definer | |
shortage_cancelled_in_cycle | p_order uuid, p_campaign_product uuid, p_cycle integer | integer | definer | |
shortage_cancelled_units | p_order uuid, p_campaign_product uuid | integer | definer | |
shortage_cancelled_value | p_order uuid | bigint | definer | |
skips_used | p_order uuid | integer | G2I-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_count | p_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 | bigint | definer | P2-14. Total of the adminOrders filter (same scope and filter as ordering.staff_orders). |
staff_order_count_ext | p_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 | bigint | definer | |
staff_order_id_by_code | p_scope text, p_code text | uuid | definer | #298. Staff-visible (TEAM/ALL, read_visible) order with this code, case-insensitive exact match; null otherwise. |
staff_order_ids | p_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 | TABLE(order_id uuid, created_at timestamptz) | definer | P2-14. Staff order filter (A-OD-01/08): scope + AND of state/type/campaign/customer/date/as-of/id/name. |
staff_order_ids_ext | p_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 | TABLE(order_id uuid, created_at timestamptz) | definer | U13-P1-03d. ordering.staff_order_ids AND approval-date / payment / delivery / campaign-state / method filters. |
staff_order_lines | p_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) | definer | P2-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_ext | p_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 integer | TABLE(order_id uuid) | definer | |
staff_order_periods | p_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) | definer | FU-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_orders | p_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 integer | 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) | definer | P2-14. adminOrders page (TEAM/ALL scope), newest first (created_at, id); phones masked, street line withheld. |
staff_orders_by_ids | p_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) | definer | U13-P1-03d. Rows of ordering.staff_orders for given ids (TEAM/ALL), masked the same way, newest first. #298: + code. |
staff_phone | p_phone text, p_full boolean | text | U19-P2-11. National phone for a customer reader, customer.mask_phone otherwise. | |
staff_scope_ok | p_scope text | boolean | definer | P2-14. Actor qualifies for TEAM (live order.read TEAM grant, M-02) or ALL (staff_all_reader_roles, empty). |
states | — | text[] | ||
stop_recurring_order | p_order_id uuid, p_source text, p_causation text | boolean | definer | U19-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) | definer | P2-14. Orders attributed (P4-11) to an APP_SALE link owner whose CURRENT team the actor manages (M-02). |
team_sale_ids | — | uuid[] | definer | FU-PERF-A. APP_SALE accounts whose CURRENT team is one the actor manages (computed once per statement). |
tier_no | p_policy_version uuid, p_campaign_product uuid, p_min_qty integer | integer | U19-P2-11. 1-based position of a price tier (by min_qty) in a policy version; the Moc N of the order detail. | |
transition_allowed | p_from text, p_to text | boolean | P2-11 / #388 O3. Order state machine (DEPOSIT_PENDING -> PLACED|DEPOSIT_FAILED|CANCELLED; PLACED -> LOCKED|CANCELLED; LOCKED -> FULFILLED|CANCELLED|FORFEITED). | |
transition_axes | p_from text, p_to text, p_reason text, p_payment text, OUT order_status text, OUT payment_status text, OUT cancel_reason text | record | U19-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
active_rank | p_account uuid, p_audience text, p_at timestamp with time zone | bigint | ||
actor_audience | — | text | ||
actor_can | p_action text | boolean | P4-08. Acting principal may write Tier configuration (ADT-01) right now. | |
actor_can_read | — | boolean | definer | |
actor_is_member | — | boolean | definer | |
append_assignment_event | p_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 text | void | ||
audience_app | p_audience text | text | ||
backfill_activate | p_run uuid, p_version integer, p_correlation text | jsonb | U28-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 | — | jsonb | U28-P3-09. Owner only. Count + hash of the tables the backfill must leave unchanged (reconcile). | |
backfill_mapping | p_at timestamp with time zone | TABLE(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 | — | jsonb | U28-P3-09. Owner only. Post-activation checks: ladder = legacy, one Standard at 0, job state, moved and rank-mismatched customers. | |
backfill_report | p_at timestamp with time zone | jsonb | U28-P3-09. Owner only. Read-only dry-run report of the customer Tier backfill (abort reasons and lists). | |
backfill_start | p_correlation text | TABLE(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_rules | p_version uuid | void | ||
check_set_version | p_version uuid | void | ||
create_membership_tier | p_expected integer, p_name text, p_threshold bigint, p_coefficient numeric, p_benefit text, p_correlation text | jsonb | definer | |
customer_ladder | p_at timestamp with time zone | TABLE(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 | — | boolean | definer | U28-P3-03. True once the customer Tier set is in force: saveTierVersion / publishTierVersion refuse USER. |
customer_tiers_at | p_at timestamp with time zone, p_account uuid | TABLE(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_tier | p_expected integer, p_tier uuid, p_correlation text | jsonb | definer | |
evaluate_customer | p_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 text | TABLE(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) | definer | U28-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_event | p_event_id uuid, p_aggregate_type text, p_aggregate_id text, p_correlation text | TABLE(status text, evaluation_id uuid, outcome text, decision text, assignment_id uuid, tier_version_id uuid) | definer | |
evaluate_member | p_account uuid, p_audience text, p_trigger text, p_at timestamp with time zone, p_source_event uuid, p_correlation text | TABLE(status text, evaluation_id uuid, outcome text, decision text, assignment_id uuid, tier_version_id uuid) | definer | P4-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_entry | p_request uuid, p_correlation text | TABLE(status text, history_id uuid) | definer | U28-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_lots | p_limit integer | integer | definer | |
list_members | p_audience text, p_definition uuid, p_keyword text, p_limit integer, p_offset integer | TABLE(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) | definer | P4-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_set | p_expected_version integer | tier_set_versions | ||
member_active | p_account uuid, p_audience text, p_at timestamp with time zone | boolean | ||
member_history_head | p_account uuid, p_at timestamp with time zone | SETOF member_tier_history | U28-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) | definer | P5-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_customers | p_account uuid, p_definition uuid, p_keyword text, p_limit integer, p_offset integer, p_phone_search boolean | TABLE(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) | definer | U28-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_write | p_expected integer, p_tier uuid | jsonb | definer | |
membership_tier_history | p_account uuid, p_limit integer, p_offset integer | TABLE(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) | definer | U28-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_preview | p_kind text, p_tier uuid, p_threshold bigint | jsonb | definer | |
membership_tiers | p_counts boolean | TABLE(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) | definer | U28-P3-08 HT-US-01/03. Customer Tier ladder with position, count and customers per Tier; TIR-02 readers only. |
mission_check | p_account uuid, p_audience text, p_version uuid, p_at timestamp with time zone | TABLE(status text, detail jsonb) | ||
mission_is_effective | p_mission uuid | boolean | ||
multiplier_actor | p_kind text | boolean | ||
multiplier_change_guard | — | trigger | definer | |
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_json | p_version uuid | jsonb | ||
multiplier_previous | p_version uuid | jsonb | ||
next_review_instant | p_at timestamp with time zone | timestamptz | ||
next_review_instant | p_at timestamp with time zone, p_audience text | timestamptz | U28-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_write | p_expected integer | tier_set_versions | ||
order_problem | p_definition uuid, p_audience text, p_order integer, p_threshold bigint, p_from timestamp with time zone, p_to timestamp with time zone | text | ||
perform_sale_transfer | p_application uuid, p_correlation text | text | definer | FU-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_at | p_anchor timestamp with time zone, p_months integer, p_zone text | timestamptz | ||
rank_ledger_sum | p_account uuid, p_audience text, p_at timestamp with time zone | bigint | U28-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_history | p_account uuid, p_limit integer, p_offset integer | TABLE(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) | definer | U28-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_at | p_at timestamp with time zone | rank_policy_versions | ||
reader_roles | — | text[] | P4-07 mirror of matrix TIR-02 tier.read (WEB_ADMIN, PROPOSED). | |
record_evaluation | p_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 jsonb | TABLE(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_debit | p_event_id uuid, p_request_id uuid, p_correlation_id text | TABLE(outcome text, debit_id uuid, allocated_points integer, unallocated_points integer) | definer | U28-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_lot | p_event_id uuid, p_request_id uuid, p_correlation_id text | TABLE(outcome text, lot_id uuid, policy_version_id uuid, anchor_at timestamptz) | definer | P4-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_advance | p_job uuid, p_version integer, p_checkpoint text, p_processed integer, p_changed integer, p_done boolean, p_failure text | integer | definer | U28-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_candidates | p_after uuid, p_limit integer | TABLE(account_id uuid) | definer | U28-P3-07. pi_worker only. Keyset page of the customers a full re-evaluation evaluates (active APP_USER members). |
reevaluation_claim | p_max_attempts integer | TABLE(id uuid, version integer, reason text, checkpoint_key text, correlation_id text, attempts integer, total_count integer) | definer | U28-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_json | p_job uuid | jsonb | ||
review_candidates | p_at timestamp with time zone, p_after_account uuid, p_after_audience text, p_limit integer | TABLE(account_id uuid, audience text) | definer | |
review_member | p_account uuid, p_audience text, p_at timestamp with time zone, p_correlation text | TABLE(status text) | definer | U28-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_transfers | p_limit integer, p_correlation text | TABLE(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 | — | boolean | definer | |
sale_transition_retry | p_correlation text | text | definer | |
save_rank_policy | p_expected_version integer, p_expiry_months integer | rank_policy_versions | definer | U28-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_count | p_definition uuid, p_at timestamp with time zone | integer | ||
set_items_at | p_at timestamp with time zone | SETOF tier_set_items | U28-P3-01. Tiers of the customer set version in force at the instant, threshold ascending. | |
set_tier_json | p_set uuid, p_definition uuid | jsonb | ||
set_tier_missing | p_tier uuid | void | ||
set_version_at | p_at timestamp with time zone | SETOF tier_set_versions | U28-P3-01. Customer Tier set version in force at the instant; no row = legacy path (B2 dual read). | |
test_tier | p_account uuid, p_audience text, p_version uuid, p_at timestamp with time zone | TABLE(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_tier | p_expected integer, p_tier uuid, p_name text, p_threshold bigint, p_coefficient numeric, p_benefit text, p_correlation text | jsonb | definer | |
versions_in_force | p_audience text, p_at timestamp with time zone | SETOF tier_versions | ||
write_set_version | p_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 text | jsonb | ||
writer_roles | — | text[] | P4-08 mirror of matrix ADT-01 tier.write (WEB_ADMIN, PROPOSED). |
schema fulfillment
Chưa có COMMENT ON SCHEMA
| Hàm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_is_operator | — | boolean | P2-17. Acting principal holds a shipment operator role in WEB_ADMIN right now (ACTIVE account/membership). | |
apply_event | p_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 boolean | jsonb | definer | |
apply_exception | p_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 boolean | jsonb | definer | |
candidate_address_changes | p_orders uuid[] | TABLE(order_id uuid, address_updated_at timestamptz) | definer | U28-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_axes | p_orders uuid[] | jsonb | definer | U28-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_json | p_case uuid | jsonb | definer | |
cod_return_refund_case | p_case uuid | uuid | definer | |
cod_signals | — | text[] | ||
complete_recurring_order | p_order uuid, p_cause text | boolean | definer | U19-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_count | p_shipment uuid | integer | definer | U19-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_of | p_shipment uuid | integer | U28-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_signal | p_shipment uuid, p_link uuid, p_kind text, p_issue text | text | definer | |
exception_kinds | — | text[] | ||
exception_status | p_occurred timestamp with time zone, p_state text, p_delivered_at timestamp with time zone | text | P2-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_orders | p_shipment uuid, p_event uuid | jsonb | definer | U19-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_shipment | p_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 | jsonb | definer | P2-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_shipment | p_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 jsonb | jsonb | definer | U19-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_taken | p_items jsonb | jsonb | definer | U28-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_facts | p_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) | definer | FU-AC-TRIAGE L6. Operators only: per grouped order/cycle its order state, COD still to collect and resolution state. |
link_payment_modes | p_shipments uuid[] | TABLE(link_id uuid, payment_mode text) | definer | U13-P2-08d. Operators only: payment mode (COD/ONLINE) of each link of the given shipments. |
lock_carrier_shipment | p_carrier_code text, p_carrier_ref text | void | definer | |
lock_cod_shipments | p_cod uuid | void | definer | |
lock_unit_method | p_order uuid, p_order_cycle uuid, p_cycle_no integer, p_actor uuid, p_source text | jsonb | definer | U19-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_payments | p_order uuid | void | definer | |
next_shipment_code | — | text | definer | U13-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_failed | p_link uuid, p_event uuid | void | definer | U19-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_returned | p_link uuid, p_event uuid | void | definer | U19-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 | — | trigger | definer | |
order_progress | p_scope text, p_order uuid | TABLE(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) | definer | P2-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_head | p_scope text, p_order uuid | TABLE(order_id uuid, campaign_type text, order_state text, committed_cycles integer) | definer | P2-21. Header of a visible order (campaign type, state, committed delivery units); none when missing/out of scope. |
reapply_pending | p_shipment uuid | jsonb | definer | FU-DEF141. Applies retained OUT_OF_ORDER carrier/system facts that became legal, earliest occurred_at first (GAP-1600). |
record_cod_return | p_shipment uuid, p_order uuid, p_reason text, p_evidence uuid[], p_source_event_id text | jsonb | definer | FU-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_attempt | p_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 text | jsonb | definer | |
record_external_event | p_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 text | jsonb | definer | |
record_external_exception | p_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 text | jsonb | definer | |
record_operator_event | p_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 text | jsonb | definer | |
record_operator_exception | p_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 text | jsonb | definer | |
recurring_order_ended | p_order uuid | boolean | definer | U19-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_delivered | p_shipment uuid | jsonb | definer | U19-P2-30. No-op (nothing is held for the COD any more); kept for the deploy window, dropped by U19-P4-02. |
resolve_cancelled_items | p_shipment uuid, p_expected_version integer, p_items jsonb, p_reason text, p_source_event_id text | jsonb | definer | FU-AC-TRIAGE L6. pi_api operators: records that the lines of cancelled orders are removed from a shipment before handover. |
search_fold | p_text text | text | definer | U19-P2-27. Lower case, diacritics removed (unaccent; Đ -> d): the key of the shipment recipient-name search. |
set_shipment_contact | p_shipment uuid, p_name text, p_phone text, p_slot text, p_clear text[] | jsonb | definer | G2I-P3-03 (O8, E9). Driver name / phone / delivery slot of a shipment, only in the transaction of its status update. |
ship_candidate_days | — | SETOF date | definer | U19-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) | definer | U19-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_candidates | p_date date, p_type text, p_limit integer, p_offset integer | TABLE(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) | definer | U19-P2-28. The 7-argument candidates without a search (old callers); same columns as 20261214012100. |
ship_candidates | p_date date, p_type text, p_prefix text, p_needle text, p_phone text, p_limit integer, p_offset integer | TABLE(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) | definer | U19-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_readiness | p_order uuid, p_order_cycle uuid | TABLE(ready boolean, payment_mode text, cod_due_vnd bigint, reason text) | definer | U19-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_facts | p_shipments uuid[] | TABLE(shipment_id uuid, due_vnd bigint, lines jsonb, collected boolean) | definer | U28-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_preview | p_shipment uuid | jsonb | definer | U28-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_due | p_shipment uuid | bigint | definer | U28-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_effects | p_shipment uuid | TABLE(event_id uuid, order_id uuid, order_code text, cycle_no integer, order_status text, payment_status text) | definer | U28-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_facts | p_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) | definer | U19-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 | — | trigger | definer | |
shipment_search_ids | p_prefix text, p_needle text, p_phone text | SETOF uuid | definer | U19-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_preview | p_shipment uuid, p_to text, p_cod boolean | jsonb | definer | U28-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_effects | p_shipment uuid | jsonb | definer | U19-P2-26. Order / payment / shipping status of every order / cycle of a shipment (command result). |
shipments_order_axes_delivered | — | trigger | definer | U19-P1-07. DELIVERED shipment -> its CONFIRMED Group Buy orders become SUCCESS (order axis), COD collected or not. |
shipments_sync_unit_shipping | — | trigger | definer | |
shortage_rows_complete_order | — | trigger | definer | |
skip_requests_complete_order | — | trigger | definer | |
sources | — | text[] | P2-17. Fulfillment event sources: OPERATOR, CARRIER, SYSTEM. A customer is never a source. | |
staff_cycle_schedule | p_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 integer | TABLE(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) | definer | FU-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_rank | p_state text | integer | ||
states | — | text[] | ||
sync_link_shipping | p_link uuid, p_actor uuid | boolean | definer | U19-P1-08. The order / cycle of one link takes the shipment state (CREATED reads PACKING); cancelled units kept. |
sync_unit_shipping | p_shipment uuid, p_actor uuid | integer | definer | U19-P1-08. Applies the shipment state to the shipping axis of every order / cycle it carries; returns units seen. |
transition_allowed | p_from text, p_to text | boolean | P2-17. Shipment machine: CREATED -> PACKING -> SHIPPING -> DELIVERED|DELIVERY_FAILED|RETURNED; DELIVERY_FAILED -> SHIPPING|RETURNED. | |
transition_recorded | p_from text, p_to text | boolean | U19-P1-08. Shipment transitions ever legal (current machine + earlier ones + backfill): shape check of stored facts. | |
unit_cod_plan | p_order uuid, p_order_cycle uuid | TABLE(payment_mode text, cod_due_vnd bigint, create_vnd bigint, online_open uuid) | definer | U19-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_pending | p_order uuid | boolean | definer | |
update_shipment_status | p_shipment uuid, p_expected_version integer, p_to text, p_note text, p_cod boolean, p_source_event_id text | jsonb | definer | U19-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
account_kind_for_app | p_app app_code | text | PPI-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 text | P1-02/P1-03 fix. Missing/excess privileges of the auth runtime design (pi_auth + definer owner); expect 0 rows. | |
credential_change | p_account uuid, p_sid uuid, p_hash text, p_correlation_id correlation_ref | jsonb | definer | PPI-P2-01. /password/change: CHANGED|NO_CREDENTIAL|SESSION_INVALID; other sessions revoked (PASSWORD_CHANGE). |
credential_create | p_subject uuid, p_phone text, p_hash text, p_challenge_id uuid | jsonb | definer | AF-P2-03. Saga S2: create the local credential, idempotent by SIGN_UP challenge (CREATED|EXISTS|PHONE_EXISTS). |
credential_for_account | p_account uuid | jsonb | definer | PPI-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_phone | p_phone text | jsonb | definer | AF-P2-03. Sign-in lookup {subject, password_hash, account_id, phone} or null. |
credential_set | p_account_id uuid, p_hash text | jsonb | definer | AF-P2-03. Reset: upsert the account's credential (CREATED|UPDATED). |
mask_email | p text | text | ||
mask_phone | p text | text | ||
mask_pipoint_uid | p text | text | ||
mfa_attempt | p_account uuid, p_app app_code, p_purpose text, p_factor_id uuid, p_max_attempts integer, p_window_seconds integer | jsonb | definer | |
mfa_audit | p_account uuid, p_action text, p_result text, p_reason text, p_metadata jsonb, p_correlation_id correlation_ref | void | ||
mfa_block | p_account uuid, p_app app_code | text | ||
mfa_enroll | p_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_ref | jsonb | definer | |
mfa_finish | p_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_ref | jsonb | definer | |
mfa_status | p_account uuid, p_app app_code | jsonb | definer | |
password_reset_claim | p_grant_hash bytea, p_app app_code, p_correlation_id correlation_ref | jsonb | definer | |
password_reset_consume | p_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_ref | jsonb | definer | |
password_reset_finish | p_grant_id uuid, p_result text, p_correlation_id correlation_ref | jsonb | definer | |
password_reset_issue | p_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_ref | jsonb | definer | |
password_reset_subject | p_phone text | uuid | ||
pipoint_audit | p_account uuid, p_action text, p_result text, p_reason text, p_before jsonb, p_after jsonb, p_metadata jsonb, p_correlation_id correlation_ref | void | ||
pipoint_bind | p_issuer text, p_uid text, p_phone phone_e164, p_email text, p_display_name text, p_correlation_id correlation_ref | jsonb | definer | PPI-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_link | p_account_id uuid, p_sid uuid, p_issuer text, p_uid text | jsonb | definer | PPI-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_begin | p_scope text, p_key_hash bytea, p_max_attempts integer, p_window_seconds integer | jsonb | definer | PPI-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_credentials | p_retention_seconds integer, p_batch integer | TABLE(o_grants integer, o_challenges integer, o_held integer, o_sign_in_challenges integer) | definer | FU-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_sessions | p_retention_seconds integer, p_batch integer | TABLE(o_sessions integer) | definer | AF-P2-04. Deletes PIDEAL sessions ended (revoked or expired) longer than the retention. Worker only. |
role_assignment_revoked_end_sessions | — | trigger | definer | AF-P3-11. Trigger: a revoked WEB_ADMIN role assignment ends that account's WEB_ADMIN sessions (ROLE_DOWNGRADE). |
role_grants_narrowed_end_sessions | — | trigger | definer | AF-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_check | p_sid uuid, p_account_id uuid, p_app app_code | boolean | definer | |
session_create | p_account_id uuid, p_app app_code, p_refresh_hash bytea, p_idle interval, p_absolute interval | jsonb | definer | |
session_revoke | p_sid uuid, p_reason text | jsonb | definer | |
session_revoke_account | p_account_id uuid, p_app app_code, p_reason text | integer | definer | |
session_rotate | p_sid uuid, p_presented bytea, p_next bytea, p_app app_code, p_idle interval, p_grace interval | jsonb | definer | |
sign_in_access | p_auth_user_id uuid, p_app app_code, p_phone phone_e164 | jsonb | definer | |
sign_in_audit | p_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_ref | void | definer | |
sign_in_begin | p_phone phone_e164, p_app app_code, p_max_failures integer, p_window_seconds integer | jsonb | definer | P1-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_create | p_account uuid, p_app app_code, p_secret_hash bytea, p_steps text[], p_correlation_id correlation_ref | jsonb | definer | PPI-P2-01. Opens a 10-minute WEB_ADMIN sign-in challenge of a STAFF account (hash of the secret only). |
sign_in_challenge_finish | p_challenge_id uuid, p_secret_hash bytea, p_correlation_id correlation_ref | jsonb | definer | PPI-P2-01. Consumes a challenge whose steps are all done: FINISHED {account_id, app, phone}|STEPS_PENDING|refusal. |
sign_in_challenge_open | p_challenge_id uuid, p_secret_hash bytea, p_step text, p_max_attempts integer | jsonb | definer | PPI-P2-01. PROCEED|INVALID|EXPIRED|LOCKED|OUT_OF_ORDER for the next step; read-only. |
sign_in_challenge_refusal | c sign_in_challenges, p_secret_hash bytea, p_step text, p_max_attempts integer | text | ||
sign_in_challenge_step | p_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_ref | jsonb | definer | PPI-P2-01. Records DONE|FAILED of the next step: DONE|FAILED|LOCKED|NOT_READY or a refusal. |
sign_in_fail | p_phone phone_e164, p_app app_code, p_max_failures integer, p_lock_seconds integer, p_correlation_id correlation_ref | jsonb | definer | |
sign_in_release | p_phone phone_e164, p_app app_code | void | definer | P1-03 + PPI-P1-02 (B-07). Gives back an undecided attempt of (kind of p_app, phone). |
sign_up_abandon | p_grant_id uuid, p_reason text, p_correlation_id correlation_ref | jsonb | definer | |
sign_up_bind | p_grant_id uuid, p_auth_user_id uuid | jsonb | definer | |
sign_up_consume | p_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_ref | jsonb | definer | |
sign_up_find_identity | p_phone text, p_challenge_id uuid | jsonb | definer | |
sign_up_issue | p_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_ref | jsonb | definer | |
sign_up_link | p_grant_id uuid, p_correlation_id correlation_ref | jsonb | definer | |
sign_up_reconcile | p_stale_seconds integer, p_correlation_id correlation_ref | jsonb | definer | |
staff_credential_for_phone | p_phone text | jsonb | definer | PPI-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_issue | p_caller uuid, p_sid uuid, p_target uuid, p_hash text, p_correlation_id correlation_ref | jsonb | definer | PPI-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_can | p_action text | boolean | P4-15. Acting principal may read/write Lucky Wheel configuration (matrix SPN-02/SPN-03, GAP-67: nobody). | |
actor_wallet_linked | — | boolean | definer | VQM-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_detail | p_session uuid | TABLE(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) | definer | VQM-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_history | p_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 uuid | TABLE(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) | definer | VQM-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_spins | p_intervals jsonb, p_at timestamp with time zone | integer | G2I-P1-02 (D6). Spins of the interval holding p_at, half-open [starts_at, ends_at); 0 outside every interval. | |
campaign_closed | p_campaign_id uuid, p_at timestamp with time zone | boolean | definer | G1S-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_outcome | p_campaign_id uuid | boolean | definer | VQM-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_wheel | p_campaign uuid | uuid | definer | CV3-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_write | p_campaign uuid | uuid | definer | VQM-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_wheel | p_wheel uuid | TABLE(id uuid, code text, name text) | definer | VQM-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_disconnected | p_session uuid, p_correlation text | TABLE(result_id uuid, reward_action_id uuid) | definer | VQM-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_session | p_session uuid, p_correlation text | TABLE(outcome text, state text, version integer, result_id uuid, reward_action_id uuid) | definer | VQM-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_session | p_session uuid, p_issue boolean, p_correlation text | TABLE(result_id uuid, reward_action_id uuid) | definer | FU-717. Internal: ends a session that has draws (COMPLETED, the one highest result, the one reward intent). |
heartbeat | p_session uuid, p_correlation text | TABLE(outcome text, state text, version integer, result_id uuid, reward_action_id uuid) | definer | VQM-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 | — | integer | VQM-P1-07 DEC-VQM-07. H: seconds between spinSessionHeartbeat calls while ACTIVE (SpinSession.heartbeatIntervalSeconds). | |
intervals_ok | p jsonb | boolean | ||
leave_session | p_session uuid, p_actor uuid, p_correlation text | TABLE(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_code | p_at timestamp with time zone | text | definer | VQM-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_deposit | p_order_id uuid, p_order_version integer, p_event_id uuid, p_correlation_id text | TABLE(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) | definer | VQM-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_spin | p_order_id uuid | TABLE(availability text, session_id uuid, state text, spins_left integer, resumable_until timestamptz, wallet_required boolean, enterable_until_outcome boolean) | definer | VQM-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_session | p_owner uuid | boolean | ||
play | p_session uuid, p_draw_no integer, p_roll numeric, p_rng_source text, p_correlation text | TABLE(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) | definer | P4-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_status | p_issue_status text, p_issue_reason text, p_release_status text, p_cancel_status text | TABLE(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 | — | interval | VQM-P1-07 DEC-VQM-07. T: an entered ACTIVE session whose last signal is older than this has disconnected. | |
prize_tiers_ok | p jsonb | boolean | ||
public_max_points_per_spin | p_campaign_id uuid, p_spin_enabled boolean | integer | G1S-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_points | p_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_display | p_campaign_ids uuid[] | TABLE(campaign_id uuid, tone text, rules_text text, max_points integer, slots jsonb) | definer | VQM-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_change | p_wheel_id uuid, p_actor uuid, p_kind text, p_old jsonb, p_new jsonb | uuid | definer | VQM-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_rounds | p_rounds jsonb, p_opens_at timestamp with time zone, p_closes_at timestamp with time zone | TABLE(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_order | p_order uuid | TABLE(base_points integer, rule_version_id uuid) | definer | P4-16. pi_worker: base points of the one retained result of the order's COMPLETED session. |
rounds_ok | p jsonb | boolean | VQM-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_config | p_wheel_id uuid, p_actor uuid, p_config jsonb, p_expected_version integer | TABLE(wheel_id uuid, code text, wheel_version integer, outcome text, rule_version_id uuid, superseded_rule_version_id uuid) | definer | VQM-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_extras | p_sessions uuid[] | TABLE(session_id uuid, order_state text, rewards jsonb) | definer | P4-16. pi_api: order state + SPIN reward rows of the acting buyer's own sessions (no other rows). |
session_ref | p_session uuid | text | definer | |
slots_ok | p jsonb | boolean | VQM-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_sessions | p_limit integer | TABLE(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) | definer | VQM-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_roll | p jsonb, p_roll numeric | TABLE(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_points | p jsonb, p_tier_no integer | integer | ||
tone_palette | p_tone text | TABLE(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_changes | p_old jsonb, p_new jsonb | jsonb | VQM-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_page | p_wheel_id uuid, p_from date, p_to date, p_actor uuid, p_limit integer, p_offset integer | TABLE(total bigint, actors jsonb, id uuid, at timestamptz, actor_id uuid, actor_name text, kind text, changes jsonb) | definer | VQM-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_locked | p_wheel uuid | boolean | definer | CV3-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_campaigns | p_wheel uuid | text[] | definer | VQM-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 | — | trigger | definer | |
wheels_record_deactivated | — | trigger | definer | VQM-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
account_status | p_account uuid | text | U6-P2-22. Derived account status of one Sale (owner context only). | |
activate | p_application_id uuid, p_account_id uuid, p_expected_version integer, p_reason text, p_correlation_id text | TABLE(account_id uuid, membership_version integer, change_request_id uuid, change_version integer) | definer | P1-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 | — | boolean | U6-P2-22. The acting principal holds a live SAL-02 role now (WEB_ADMIN, ACTIVE account and membership); fail closed. | |
actor_can_read | — | boolean | FU-L4-SALE-READ. The acting principal holds a live reader role (matrix SAL-01); false for everyone else (fail closed). | |
actor_can_review | — | boolean | U6-P2-22. The acting principal holds a live SAL-03 role now (WEB_ADMIN, ACTIVE account and membership); fail closed. | |
affiliate_orders | p_account uuid, p_keyword text, p_limit integer, p_offset integer | TABLE(order_id uuid, customer_account_id uuid, ordered_at timestamptz, order_state text, value_vnd bigint, order_total bigint, customer_total bigint, total bigint) | definer | FU-L4-SALE-READ AP-17. Orders attributed to one Sale (Affiliate Last-Touch), searchable; needs sale.read (SAL-01). |
affiliate_page | p_account uuid, p_keyword text, p_limit integer, p_offset integer | TABLE(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) | definer | U6-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_ticket | p_account uuid, p_ticket uuid, p_expected_version integer, p_qualification_verified boolean, p_correlation_id text | TABLE(kind text, ticket_version integer, account_status text, version integer) | definer | U6-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_media | p_account uuid, p_media uuid, p_use text, p_max_bytes bigint, p_field text | void | ||
conflicts | p_account uuid, p_username text, p_email text, p_referral text, p_phone text | text[] | ||
create_sale | p_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 text | TABLE(account_id uuid, sale_code text, version integer) | definer | U6-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_rewards | p_account uuid | TABLE(order_id uuid, points bigint) | definer | U6-P7-56 NEW-SL-08. Internal: points credited to one Sale per order (AFFILIATE_ORDER ISSUE accepted, not cancelled); sale.read. |
derive_account_status | p_membership text | text | U6-P2-22. APP_SALE membership status -> SaleAccountStatus (INITIATED | ACTIVE | INACTIVE | LOCKED). | |
derive_ticket_status | p_application text, p_change_pending boolean, p_membership text | text | U6-P2-22. Delegates to the 4-argument form with no profile-change history (REJECTED application = REJECTED since U6-P7-02). | |
derive_ticket_status | p_application text, p_change_pending boolean, p_membership text, p_last_change text | text | U6-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) | definer | FU-L4-SALE-READ. Private: every Sale (membership or application) with the raw phone, for the reads below only. |
format_code | p_number bigint | text | ||
issue_code | — | trigger | definer | |
lock_ticket | p_account uuid, p_ticket uuid, p_expected_version integer | TABLE(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_media | p_media uuid, p_use_type text, p_account uuid | boolean | definer | U6-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). |
member | p_account uuid | TABLE(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) | definer | FU-L4-SALE-READ AP-17. One Sale: identity (masked), tier, application and account status; needs sale.read (SAL-01). |
member_page | p_keyword text, p_ticket text, p_account text, p_limit integer, p_offset integer | TABLE(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) | definer | U6-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_page | p_keyword text, p_ticket text, p_account text, p_limit integer, p_offset integer, p_sort text | TABLE(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) | definer | U12-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_profile | p_account uuid | TABLE(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) | definer | U6-P2-22 SL-US-02. One Sale: profile, tier, derived statuses, open ticket, editable account status; needs sale.read. |
members | p_keyword text, p_application text, p_account text, p_team uuid, p_limit integer, p_offset integer | TABLE(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) | definer | FU-L4-SALE-READ AP-16. One page of Sales, filters AND-combined, phone masked, newest first; needs sale.read (SAL-01). |
membership | p_sale uuid | TABLE(account_id uuid, status text, version integer, team_id uuid, team_version integer) | definer | P1-13. APP_SALE membership + current team of a Sale in the actor's TEAM scope (guard row context). |
new_referral_code | — | text | U6-P7-55 (NEW-SL-07). System-generated Sale referral code (Referral link format), unused by any Sale, link or profile. | |
one_open_ticket_guard | — | trigger | definer | |
phone_owner | p_phone text | TABLE(account_id uuid, is_sale boolean) | definer | U6-P7-53 (NEW-SL-05). The account holding this phone and whether it already is a Sale; needs sale.manage. |
profile_conflicts | p_account uuid, p_username text, p_email text, p_referral text, p_phone text | text[] | definer | U6-P2-22. Taken fields (username, email, referralCode, phone) excluding the Sale itself; null unless sale.manage. |
profiles_guard | — | trigger | definer | |
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_page | p_account uuid, p_keyword text, p_limit integer, p_offset integer | TABLE(customer_account_id uuid, customer_code text, full_name text, registered_at timestamptz, referred_total bigint, total bigint, reward_points bigint, reward_total bigint) | definer | U6-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. |
referrals | p_account uuid, p_keyword text, p_limit integer, p_offset integer | TABLE(customer_account_id uuid, full_name text, registered_at timestamptz, referred_total bigint, total bigint) | definer | FU-L4-SALE-READ AP-17. Customers referred by one Sale (SIGNUP milestone), searchable; needs sale.read (SAL-01). |
reject_ticket | p_account uuid, p_ticket uuid, p_expected_version integer, p_reason_id uuid, p_note text, p_correlation_id text | TABLE(kind text, ticket_version integer, account_status text, version integer) | definer | U6-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) | definer | U6-P7-29 SL-US-04. Active seeded rejection reasons by display order, with requires_note; needs sale.review. |
reviewer_not_creator_guard | — | trigger | definer | U6-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) | definer | U6-P2-22. Private: every Sale (sale_codes) with raw and masked phone, profile, derived ticket/account status, version. |
set_status | p_sale uuid, p_status text, p_expected_version integer, p_reason text | TABLE(version integer, status text, previous_status text) | definer | P1-13. ACTIVE/SUSPENDED/LOCKED of an activated Sale membership by a TEAM-scoped sale_profile.manage holder. |
set_status_bulk | p_items jsonb, p_status text, p_correlation_id text | TABLE(account_id uuid, outcome text, previous_status text, status text, version integer) | definer | U6-P2-22 SL-US-01 AC09. Atomic bulk account status (1..100); Khoi tao skipped, same status unchanged; needs sale.manage. |
ticket_status | p_account uuid | text | U6-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) | definer | U6-P2-22 SL-US-03 AC01. Published Sale tiers in force now; needs sale.manage. |
touch_profile | p_account uuid | integer | ||
update_sale | p_account uuid, p_expected_version integer, p_patch jsonb, p_correlation_id text | TABLE(version integer, changed boolean, fields text[]) | definer | U6-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_can_manage | — | boolean | P2-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 | — | boolean | U12-FU-58 (GAP-2303). Acting principal holds catalog.read (CAT-01) at ALL in WEB_ADMIN right now (rbac.actor_grants()). | |
attribute_has_values | p_attribute_id uuid | boolean | PSW-P1-06. True when a live value of a live product uses the attribute (data_type lock, delete only with 0 values). | |
attribute_phase | p_attribute_id uuid | text | PSW-P1-05 (design §2). CATEGORY (live category) | COMMON (category_id null) | ARCHIVED (category soft-deleted); null for a missing, deleted or unreadable attribute. | |
attribute_scope | p_category_id uuid | TABLE(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_count | p_brand_id uuid | bigint | P2-01 hook, replaced by P2-02: non-deleted products assigned to the brand (0 until products exist). | |
category_branch | p_category_id uuid | TABLE(category_id uuid) | PSW-P1-06 (R3). The live category with its live ancestors and descendants; empty for a missing / deleted category. | |
category_height | p_id uuid | integer | ||
category_is_leaf | p_id uuid | boolean | ||
category_level | p_id uuid | integer | ||
category_path_names | p_id uuid | text[] | ||
category_product_count | p_category_id uuid | bigint | P2-01 hook, replaced by P2-02: non-deleted products directly assigned to the category (0 until products exist). | |
category_subtree | p_category_id uuid | TABLE(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_components | p_combo_id uuid | uuid[] | 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 | — | void | P2-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_units | p_unit_id uuid | integer | ||
name_key | value text | text | P2-01 Rule #8 key: trim + NFC + Unicode lower (pg_c_utf8). No diacritic or inner-space folding (gap). | |
product_blockers | p_ids uuid[] | TABLE(product_id uuid, kind text, ref_id uuid, ref_name text, ref_state text) | definer | U6-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_campaigns | p_product_id uuid | TABLE(campaign_id uuid, name text, campaign_type text, state text, sku text) | definer | P2-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_valid | p_columns text[] | boolean | U12-P2-19. Canonical column set: known codes, locked present, no duplicate, fixed order. | |
product_combo_count | p_product_id uuid | bigint | ||
product_default_columns | — | text[] | U12-P2-19. Default product-list columns: the 8 columns of the current table (2 locked + 6). | |
product_history_actors | p_product_id uuid | TABLE(account_id uuid, display_name text, event_count integer) | definer | U12-P3-09, U12-FU-58. Distinct actors of a product with event counts and names, catalog.read holders only. |
product_history_export_rows | p_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 | SETOF catalog.product_history_row | definer | U12-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_gate | p_export boolean, p_product_id uuid | void | ||
product_history_guard | — | trigger | ||
product_history_read | p_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 integer | SETOF catalog.product_history_row | definer | U12-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_rows | p_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 integer | SETOF catalog.product_history_row | ||
product_locked_columns | — | text[] | U12-P2-19. Always-shown product-list columns (SKU, NAME). | |
product_open_campaign_count | p_product_id uuid | bigint | definer | P2-06 (replaces the P2-02 stub): unfinished campaigns (DRAFT/REVIEW/ACTIVE/CLOSING) containing the product. |
product_unit_in_use | p_unit_id uuid | text | PSW-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_history | p_batch integer | integer | definer | U12-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_history | p_operation text, p_request_id text, p_correlation_id text, p_source text, p_occurred_at timestamp with time zone, p_events jsonb | TABLE(product_id uuid, event_id uuid, replayed boolean) | definer | U12-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_products | p_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_names | p_ids uuid[] | TABLE(account_id uuid, display_name text) | definer | U6-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
accounts_by_referral | p_code text | SETOF uuid | definer | U6-P2-23. Customers whose profile referral code equals the whole given code (exact); customer readers. |
accounts_in_province | p_province text | SETOF uuid | definer | U6-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_tier | p_tier uuid | SETOF uuid | definer | U6-P2-23, U28-P7-01. Customers whose current USER Tier (customer.tier_heads) is the given definition. |
active_rank_of | p_account uuid | bigint | definer | U6-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_holds | roles text[] | boolean | P2-04. Acting principal holds one of these WEB_ADMIN roles right now (ACTIVE account and membership). | |
addresses_of | p_account uuid | TABLE(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) | definer | U6-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_code | p_account uuid | text | definer | U6-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_valid | p_columns text[] | boolean | U6-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_for | p_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) | definer | U6-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) | definer | U6-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_code | p_joined_at timestamp with time zone, p_number integer | text | U6-P7-61 Q-3. KH + ddmmyyyy (Vietnam date of the join instant) + 6-digit counter. The only place of the code shape. | |
issue_code | — | trigger | definer | |
lock_groups | — | void | P2-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_line | line text | text | FU-L3-CUSTOMER-DETAIL. Staff display mask of a street line; single place to change once O-05 is decided (GAP-2120). | |
mask_phone | phone text | text | P2-04. Staff display mask of an E.164 phone (Admin SPEC format; GAP-06 open). | |
name_key | value text | text | ||
open_order_count | p_account uuid | integer | definer | FU-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_ref | p_account uuid | text | definer | P2-05. PiPoint link reference of a customer for the server-side balance read; null unless a customer reader. |
province_key | p_value text | text | U6-P7-61 NEW-KH-13. Comparison key of a province text: case, diacritics, punctuation and a leading Thanh pho/TP/Tinh folded away. | |
purchase_history | p_account uuid, p_limit integer, p_offset integer | TABLE(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) | definer | P2-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) | definer | P2-05. Completed-only aggregates per buyer (count, units, last purchase, final-price spend) for customer readers; empty otherwise. |
purchase_summary_for | p_accounts uuid[] | TABLE(account_id uuid, completed_order_count integer, products_purchased bigint, last_purchase_at timestamptz, total_spend_vnd bigint, spend_complete boolean) | definer | FU-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_accounts | p_keyword text | SETOF uuid | definer | U6-P2-23 KH-US-01 AC04. Customers whose code, name or phone contains the keyword; customer readers only. |
search_hit | p_code text, p_full_name text, p_phone_e164 text, p_keyword text | boolean | U6-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 | — | trigger | definer | PPI-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_status | p_account uuid, p_status text | text | definer | P2-04. KH-US-03 lock/unlock of the APP_USER membership for customer managers; account lock wins. |
tags_valid | tags text[] | boolean | ||
tier_heads | p_accounts uuid[], p_at timestamp with time zone | TABLE(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_of | p_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) | definer | U6-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) | definer | U6-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_can | p_action text | boolean | P4-02. Acting principal may read/write/pause/assign Missions (matrix MS-01..MS-04) right now. | |
actor_has_role | p_roles text[] | boolean | ||
add_contributions | p_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 uuid | integer | definer | P4-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_progress | p_assignments uuid[], p_at timestamp with time zone | SETOF mission.progress_row | P4-06. Internal derivation of state + criterion figures from the evidence at p_at (a test may pass a past/future instant). | |
contribute_affiliate_order | p_order_id uuid, p_order_version integer, p_event_id uuid, p_event_type text, p_correlation_id text | TABLE(outcome text, contributed integer, reversed integer) | definer | P4-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_order | p_order uuid, p_event_id uuid, p_correlation_id text | integer | definer | U19-R20 (GAP-W-VD-06). DELIVERED_ORDER_COUNT / VALUE once for a completed Recurring order, source ORDER. |
contribute_delivered_shipment | p_shipment_id uuid, p_shipment_version integer, p_event_id uuid, p_event_type text, p_correlation_id text | TABLE(outcome text, contributed integer, excluded integer) | definer | U19-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_milestone | p_referral_id uuid, p_milestone text, p_referrer uuid, p_referee uuid, p_event_id uuid, p_event_type text, p_correlation_id text | TABLE(outcome text, metric text, contributed integer) | definer | P4-04. pi_worker only: one unit per referred person on the referrer's Referral metric, from the P4-11 row. |
counted_contributions | p_assignment uuid | SETOF mission_contributions | ||
criterion_progress | p_assignment uuid | TABLE(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_ref | p_ref text | text | ||
metric_source | p_metric text | TABLE(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_impact | p_version_id uuid | TABLE(assigned_count bigint, completed_count bigint, in_progress_count bigint, with_progress_count bigint, contribution_count bigint, reversal_count bigint, as_of timestamptz) | definer | P4-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 | — | trigger | definer | |
progress_after_version_change | — | trigger | definer | |
progress_evidence | p_assignment uuid, p_criterion uuid, p_limit integer, p_offset integer | TABLE(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_list | p_account uuid, p_purpose text, p_limit integer, p_offset integer | SETOF mission.progress_row | definer | |
progress_reader_roles | — | text[] | P4-06 mirror of matrix MPR-02 mission_progress.read (WEB_ADMIN, PROPOSED, GAP-174). | |
progress_scope | — | text | definer | |
progress_scope_ids | p_account uuid, p_purpose text | TABLE(assignment_id uuid, assigned_at timestamptz) | definer | |
progress_snapshot_drift | — | TABLE(assignment_id uuid, criterion_id uuid, reason text) | ||
progress_total | p_account uuid, p_purpose text | bigint | definer | |
progress_visible | p_assignment uuid | boolean | definer | |
reader_roles | — | text[] | P4-02 mirror of matrix MS-01 mission.read (PROPOSED, GAP-45). | |
rebuild_progress | p_assignment uuid | integer | definer | P4-06. Operator/owner rebuild of the snapshot cache from the evidence (one assignment, or all). No role is granted it. |
refresh_progress | p_assignment uuid | void | definer | P4-06. Internal: re-derive the snapshot and the set-once completed_at of one assignment from mission_contributions. |
refund_fence_contribution | — | trigger | definer | |
reverse_affiliate_order | p_order_id uuid, p_occurred_at timestamp with time zone, p_event_id uuid, p_event_type text, p_correlation_id text | integer | definer | |
reverse_order_contributions | p_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 uuid | TABLE(reversed integer, recorded integer) | definer | |
reverse_order_refund | p_order uuid, p_event_id uuid, p_event_type text, p_correlation_id text, p_only uuid | TABLE(outcome text, reversed integer, recorded integer) | definer | |
reverse_refunded_order | p_aggregate_type text, p_aggregate_id uuid, p_event_id uuid, p_event_type text, p_correlation_id text | TABLE(outcome text, reversed integer, recorded integer) | definer | P4-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_cycle | p_cycle text | boolean | definer | U19-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_can_hold | — | boolean | ||
actor_can_review | — | boolean | ||
actor_has_staff_role | p_roles text[] | boolean | definer | |
actor_is_subject | p_apps text[] | boolean | definer | |
assert_owner_bypasses_rls | — | void | ||
close_account | p_account uuid, p_reason text, p_release_pipoint boolean | jsonb | definer | PPI-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 | — | trigger | definer | PPI-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_export | p_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 jsonb | TABLE(outcome text, export_id uuid, expires_at timestamptz, version integer) | definer | P1-14. privacy.export job: records the package (expiry from PRIVACY_EXPORT_PACKAGE) and completes. |
consent_purpose_guard_status | — | trigger | ||
delete_own_account | p_request_id text, p_correlation text | TABLE(id uuid, status text, version integer, created_at timestamptz, job_slot text) | definer | PPI-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_pii | p_account uuid, p_actor uuid | integer | definer | U6-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_subject | p_request_id uuid, p_run_id uuid | TABLE(outcome text, request_status text, version integer, purged_paths text[]) | definer | P1-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 | — | uuid | definer | U6-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_source | p_request_id uuid | TABLE(outcome text, account_id uuid, request_version integer, package jsonb) | definer | P1-14. privacy.export job: the APPROVED EXPORT subject's own data (masked), or why not. |
hold_record_event | — | trigger | ||
hold_roles | — | text[] | ||
mask_email | p text | text | PPI-P3-07. n***@domain (audit/mask.ts maskMailAddress shape); **** when there is no local part; null stays null. | |
mask_phone | p text | text | ||
purge_expired_exports | p_run_id uuid | TABLE(outcome text, purged integer, held integer, purged_paths text[]) | definer | P1-14. privacy.export_purge job: expired packages purged under an APPROVED policy; held subjects kept. |
purge_job_name | — | text | ||
record_consent | p_purpose text, p_action text, p_purpose_version integer, p_expected_seq integer, p_request_id text, p_correlation text | TABLE(record_id uuid, seq integer, action text, purpose_version integer, changed boolean) | definer | P1-14. grantConsent/withdrawConsent: appends one consent_records row for the acting subject. |
release_hold | p_id uuid, p_expected_version integer, p_reason text | TABLE(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_request | p_id uuid, p_expected_version integer, p_decision text, p_reason text, p_request_id text | TABLE(id uuid, status text, version integer, job_slot text) | definer | |
reviewer_roles | — | text[] | ||
set_hold | p_scope_kind text, p_account_id uuid, p_order_id uuid, p_reason text, p_request_id text, p_correlation text | TABLE(id uuid, account_id uuid, status text, version integer, set_at timestamptz) | definer | |
subject_on_hold | p_account_id uuid | boolean | definer | |
submit_request | p_kind text, p_request_id text, p_correlation text | TABLE(id uuid, status text, version integer, created_at timestamptz) | definer | P1-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
access | p_kind text | text | definer | |
assert_in | p_name text, p_value text, p_allowed text[] | void | ||
assert_window | p_from timestamp with time zone, p_to timestamp with time zone | void | ||
campaign_cohort | p_cohort text, p_from timestamp with time zone, p_to timestamp with time zone, p_type text | TABLE(campaign_type text, campaigns bigint, confirmed bigint, failed bigint, rate_numerator bigint, rate_denominator bigint, success_rate numeric) | definer | P4-20. Closed (outcome recorded) vs open campaigns; rate = numerator / denominator, NULL not 0. |
campaign_funnel | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_type text | TABLE(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) | definer | P4-20. Orders per campaign by milestone reached for ONE explicit date basis; SQL totals row; READ scope. |
cod | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_value_basis text | TABLE(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) | definer | P4-20. COD cohort by ONE explicit stage date: delivered / collected / remitted apart plus the two gaps; MONEY scope. |
cod_status | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_value_basis text | SETOF report.source_row | definer | |
cohort_status | p_cohort text, p_from timestamp with time zone, p_to timestamp with time zone, p_type text | SETOF report.source_row | definer | |
ended_days | p_from timestamp with time zone, p_to timestamp with time zone | SETOF date | ||
figure | p_value numeric, p_complete boolean | numeric | P4-20. Zero becomes NULL while a feeding source is INCOMPLETE. | |
funnel_status | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_type text | SETOF report.source_row | definer | |
order_cohort | p_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_type text | TABLE(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_status | p_campaign uuid, p_to timestamp with time zone | SETOF report.source_row | ||
orders | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_type text, p_value_basis text | TABLE(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) | definer | P4-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_status | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_campaign uuid, p_type text, p_value_basis text | SETOF report.source_row | definer | |
payment_at | p_basis text, p_provider_at timestamp with time zone, p_recorded_at timestamp with time zone | timestamptz | P4-20. PROVIDER_TIME | RECORDED bucket instant. | |
payments | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_mode text, p_value_basis text | TABLE(day_vn date, provider_mode text, kind text, status text, transactions bigint, amount_vnd bigint, is_total boolean) | definer | P4-20. Provider transactions per VN day x kind x status (captured / refunded / FAILED / UNKNOWN apart); MONEY scope. |
payments_status | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_mode text, p_value_basis text | SETOF report.source_row | definer | |
point_at | p_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 zone | timestamptz | ||
points | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone | TABLE(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) | definer | P4-20. ACCEPTED point requests per operation / bucket at their OWN rate snapshot; totals per operation; VND needs MONEY. |
points_status | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone | SETOF report.source_row | definer | |
policy_undecided | p_report text, p_value_basis text | TABLE(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. | |
require | p_kind text | text | definer | P4-20. Scope of the live grant for READ | MONEY | SALE, else 42501. |
sale_attribution_pending | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone | bigint | ||
sale_gate | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_team uuid | text | definer | |
sale_performance | p_group text, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_team uuid, p_value_basis text | TABLE(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) | definer | P4-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_scan | p_scope text, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_team uuid | TABLE(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_status | p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone, p_team uuid, p_value_basis text | SETOF report.source_row | definer | |
vn_day | p_at timestamp with time zone | date | ||
vn_days | p_from timestamp with time zone, p_to timestamp with time zone | SETOF date |
schema attribution
Chưa có COMMENT ON SCHEMA
| Hàm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_can_disable | — | boolean | definer | |
actor_is_link_owner | — | boolean | definer | P4-11. Matrix S-03/S-04/ATR-01..03 mirror: ACTIVE account + ACTIVE membership + base role in the claimed app. |
actor_is_referral_claimant | — | boolean | definer | |
assign_order | p_order_id uuid, p_event_id uuid, p_event_type text, p_correlation_id text | TABLE(assignment_id uuid, outcome text, policy_version_id uuid, created boolean) | definer | P4-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_touches | p_buyer uuid, p_at timestamp with time zone | SETOF attribution_touches | definer | |
claim_affiliate_touches | p_visitor_key text, p_correlation_id text | TABLE(outcome text, bound_count integer) | definer | FU-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_signup | p_visitor_key text, p_correlation_id text | TABLE(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 | P4-12. The caller binds itself to its sign-up Last-Touch Referral (once; ATR-06); identity_mismatch refused. |
create_affiliate_link | p_campaign_id uuid, p_campaign_product_id uuid, p_correlation_id text | TABLE(link_id uuid, created boolean) | definer | |
create_referral_link | p_correlation_id text | TABLE(link_id uuid, created boolean) | definer | |
disable_affiliate_link | p_id uuid, p_expected_version integer, p_reason text | TABLE(link_id uuid, version integer) | definer | |
first_paid_fact | p_account uuid | TABLE(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_active | p_owner uuid, p_app text | boolean | definer | |
masked_buyer | p_assignment uuid | text | definer | |
masked_referred | p_milestone uuid | text | definer | |
milestone_fact | p_id uuid, p_milestone text, p_outcome text | TABLE(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_link | p_kind text, p_code text, p_visitor_key text, p_request_id text, p_correlation_id text | TABLE(outcome text, target_kind text, campaign_id uuid, campaign_product_id uuid, touch_id uuid) | definer | P4-12. Public link open (ATR-05): safe in-app target kind only, no owner data; records a touch when OPENED. |
owner_role | p_app text | text | ||
policy_at | p_at timestamp with time zone | attribution_policy_versions | ||
preview_referrer | — | TABLE(code text, masked_name text) | definer | G2I-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_companion | p_code text | TABLE(display_name text, rank_name text, successful_orders bigint, phone text, zalo_phone text, referral_code text, avatar_path text) | definer | G1S-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_order | p_order_id uuid | TABLE(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) | definer | P4-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_verified | p_account uuid, p_identity_ref text, p_occurred_at timestamp with time zone, p_source_type text, p_source_id text, p_correlation_id text | TABLE(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 | P4-12. EKYC_VERIFIED once per referred person; one hashed eKYC identity per referred account; pi_worker only. |
record_first_paid | p_order uuid, p_correlation_id text | TABLE(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 | P4-12. FIRST_PAID from PIDEAL state (earliest SETTLED REMAINING of the order owner); pi_worker only. |
record_referral_milestone | p_account uuid, p_milestone text, p_occurred_at timestamp with time zone, p_source_type text, p_source_id text, p_correlation_id text | TABLE(milestone_id uuid, outcome text) | definer | |
record_referral_signup | p_account uuid, p_visitor_key text, p_source_type text, p_source_id text, p_correlation_id text | TABLE(milestone_id uuid, outcome text) | definer | |
record_touch | p_kind text, p_code text, p_visitor_key text, p_request_id text, p_correlation_id text | TABLE(touch_id uuid, touched_at timestamptz, recorded boolean) | definer | P4-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_can | p_action text | boolean | ||
actor_has_role | p_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_redeem | p_corrects uuid, p_recon uuid | uuid | ||
compensation_conflicts | — | TABLE(redeem_request_id uuid, redeemed_points integer, returned_points bigint, reversal_points bigint, adjust_points bigint) | definer | FU-1822. Detection of a double compensation (reversals + live CREDIT adjustments > redeemed). Owner only. |
counted_reversals | p_redeem uuid | TABLE(points bigint, unresolved boolean) | ||
decide | p_id uuid, p_expected_version integer, p_decision text, p_payload_hash bytea, p_note text, p_correlation_id correlation_ref | SETOF point_adjustments | definer | P3-21. Checker approves or rejects a PENDING proposal: never the maker, version and payload hash bound. |
decide_rank_debit | p_id uuid, p_expected_version integer, p_decision text, p_payload_hash bytea, p_note text, p_correlation_id correlation_ref | SETOF rank_adjustments | definer | PPI-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_states | p_ids uuid[] | TABLE(adjustment_id uuid, status text, result_code text, provider_recorded_at timestamptz, result_available integer) | definer | |
dispatch_input | p_id uuid | TABLE(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) | definer | P3-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 | — | text | P3-21. Job name of the ADJUST dispatch run (slot adjust:<point_adjustments.id>). | |
history_wallet_ref | p_account uuid | text | definer | PPI-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_request | p_operation text, p_source text, p_request_id text, p_account uuid, p_points integer, p_direction text, p_maker uuid, p_checker uuid | boolean | definer | |
live_credit_points | p_redeem uuid, p_exclude uuid | bigint | ||
maker_roles | — | text[] | P3-21 + PPI-P5-07 mirror of matrix F-06 point_adjust.request: operations (GAP-PPI-06b = a). | |
payload_hash | p_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 uuid | bytea | ||
propose | p_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_ref | SETOF point_adjustments | definer | |
propose_rank_debit | p_source uuid, p_reason_text text, p_correlation_id correlation_ref | SETOF rank_adjustments | definer | PPI-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_hash | p_account uuid, p_points integer, p_reason_code text, p_reason_text text, p_evidence uuid[], p_source uuid, p_maker uuid | bytea | ||
reader_roles | — | text[] | P3-21 + PPI-P5-07 mirror of matrix ADJ-01 point_adjust.read: operations + finance (maker and checker). | |
recall_failed_delivery | p_order uuid, p_failed uuid, p_component text, p_correlation text | integer | definer | #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_rate | p_order uuid | TABLE(rate_vnd numeric, policy_version text) | definer | PPI-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_return | p_order uuid, p_cycle_no integer, p_correlation_id correlation_ref | integer | definer | PPI-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. |
recipients | p_ids uuid[] | TABLE(account_id uuid, full_name text, phone_masked text) | definer | PPI-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. |
refuse | p_code text, p_reason text, p_detail text | void | ||
request_discrepancies | p_id uuid | TABLE(id uuid, run_id uuid, run_date date, discrepancy_type text, status text, compensates boolean, created_at timestamptz, resolved_at timestamp with time zone) | definer | PPI-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_rows | p_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 integer | TABLE(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) | definer | PPI-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_conflict | p_redeem uuid, p_points integer, p_exclude uuid | text |
schema cms
Chưa có COMMENT ON SCHEMA
| Hàm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_can | p_action text | boolean | P4-17. Acting principal may read/manage/publish CMS content (matrix MK-01/MK-02) right now. | |
actor_has_role | p_roles text[] | boolean | ||
article_image_mimes | — | text[] | ||
articles_visible_at | p_at timestamp with time zone | TABLE(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_at | p_app text, p_placement text, p_at timestamp with time zone | TABLE(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_content | p_body jsonb | boolean | ||
body_types_allowed | — | text[] | ||
is_slug | p_value text | boolean | ||
keyword_usage | p_keyword uuid | bigint | definer | |
keyword_usage_count | p_keyword uuid | bigint | definer | |
lock_category_tree | — | void | ||
manager_roles | — | text[] | P4-17 mirror of matrix MK-01 cms.manage (DEFINED). | |
media_attachable | p_media uuid, p_mimes text[] | boolean | definer | P4-17. True when the media is READY, undeleted, public CMS_MEDIA of an allowed MIME type. |
pages_visible_at | p_at timestamp with time zone | TABLE(id uuid, slug text, locale text, version_id uuid, version integer, title text, publish_at timestamptz) | definer | |
public_article | p_slug text | TABLE(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 | P4-17. One published, in-schedule article by slug with sanitized body_html. For P4-18; matrix A-04. |
public_article_doc | p_slug text, p_locale text | TABLE(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) | definer | P4-18 + FU-CMS. One published, in-schedule article (published version only) with its sanitized body_json and SEO. |
public_article_list | p_locale text, p_limit integer, p_offset integer | TABLE(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_total | p_locale text | bigint | definer | |
public_articles | p_limit integer, p_offset integer | TABLE(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) | definer | P4-17. Published, in-schedule articles (list, no body). For P4-18 publicContent; matrix A-04. |
public_banner_feed | p_placement text | TABLE(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) | definer | P4-18 + FU-CMS. Published in-window banners of the request app with target availability (article, page, screen, campaign). |
public_banners | p_app text, p_placement text | TABLE(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 | P4-17. Published banners of one app/placement inside [starts_at, ends_at) now. For P4-18; matrix A-04. |
public_media | p_ids uuid[] | TABLE(id uuid, storage_path text) | definer | P4-18. Public READY CMS image media only; returns the object path inside the public bucket. |
public_page_doc | p_slug text, p_locale text | TABLE(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) | definer | FU-CMS. One published, in-schedule content page (published version only) with its stored sanitized body_json. |
public_reader | — | boolean | P4-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_can | p_action text | boolean | P3-07. Acting principal may read/write/submit/approve Finance policy versions (matrix FPL-01..04) right now. | |
actor_has_role | p_roles text[] | boolean | ||
applicable_version | p_kind text, p_at timestamp with time zone | SETOF finance_policy_versions | ||
approve | p_version_id uuid, p_expected_version integer, p_correlation_id correlation_ref | SETOF finance_policy_versions | definer | P3-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_problem | p_kind text, p_body jsonb | text | P3-07. NULL when the body is a well-formed rule set of the kind (shape only, no value), else a problem code. | |
body_roles | p_body jsonb | text[] | ||
checker_roles | — | text[] | P3-07 mirror of matrix FPL-04 finance_policy.approve: GAP-71, empty. | |
decide | p_kind text, p_at timestamp with time zone, p_pinned uuid, p_input jsonb | jsonb | ||
evaluate_funds_voucher | p_fund_code text, p_voucher_kind text, p_at timestamp with time zone, p_pinned_version_id uuid | jsonb | definer | |
evaluate_reconciliation_tolerance | p_provider_vnd bigint, p_local_vnd bigint, p_at timestamp with time zone, p_pinned_version_id uuid | jsonb | definer | |
evaluate_refund_threshold | p_amount_vnd bigint, p_at timestamp with time zone, p_pinned_version_id uuid | jsonb | definer | |
guard_body_roles | — | trigger | ||
guard_version_update | — | trigger | ||
is_vnd | p jsonb | boolean | ||
keys_are | p 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_approved | p_kind text, p_from timestamp with time zone, p_to timestamp with time zone, p_self uuid | boolean | ||
payload_hash | v finance_policy_versions | bytea | ||
reader_roles | — | text[] | P3-07 mirror of matrix FPL-01 finance_policy.read: GAP-71, empty. | |
refuse | p_code text, p_reason text, p_detail text | void | ||
role_list_ok | p jsonb | boolean | ||
save_draft | p_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_ref | SETOF finance_policy_versions | definer | |
submit | p_version_id uuid, p_expected_version integer, p_correlation_id correlation_ref | SETOF finance_policy_versions | definer |
schema notification
Chưa có COMMENT ON SCHEMA
| Hàm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
announce_deal_tier | p_campaign_product uuid, p_source_event_id uuid, p_source_event_type text, p_correlation_id text | integer | definer | G1S-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 | — | trigger | definer | PPI-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 | — | trigger | definer | G1S-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 | — | timestamptz | U19-P2-16. When the in-app feed started (the migration time): events recorded before it are never announced. | |
g1s_feed_since | — | timestamptz | G1S-P1-11. When the G1S notices started (the migration time): G1S event types recorded before it are never announced. | |
g1s_pay_now_awaits_credit | p_order_id uuid | boolean | definer | PPI-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_points | p_order_id uuid | integer | definer | G1S-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_keys | p_order_id uuid | jsonb | G2S-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 | — | timestamptz | G2S-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_points | p_order_id uuid, p_credited boolean | integer | G2S-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_recipient | p_account uuid | boolean | ||
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_forfeit | p_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id text | TABLE(outcome text, reason text, in_app_event_id uuid) | definer | FU-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_event | p_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id text | TABLE(outcome text, reason text, in_app_event_id uuid) | definer | G1S-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_outcome | p_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id text | TABLE(outcome text, reason text, in_app_event_id uuid) | definer | P4-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_event | p_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id text | TABLE(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_completed | p_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id text | TABLE(outcome text, reason text, in_app_event_id uuid) | definer | U19-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_update | p_event_id uuid, p_event_type text, p_aggregate_type text, p_aggregate_id text, p_aggregate_version integer, p_correlation_id text | TABLE(outcome text, reason text, in_app_event_id uuid) | definer | U19-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_left | s spin_sessions, p_now timestamp with time zone | integer | VQM-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_reminders | p_now timestamp with time zone, p_correlation_id text | TABLE(kind text, written integer) | definer | G1S-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_event | p_id uuid | TABLE(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) | definer | FU-455 (NTF-03). One ledger entry with its in-app row (masked recipient); no row for an unknown id. |
staff_events | p_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 integer | TABLE(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) | definer | FU-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 | — | void | definer | |
write_order_notice | p_kind text, p_order uuid, p_payload jsonb, p_source_event_id uuid, p_source_event_type text, p_correlation_id text | uuid | definer | G1S-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
affiliate_rate_at | p_role text, p_at timestamp with time zone | TABLE(rate_bp integer, policy_version text) | definer | L9 / 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_facts | p_order_id uuid | TABLE(deposit_cash_vnd bigint, points_redeemed_vnd bigint, remaining_paid_vnd bigint, remaining_due_vnd bigint) | definer | FU-715. Cash facts of an order for the reward base (settled DEPOSIT, ONLINE REMAINING, close remaining); pi_worker only. |
campaign_reward_facts | p_order_id uuid | TABLE(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) | definer | U19-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_plan | p_order uuid, p_correlation text | integer | definer | U19-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_vnd | p_order_id uuid | TABLE(remaining_vnd bigint) | definer | FU-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 | — | text | P3-20. Job name of the reward dispatch run (slot reward:<point_reward_actions.id>). | |
failed_delivery_cut | p_order uuid, p_failed uuid, p_correlation text | integer | definer | #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_value | p_order uuid, p_failed uuid | TABLE(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_request | p_operation text, p_source text, p_order uuid | boolean | ||
log_release | — | trigger | definer | U19-P2-20. One PIPOINT pipoint.release activity row when a RELEASE is accepted (pending -> available). |
log_returned_cancel | — | trigger | definer | U19-P2-18. One PIPOINT pipoint.cancel activity row when the CANCEL_ISSUE of a returned order is accepted. |
order_reward_points | p_order uuid | jsonb | definer | U28-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_subject | p_order_id uuid | TABLE(owner_account_id uuid, campaign_type text, state text) | definer | P3-20. Reward recipient (order owner), campaign type and state of one order; pi_worker only. |
partial_cancel_bind | p_id uuid, p_date date | jsonb | definer | |
partial_cancel_plan | p_case uuid, p_correlation text | integer | definer | FU-SHORTAGE2. One QUEUED partial-cancel row per PARTIAL_UNITS row of a recorded case (idempotent); pi_worker only. |
partial_cancel_settle | p_id uuid, p_status text, p_provider_ref text, p_reason text | void | definer | |
partial_state | p_order uuid, p_component text | TABLE(points bigint, in_flight boolean, queued boolean) | definer | FU-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_at | p_at timestamp with time zone | TABLE(rate_vnd numeric, policy_version text) | definer | P3-20. AS-03 rate snapshot: APPROVED POINT_RATE in force at the instant; no row when none; pi_worker only. |
record_first_paid_cycle | p_order_id uuid, p_cycle_no integer, p_paid_at timestamp with time zone, p_source text, p_event_id uuid | TABLE(is_first boolean, cycle_no integer, paid_at timestamptz) | definer | FU-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_vnd | p_order uuid | bigint | U28-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_points | p_order uuid, p_component text | bigint | definer | #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_unit | p_order_id uuid, p_cycle_no integer | boolean | definer | U19-P2-18. True when the order (cycle null) or its cycle is in order status RETURNED; pi_worker only. |
tier_multiplier_at | p_account_id uuid, p_audience text, p_activity text, p_at timestamp with time zone | TABLE(multiplier numeric, tier_version_id uuid, benefit_policy_ref text) | definer | U28-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_can_read | — | boolean | definer | |
actor_grants | — | TABLE(permission text, scope text) | definer | P1-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_holds | p_permission text | boolean | definer | |
actor_holds_role | p_role_id uuid | boolean | definer | |
approve_change | p_id uuid, p_expected_version integer | SETOF role_change_requests | definer | |
bootstrap_first_admins | p_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 text | TABLE(run_id uuid, outcome text, super_admin_account_id uuid, admin_account_id uuid) | definer | P1-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_admin | p_phone text, p_mfa_reset boolean, p_password_hash text, p_operator text, p_reason text | TABLE(run_id uuid, account_id uuid, factors_removed integer, sessions_revoked integer, credential_expires_at timestamptz) | definer | PPI-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 | — | trigger | definer | |
change_payload_hash | p_kind text, p_app text, p_role_id uuid, p_role_version integer, p_account_id uuid, p_assignment_id uuid, p_grants jsonb | text | ||
change_requests | p_status text, p_id uuid | TABLE(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_role | p_code text, p_name text, p_description text | TABLE(id uuid, version integer) | definer | |
grants_at | p_role_id uuid, p_version integer | jsonb | definer | |
guard_change_request | — | trigger | ||
guard_grant | — | trigger | ||
is_last_super_admin | p_assignment_id uuid | boolean | definer | |
normalize_grants | p_app text, p_grants jsonb | jsonb | definer | |
permission_catalog | — | TABLE(id uuid, code text, description text, risk_level text, allowed_scopes text[], deprecated_at timestamptz) | definer | |
request_change | p_kind text, p_role_id uuid, p_account_id uuid, p_grants jsonb, p_expected_version integer, p_reason text, p_correlation_id text | SETOF role_change_requests | definer | |
require | p_permission text | void | definer | |
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_history | p_role_id uuid | TABLE(version integer, name text, description text, changed_by uuid, change_request_id uuid, recorded_at timestamptz, grants jsonb) | definer | |
update_role | p_role_id uuid, p_expected_version integer, p_name text, p_description text | TABLE(version integer) | definer |
schema report_export
P4-21. Report export jobs (definer functions); see schema-ownership s5bu.
| Hàm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_can | p_what text | boolean | definer | P4-21. RLS gate: the live report.export / report_money.export grant. |
assert_filters | p_code text, f jsonb, p_from timestamp with time zone, p_to timestamp with time zone | void | ||
audit | j report_export_jobs, p_action text, p_result text, p_reason text, p_metadata jsonb | void | ||
claim | p_job uuid, p_attempt integer, p_run uuid | TABLE(o_outcome text) | definer | P4-21. QUEUED -> PROCESSING for the enqueued attempt. |
complete | p_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 jsonb | TABLE(o_outcome text, o_expires_at timestamptz) | definer | P4-21. DONE (file recorded, expiry from the job ttl) or NO_DATA, plus the audit row, one transaction. |
download_ref | p_id uuid | TABLE(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) | definer | P4-21. Own DONE file reference after re-deciding the permission. |
enqueue | — | trigger | definer | |
fail | p_job uuid, p_attempt integer, p_run uuid, p_code text | TABLE(o_outcome text) | definer | P4-21. PROCESSING -> FAILED with a stable code, audited. |
filters_ok | p jsonb | boolean | ||
guard_transition | — | trigger | ||
kind | p_code text | text | ||
my_access | — | TABLE(can_read boolean, can_read_money boolean, can_export boolean, can_export_money boolean) | definer | |
permit | p_code text | boolean | definer | P4-21. Live read + export grant of the acting principal for a report, else 42501. |
purge_expired | — | TABLE(o_path text) | definer | P4-21. Expired DONE files -> EXPIRED; paths returned for removal. |
refuse | p_code text, p_reason text, p_detail text | void | ||
request | p_code text, p_filters jsonb, p_from timestamp with time zone, p_to timestamp with time zone, p_money boolean, p_correlation correlation_ref | TABLE(o_outcome text, o_id uuid) | definer | P4-21. Queues an export job (one active per requester and filter set); POLICY_UNDECIDED without a file lifetime. |
retry | p_id uuid, p_expected_version integer | TABLE(o_id uuid, o_version integer) | definer | P4-21. FAILED job of the caller back to QUEUED (same snapshot parameters). |
snapshot | p_job uuid, p_max_rows integer | jsonb | definer | P4-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_is_reviewer | — | boolean | FU-718. Acting principal may read and decide PROFILE_CHANGE requests now. | |
actor_is_sale | — | boolean | FU-718. Matrix U-07 mirror for the Sale profile functions. | |
cas | p_account uuid, p_expected integer, p_create boolean | void | ||
change | p_id uuid | SETOF sale_profile.change_row | definer | FU-718. One request for a reviewer (SPC-01), masked, never the reviewer's own. |
change_view | c sale_profile_changes, p_total bigint | sale_profile.change_row | ||
changes_guard | — | trigger | ||
decide_change | p_id uuid, p_expected integer, p_decision text, p_reason text | TABLE(change_id uuid, sale_account_id uuid, new_state text, new_version integer) | definer | FU-718. Reviewer decision (SPC-02): approval applies the new values atomically; reject keeps the reason. |
mask_tail | p_value text | text | FU-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) | definer | FU-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_changes | p_limit integer, p_offset integer | SETOF sale_profile.change_row | definer | FU-718. The acting Sale's own PROFILE_CHANGE requests, masked. |
queue | p_state text, p_limit integer, p_offset integer | SETOF sale_profile.change_row | definer | FU-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_contact | p_expected integer, p_email text, p_address text | integer | definer | FU-718. DIRECT edit of contact email/address (SPEC-06). |
set_avatar | p_expected integer, p_media uuid | integer | definer | FU-718. DIRECT edit of the avatar: own READY AVATAR media (GAP-873). |
submit_change | p_expected integer, p_full_name text, p_id_number text, p_bank_account text | uuid | definer | FU-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
accepted_at | p_request uuid, p_requested_at timestamp with time zone | timestamptz | ||
actor_can | p_action text | boolean | ||
build_draft | p_month date, p_cutoff timestamp with time zone, p_correlation correlation_ref | TABLE(o_id uuid, o_version integer, o_outcome text) | definer | P3-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_of | p_operation text, p_business_date date, p_recorded_at timestamp with time zone, p_requested_at timestamp with time zone | date | ||
open_discrepancies | p_month date | integer | ||
open_months | p_cutoff timestamp with time zone | TABLE(o_month date) | definer | |
rate_basis | — | text | ||
reader_roles | — | text[] | P3-23 mirror of matrix PRP-01 point_report.read. | |
refuse | p_code text, p_reason text, p_detail text | void | ||
selection | p_month date, p_cutoff timestamp with time zone | TABLE(id uuid, request_id text, operation text, adjust_direction text, target_bucket text, points integer, rate_snapshot_vnd numeric) | ||
selection_hash | p_month date, p_cutoff timestamp with time zone, p_open integer | bytea | ||
settle | p_id uuid, p_expected_version integer, p_note text, p_correlation correlation_ref | SETOF point_report_versions | definer | P3-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_corrections | p_now timestamp with time zone, p_correlation correlation_ref | TABLE(o_request_id uuid, o_report_id uuid, o_month date) | definer | P3-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_in_roles | p_roles text[] | boolean | ||
cancel_refund_figures | p_order uuid, p_cancel integer[] | jsonb | definer | U19-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_shares | p_unit_price bigint, p_deposit_bp integer, p_deposit bigint, p_points integer, p_qty integer, p_cancelled integer | TABLE(cash_vnd bigint, points integer) | FU-575. Cumulative deposit (kept part rounded up) and points (rounded down) refunded after N cancelled units. | |
cumulative_value_shares | p_deposit_bp integer, p_deposit bigint, p_points integer, p_v0 bigint, p_cancelled_value bigint | TABLE(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. | |
impact | p_campaign_product uuid, p_cycle_no integer, p_orders uuid[], p_limit integer | jsonb | definer | P2-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_order | p_order uuid, p_note text, p_source text | jsonb | definer | U19-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_gate | p_order uuid, p_apply boolean | jsonb | definer | U13-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_units | p_order uuid, p_campaign_product uuid, p_cycle_no integer | jsonb | definer | FU-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 | — | text | FU-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_case | p_case_type text, p_campaign_product uuid, p_cycle_no integer, p_reason text, p_evidence uuid[], p_items jsonb, p_source_event_id text | jsonb | definer | P2-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
customer_uid | p_account uuid | TABLE(customer boolean, uid text) | definer | PPI-P9-01 customerIdentity. customer = a CUSTOMER account; uid = its live pipoint link (null: not linked). ekyc.read, else PT403. |
redeem_snapshot | p_uid text | TABLE(ekyc_status text, via text) | definer | PPI-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_sync | p_uid text, p_correlation_id correlation_ref | text | definer | PPI-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_sync | p_account_id uuid, p_uid text, p_claim_ekyc text, p_claim_via text, p_correlation_id correlation_ref | text | definer | PPI-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_people | p_uids text[] | TABLE(uid text, account_id uuid, own boolean) | definer | PPI-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 | — | text | definer | PPI-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_ack | p_slot_key text | jsonb | definer | PPI-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_apply | p_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 zone | jsonb | definer | PPI-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_begin | p_slot_key text | jsonb | definer | PPI-P4-01. eKYC receipt of the slot: NO_RECEIPT | ALREADY_PROCESSED | NO_ACCOUNT (no live pipoint link: acked) | OPEN + uid (pull status once). |
sync_fail | p_slot_key text, p_code text | jsonb | definer | PPI-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
app_memberships_deleted_account_guard | — | trigger | definer | |
end_pipoint_wallet_link | — | trigger | definer | PPI-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_accounts | p_account uuid | uuid[] | definer | PPI-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_unlink | p_account uuid, p_uid text, p_operator text, p_reason text, p_correlation_id correlation_ref | jsonb | PPI-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_person | p_a uuid, p_b uuid | boolean | definer | PPI-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_accounts | p_membership_status text, p_awaiting_role boolean, p_limit integer, p_offset integer | TABLE(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) | definer | PPI-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_provision | p_account uuid, p_phone text, p_full_name text, p_role_code text, p_note text, p_correlation_id text | TABLE(account_id uuid, membership_version integer, role_change_request_id uuid) | definer | PPI-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_reject | p_account uuid, p_expected_version integer, p_reason text | TABLE(membership_version integer, rejected_requests integer, sessions_revoked integer) | definer | PPI-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_holds_team | p_permission text | boolean | definer | P1-13. The acting WEB_ADMIN principal holds a live grant of the permission at scope TEAM. |
actor_in_team | p_team uuid | boolean | definer | P1-13. TEAM-scope RLS predicate: team in actor_team_ids(). |
actor_team_ids | — | uuid[] | definer | P1-13. Principal.teamIds: managed ACTIVE teams (WEB_ADMIN) or own current team (APP_SALE); empty otherwise. |
assignment_version | p_sale uuid | integer | definer | |
current_team | p_sale uuid | uuid | definer | P1-13. Current team of a Sale (CURRENT basis); see team_at. |
may_resolve | p_sale uuid | boolean | definer | |
team_at | p_sale uuid, p_at timestamp with time zone | uuid | definer | P1-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_unchecked | p_sale uuid, p_at timestamp with time zone | uuid | ||
transfer | p_sale uuid, p_to_team uuid, p_expected_version integer, p_reason text, p_correlation_id text | TABLE(history_id uuid, from_team uuid, to_team uuid, version integer, effective_from timestamptz, changed boolean) | definer | P1-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
applicant_document_room | — | boolean | FU-PENDINGUPLOAD. MD-09 plus the cap of 10 not-deleted SUPPORTING_DOCUMENT objects per applicant (GAP-2030). | |
is_applicant_app | — | boolean | P1-12. Matrix S-06/U-10 mirror: claimed APP_SALE membership (any status) or ACTIVE APP_USER with role user. | |
is_pending_applicant | — | boolean | FU-PENDINGUPLOAD. Matrix MD-09..MD-11 mirror: claimed APP_SALE, membership PENDING, account ACTIVE (DEC-S-APPLICATION-UPLOAD). | |
may_review | — | boolean | P1-12. Matrix AD-07/AD-08 mirror: WEB_ADMIN with an effective reviewer role (admin, super_admin since FU-SALEREVIEWER). | |
may_submit | — | boolean | P1-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
evaluate | p_account uuid, p_at timestamp with time zone | TABLE(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). | |
live | p_applications uuid[] | TABLE(application_id uuid, status text, rank_points bigint, fingerprint text, evidence jsonb) | definer | P4-10. Live qualification of PENDING User-to-Sale applications the caller may see (own, or reviewer); others omitted. |
may_read | p_application sale_applications | boolean | ||
mine | — | TABLE(status text, rank_points bigint, fingerprint text, evidence jsonb) | definer | P4-10. The acting User's own live qualification (UA-26 AC01); 42501 for anyone else. |
mission_state | p_account uuid, p_definition uuid, p_at timestamp with time zone | TABLE(status text, assignment_count integer, states jsonb, gaps jsonb) | ||
record | p_application uuid, p_kind text, p_decision text | TABLE(id uuid, status text, rank_points bigint, fingerprint text, evidence jsonb, evaluated_at timestamptz) | definer | P4-10. Stores the database-derived qualification at submission or decision (applicant / deciding reviewer only); an APPROVE snapshot is QUALIFIED or the insert fails. |
records | p_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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
base | p_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 text | TABLE(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) | definer | P4-14. Scoped ATTRIBUTED Sale assignments with both teams and the shared P4-13 qualification (private). |
customers | p_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 | TABLE(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) | definer | P4-14. Scoped attributed customers (buyer x Sale x attribution team), masked, with order counts. |
orders | p_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 text | TABLE(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) | definer | P4-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. |
performance | p_scope text, p_team uuid, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone | TABLE(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) | definer | P4-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_status | p_scope text, p_team uuid, p_date_basis text, p_from timestamp with time zone, p_to timestamp with time zone | TABLE(attribution_pending boolean, payment_pending boolean, qualification_undecided boolean, gross_total_orders bigint, gross_total_value_vnd bigint) | definer | P4-14 + FU-636. Incomplete-source flags (attribution not consumed, deposit not confirmed, base undecided) and the period gross total of the scope. |
scope_ok | p_scope text, p_perm text | boolean | definer | P4-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
live_grant | p_session_id uuid, p_action text | uuid | ||
reset_approve | p_id uuid, p_expected_version integer, p_correlation_id correlation_ref | SETOF mfa_reset_requests | definer | |
reset_get | p_id uuid | SETOF mfa_reset_requests | definer | |
reset_request | p_target uuid, p_reason text, p_ttl_seconds integer, p_correlation_id correlation_ref | SETOF mfa_reset_requests | definer | |
step_up_consume | p_session_id uuid, p_action text | boolean | definer | |
step_up_valid | p_session_id uuid, p_action text | boolean | definer |
schema affiliate_reward
Chưa có COMMENT ON SCHEMA
| Hàm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
backfill_candidates | — | TABLE(order_id uuid, deposit_at timestamptz) | definer | U19-P2-20. Deposited, undelivered, attributed orders without an Affiliate row (backfill of the deposit-time Pending); pi_worker only. |
deliveries | p_shipment_id uuid, p_shipment_version integer | TABLE(outcome text, order_id uuid, cycle_no integer, gross_vnd bigint, basis text, delivered_at timestamptz) | definer | F2 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_delivery | p_order_id uuid | TABLE(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) | definer | F2. 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_order | p_order_id uuid | TABLE(outcome text, recipient_account_id uuid, role text, assignment_id uuid, base_vnd bigint, base_basis text, campaign_type text, order_state text) | definer | P4-13. pi_worker only: Affiliate qualification of one order (shared P4-04 rules) + recipient wallet role. |
my_rewards | p_limit integer, p_offset integer | TABLE(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) | definer | P4-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
account_deleted_apply | p_slot_key text | jsonb | definer | PPI-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_begin | p_slot_key text | jsonb | definer | PPI-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_accounts | p_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 integer | record | definer | PPI-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). |
receive | p_event_id text, p_type text, p_uid text, p_occurred_at timestamp with time zone, p_correlation_id correlation_ref | text | definer | PPI-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
jwt | — | jsonb | ||
role | — | text | ||
uid | — | uuid |
schema profile_access
Chưa có COMMENT ON SCHEMA
| Hàm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
actor_apps | — | text[] | definer | P1-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) | definer | G2I-P3-04. Province / City catalogue for the U-12 address form (profile.manage actors only), by name. |
may_manage | — | boolean | P1-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
get_int | p_key text, p_default integer | integer | definer | U19-P1-03. Integer system parameter; p_default when the key is missing; raises 22023 on a non-integer value. |
get_text | p_key text, p_default text | text | definer | U19-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àm | Tham số | Trả về | Mô tả | |
|---|---|---|---|---|
may_use_wallet | — | boolean | P3-18. Matrix U-06/U-11 mirror: own ACTIVE user/sale membership in the claimed app. |