@fayz-ai/plugin-financial 0.2.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/data/supabase.d.ts.map +1 -1
- package/dist/data/tables.d.ts +11 -0
- package/dist/data/tables.d.ts.map +1 -0
- package/dist/index.cjs +64 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +64 -52
- package/dist/index.js.map +1 -1
- package/dist/migrations/index.d.ts +16 -0
- package/dist/migrations/index.d.ts.map +1 -0
- package/dist/registries.d.ts.map +1 -1
- package/package.json +10 -4
- package/src/README.md +5 -5
- package/src/contract.test.ts +1 -1
- package/src/data/supabase.ts +50 -47
- package/src/data/tables.ts +12 -0
- package/src/migrations/000_plg_rename.sql +30 -0
- package/src/migrations/001_financial_base.sql +30 -30
- package/src/migrations/002_chart_of_accounts.sql +10 -10
- package/src/migrations/003_card_brands.sql +4 -4
- package/src/migrations/004_order_to_cash.sql +28 -28
- package/src/migrations/005_seed_defaults.sql +6 -6
- package/src/migrations/006_rls_policies.sql +5 -5
- package/src/migrations/{006_extract_fee_amount.sql → 006b_extract_fee_amount.sql} +4 -4
- package/src/migrations/007_reconciliation.sql +9 -9
- package/src/migrations/007b_movement_payment_method_type.sql +6 -0
- package/src/migrations/008_split_payment_movements.sql +5 -5
- package/src/migrations/index.ts +544 -0
- package/src/registries.ts +8 -7
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const MIGRATION_000_PLG_RENAME = "-- 000_plg_rename.sql \u2014 rename legacy financial tables to plg_financial_* for pools\n-- provisioned before the industry-pool rename. Guarded: fires only when the legacy\n-- name exists and the target does not, so fresh pools skip every branch.\nDO $$\nBEGIN\n IF to_regclass('public.financial_movements') IS NOT NULL AND to_regclass('public.plg_financial_movements') IS NULL THEN\n ALTER TABLE public.financial_movements RENAME TO plg_financial_movements;\n END IF;\n IF to_regclass('public.chart_of_accounts') IS NOT NULL AND to_regclass('public.plg_financial_chart_of_accounts') IS NULL THEN\n ALTER TABLE public.chart_of_accounts RENAME TO plg_financial_chart_of_accounts;\n END IF;\n IF to_regclass('public.bank_accounts') IS NOT NULL AND to_regclass('public.plg_financial_bank_accounts') IS NULL THEN\n ALTER TABLE public.bank_accounts RENAME TO plg_financial_bank_accounts;\n END IF;\n IF to_regclass('public.card_brands') IS NOT NULL AND to_regclass('public.plg_financial_card_brands') IS NULL THEN\n ALTER TABLE public.card_brands RENAME TO plg_financial_card_brands;\n END IF;\n IF to_regclass('public.cost_centers') IS NOT NULL AND to_regclass('public.plg_financial_cost_centers') IS NULL THEN\n ALTER TABLE public.cost_centers RENAME TO plg_financial_cost_centers;\n END IF;\n IF to_regclass('public.cash_register_sessions') IS NOT NULL AND to_regclass('public.plg_financial_cash_register_sessions') IS NULL THEN\n ALTER TABLE public.cash_register_sessions RENAME TO plg_financial_cash_register_sessions;\n END IF;\n IF to_regclass('public.payment_methods') IS NOT NULL AND to_regclass('public.plg_financial_payment_methods') IS NULL THEN\n ALTER TABLE public.payment_methods RENAME TO plg_financial_payment_methods;\n END IF;\n IF to_regclass('public.payment_method_types') IS NOT NULL AND to_regclass('public.plg_financial_payment_method_types') IS NULL THEN\n ALTER TABLE public.payment_method_types RENAME TO plg_financial_payment_method_types;\n END IF;\nEND $$;\n";
|
|
2
|
+
export declare const MIGRATION_001_FINANCIAL_BASE = "-- Financial Plugin: Base Tables\n-- Pattern: uuid PK, tenant_id FK, timestamps, RLS via project_rls.sql auto-detection\n\nCREATE TABLE IF NOT EXISTS public.plg_financial_payment_method_types (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n name text NOT NULL,\n transaction_type text NOT NULL,\n is_active boolean NOT NULL DEFAULT true,\n allowed_account_types jsonb DEFAULT '[]'::jsonb,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_financial_payment_method_types ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_financial_payment_method_types_tenant ON public.plg_financial_payment_method_types(tenant_id);\n\nCREATE TABLE IF NOT EXISTS public.plg_financial_payment_methods (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n name text NOT NULL,\n payment_method_type_id uuid REFERENCES public.plg_financial_payment_method_types(id),\n is_active boolean NOT NULL DEFAULT true,\n discount_mode text,\n discount_value numeric(12,2) DEFAULT 0,\n interest_mode text,\n interest_value numeric(12,2) DEFAULT 0,\n min_installments integer DEFAULT 1,\n max_installments integer DEFAULT 1,\n service_filter_mode text DEFAULT 'all',\n service_filter_ids jsonb DEFAULT '[]'::jsonb,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_financial_payment_methods ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_financial_payment_methods_tenant ON public.plg_financial_payment_methods(tenant_id);\n\nCREATE TABLE IF NOT EXISTS public.plg_financial_bank_accounts (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n name text NOT NULL,\n account_type text NOT NULL DEFAULT 'bank_account',\n bank_name text,\n account_number text,\n agency_number text,\n current_balance numeric(14,2) NOT NULL DEFAULT 0,\n initial_balance numeric(14,2) NOT NULL DEFAULT 0,\n credit_limit numeric(14,2),\n due_day integer,\n closing_day integer,\n is_active boolean NOT NULL DEFAULT true,\n unit_id uuid,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_financial_bank_accounts ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_financial_bank_accounts_tenant ON public.plg_financial_bank_accounts(tenant_id);\n\nCREATE TABLE IF NOT EXISTS public.plg_financial_cash_register_sessions (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n bank_account_id uuid NOT NULL REFERENCES public.plg_financial_bank_accounts(id),\n status text NOT NULL DEFAULT 'open',\n opened_at timestamptz NOT NULL DEFAULT now(),\n opened_by_user_id uuid,\n opened_by_name text,\n opening_balance numeric(14,2) NOT NULL,\n closed_at timestamptz,\n closed_by_user_id uuid,\n closed_by_name text,\n closing_balance numeric(14,2),\n expected_balance numeric(14,2),\n difference numeric(14,2),\n notes text,\n unit_id uuid,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_financial_cash_register_sessions ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_financial_cash_register_sessions_tenant ON public.plg_financial_cash_register_sessions(tenant_id);\n\n-- Financial movements (installments, payments) \u2014 plugin-specific, not archetype\n-- Invoices themselves use public.orders (kind='invoice_payable'/'invoice_receivable')\nCREATE TABLE IF NOT EXISTS public.plg_financial_movements (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n invoice_id uuid REFERENCES public.orders(id),\n direction text NOT NULL,\n movement_kind text NOT NULL,\n amount numeric(14,2) NOT NULL,\n paid_amount numeric(14,2) DEFAULT 0,\n status text NOT NULL DEFAULT 'pending',\n due_date date NOT NULL,\n payment_date date,\n installment_number integer,\n payment_method_id uuid REFERENCES public.plg_financial_payment_methods(id),\n bank_account_id uuid REFERENCES public.plg_financial_bank_accounts(id),\n cash_session_id uuid REFERENCES public.plg_financial_cash_register_sessions(id),\n card_brand text,\n card_installments integer,\n notes text,\n metadata jsonb DEFAULT '{}'::jsonb,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_financial_movements ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_financial_movements_tenant ON public.plg_financial_movements(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_financial_movements_invoice ON public.plg_financial_movements(invoice_id);\nCREATE INDEX IF NOT EXISTS idx_plg_financial_movements_due ON public.plg_financial_movements(tenant_id, due_date);\nCREATE INDEX IF NOT EXISTS idx_plg_financial_movements_bank ON public.plg_financial_movements(bank_account_id);\n";
|
|
3
|
+
export declare const MIGRATION_002_CHART_OF_ACCOUNTS = "-- Financial Plugin: Chart of Accounts + Cost Centers\n\nCREATE TABLE IF NOT EXISTS public.plg_financial_chart_of_accounts (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n code text NOT NULL,\n name text NOT NULL,\n node_type text NOT NULL DEFAULT 'leaf',\n parent_id uuid REFERENCES public.plg_financial_chart_of_accounts(id),\n is_active boolean NOT NULL DEFAULT true,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_financial_chart_of_accounts ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_financial_chart_of_accounts_tenant ON public.plg_financial_chart_of_accounts(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_financial_chart_of_accounts_parent ON public.plg_financial_chart_of_accounts(parent_id);\n\nCREATE TABLE IF NOT EXISTS public.plg_financial_cost_centers (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n code text NOT NULL,\n name text NOT NULL,\n is_active boolean NOT NULL DEFAULT true,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_financial_cost_centers ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_financial_cost_centers_tenant ON public.plg_financial_cost_centers(tenant_id);\n";
|
|
4
|
+
export declare const MIGRATION_003_CARD_BRANDS = "-- Financial Plugin: Card Brands\n\nCREATE TABLE IF NOT EXISTS public.plg_financial_card_brands (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n name text NOT NULL,\n is_active boolean NOT NULL DEFAULT true,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_financial_card_brands ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_financial_card_brands_tenant ON public.plg_financial_card_brands(tenant_id);\n";
|
|
5
|
+
export declare const MIGRATION_004_ORDER_TO_CASH = "-- Financial plugin \u2014 order-to-cash companion SQL.\n-- The atomic \"promote an order into an invoice + installment ledger\" function\n-- that CRM (approveQuote) and the agenda financial bridge both RPC. It belongs\n-- to the financial plugin (it writes plg_financial_movements + reads orders), and it\n-- ships WITH the plugin so enabling Payments provisions it. Idempotent.\n-- Depends on: public.orders, public.plg_financial_movements (001_financial_base).\n\n-- 1. Sequence generator (REC-00001 / PAG-00001 numbering)\nCREATE TABLE IF NOT EXISTS public.sequences (\n tenant_id uuid NOT NULL REFERENCES public.tenants(id),\n kind text NOT NULL,\n current_value bigint NOT NULL DEFAULT 0,\n PRIMARY KEY (tenant_id, kind)\n);\nCREATE OR REPLACE FUNCTION public.next_sequence(p_tenant_id uuid, p_kind text)\nRETURNS bigint LANGUAGE plpgsql AS $$\nDECLARE v_next bigint;\nBEGIN\n INSERT INTO public.sequences (tenant_id, kind, current_value)\n VALUES (p_tenant_id, p_kind, 1)\n ON CONFLICT (tenant_id, kind)\n DO UPDATE SET current_value = public.sequences.current_value + 1\n RETURNING current_value INTO v_next;\n RETURN v_next;\nEND;\n$$;\n\n-- 2. Order-to-cash columns on the spine orders (plugin extends public.orders)\nALTER TABLE public.orders\n ADD COLUMN IF NOT EXISTS stage text,\n ADD COLUMN IF NOT EXISTS direction text;\n\n-- 3. RLS + grants for plg_financial_movements (table from 001_financial_base.sql)\nALTER TABLE public.plg_financial_movements ENABLE ROW LEVEL SECURITY;\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_financial_movements TO authenticated;\nDO $$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename='plg_financial_movements' AND policyname='plg_financial_movements_select') THEN\n CREATE POLICY plg_financial_movements_select ON public.plg_financial_movements FOR SELECT TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()));\n CREATE POLICY plg_financial_movements_insert ON public.plg_financial_movements FOR INSERT TO authenticated WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()));\n CREATE POLICY plg_financial_movements_update ON public.plg_financial_movements FOR UPDATE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()));\n CREATE POLICY plg_financial_movements_delete ON public.plg_financial_movements FOR DELETE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()));\n END IF;\nEND $$;\n\n-- 4. The function (v2 \u2014 backward compatible with the 3-arg CRM call via defaults)\nDROP FUNCTION IF EXISTS public.fn_invoice_from_order(uuid, date, text);\nCREATE OR REPLACE FUNCTION public.fn_invoice_from_order(\n p_order_id uuid,\n p_due_date date DEFAULT NULL,\n p_status text DEFAULT NULL,\n p_installments int DEFAULT 1,\n p_direction text DEFAULT 'credit'\n) RETURNS uuid\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_order public.orders%ROWTYPE;\n v_ref text;\n v_seq bigint;\n v_summary text;\n v_contact text;\n v_existing uuid;\n v_kind text;\n v_prefix text;\n v_n int := GREATEST(COALESCE(p_installments, 1), 1);\n v_total numeric;\n v_base numeric;\n v_amt numeric;\n v_alloc numeric := 0;\n v_due date;\n i int;\nBEGIN\n SELECT * INTO v_order FROM public.orders WHERE id = p_order_id;\n IF NOT FOUND THEN RAISE EXCEPTION 'fn_invoice_from_order: order % not found', p_order_id; END IF;\n IF v_order.tenant_id NOT IN (SELECT public.user_tenant_ids()) THEN\n RAISE EXCEPTION 'fn_invoice_from_order: forbidden';\n END IF;\n\n SELECT id INTO v_existing FROM public.plg_financial_movements\n WHERE invoice_id = p_order_id AND movement_kind = 'bill' LIMIT 1;\n IF v_existing IS NOT NULL THEN RETURN p_order_id; END IF;\n\n IF p_direction = 'debit' THEN v_kind := 'invoice_payable'; v_prefix := 'PAG';\n ELSE v_kind := 'invoice_receivable'; v_prefix := 'REC'; END IF;\n\n SELECT public.next_sequence(v_order.tenant_id, v_kind) INTO v_seq;\n v_ref := v_prefix || '-' || lpad(v_seq::text, 5, '0');\n\n SELECT string_agg(name, ', ' ORDER BY sort_order) INTO v_summary\n FROM public.order_items WHERE order_id = p_order_id;\n SELECT name INTO v_contact FROM public.people WHERE id = v_order.party_id;\n\n UPDATE public.orders SET\n status = COALESCE(p_status, status),\n stage = 'invoiced',\n direction = p_direction,\n reference_number = v_ref,\n metadata = COALESCE(metadata, '{}'::jsonb) || jsonb_build_object(\n 'itemsSummary', COALESCE(v_summary, ''),\n 'contactName', v_contact,\n 'installmentCount', v_n,\n 'quoteNumber', v_order.reference_number,\n 'direction', p_direction\n ),\n updated_at = now()\n WHERE id = p_order_id;\n\n v_total := COALESCE(v_order.total, 0);\n v_base := round(v_total / v_n, 2);\n v_due := COALESCE(p_due_date, current_date);\n FOR i IN 1..v_n LOOP\n IF i = v_n THEN v_amt := round(v_total - v_alloc, 2);\n ELSE v_amt := v_base; v_alloc := v_alloc + v_base; END IF;\n INSERT INTO public.plg_financial_movements\n (tenant_id, invoice_id, direction, movement_kind, amount, paid_amount, status, due_date, installment_number)\n VALUES\n (v_order.tenant_id, p_order_id, p_direction, 'bill', v_amt, 0, 'pending',\n (v_due + ((i - 1) || ' months')::interval)::date, i);\n END LOOP;\n\n RETURN p_order_id;\nEND;\n$$;\nGRANT EXECUTE ON FUNCTION public.fn_invoice_from_order(uuid, date, text, int, text) TO authenticated;\n\n-- 5. Derived balances view (Payments page + agenda payment badge read this)\nCREATE OR REPLACE VIEW public.v_invoice_balances AS\nWITH bill AS (\n SELECT\n invoice_id,\n SUM(amount) FILTER (WHERE status <> 'cancelled') AS billed,\n SUM(paid_amount) FILTER (WHERE status <> 'cancelled') AS paid,\n bool_or(status NOT IN ('paid','cancelled') AND due_date < current_date) AS has_overdue\n FROM public.plg_financial_movements\n WHERE movement_kind = 'bill'\n GROUP BY invoice_id\n)\nSELECT\n o.id AS invoice_id, o.tenant_id, o.kind, o.reference_number, o.party_id, o.direction,\n CASE WHEN o.direction = 'debit' OR o.kind = 'invoice_payable' THEN 'payable' ELSE 'receivable' END AS flow,\n COALESCE(b.billed, o.total, 0) AS amount,\n COALESCE(b.paid, 0) AS paid,\n CASE WHEN o.status = 'cancelled' OR o.stage = 'cancelled' THEN 0\n ELSE COALESCE(b.billed, o.total, 0) - COALESCE(b.paid, 0) END AS balance,\n CASE\n WHEN o.status = 'cancelled' OR o.stage = 'cancelled' THEN 'cancelled'\n WHEN COALESCE(b.billed, o.total, 0) = 0 THEN 'open'\n WHEN COALESCE(b.paid, 0) >= COALESCE(b.billed, o.total, 0) THEN 'paid'\n WHEN COALESCE(b.paid, 0) > 0 THEN 'partial'\n WHEN COALESCE(b.has_overdue, false) THEN 'overdue'\n ELSE 'open'\n END AS status,\n o.created_at, o.updated_at\nFROM public.orders o\nLEFT JOIN bill b ON b.invoice_id = o.id\nWHERE o.kind IN ('invoice_receivable','invoice_payable') OR b.invoice_id IS NOT NULL;\nALTER VIEW public.v_invoice_balances SET (security_invoker = true);\nGRANT SELECT ON public.v_invoice_balances TO authenticated;\n\n-- Refresh PostgREST's schema cache so the new RPC/views are visible immediately.\nNOTIFY pgrst, 'reload schema';\n";
|
|
6
|
+
export declare const MIGRATION_005_SEED_DEFAULTS = "-- Financial plugin \u2014 seed: payment method types + card brands.\n-- These are the read-only \"system\" registries the plugin's UI assumes exist\n-- (PaymentModal, card selection). They live as registry seedData in TS but were\n-- never written to the DB, so a fresh tenant had none. This backfills them for\n-- every tenant that has none. Idempotent. Plugin-owned so every app gets them.\n\nDO $$\nDECLARE t_id uuid;\nBEGIN\n FOR t_id IN (\n SELECT id FROM public.tenants\n WHERE id NOT IN (SELECT DISTINCT tenant_id FROM public.plg_financial_payment_method_types)\n )\n LOOP\n INSERT INTO public.plg_financial_payment_method_types (tenant_id, name, transaction_type) VALUES\n (t_id, 'Cash', 'cash'),\n (t_id, 'PIX', 'pix'),\n (t_id, 'Credit Card', 'credit_card'),\n (t_id, 'Debit Card', 'debit_card'),\n (t_id, 'Bank Transfer', 'bank_transfer'),\n (t_id, 'Check', 'check');\n END LOOP;\nEND $$;\n\nDO $$\nDECLARE t_id uuid;\nBEGIN\n FOR t_id IN (\n SELECT id FROM public.tenants\n WHERE id NOT IN (SELECT DISTINCT tenant_id FROM public.plg_financial_card_brands)\n )\n LOOP\n INSERT INTO public.plg_financial_card_brands (tenant_id, name) VALUES\n (t_id, 'Visa'), (t_id, 'Mastercard'), (t_id, 'American Express'),\n (t_id, 'Elo'), (t_id, 'Hipercard'), (t_id, 'Diners Club'),\n (t_id, 'Discover'), (t_id, 'JCB'), (t_id, 'Aura'), (t_id, 'Hiper');\n END LOOP;\nEND $$;\n";
|
|
7
|
+
export declare const MIGRATION_006_RLS_POLICIES = "-- Financial Plugin: RLS policies + grants for ALL base tables.\n--\n-- The base migrations (001/002/003) ENABLE row-level security but relied on an\n-- external `project_rls.sql` auto-detection step to create the actual policies.\n-- That step does not run in the Drizzle/companion pipeline, so every table\n-- except plg_financial_movements was RLS-enabled with NO policy \u2192 all inserts denied\n-- (\"new row violates row-level security policy\"). This creates the canonical\n-- per-tenant policies idempotently. Re-running is a no-op (IF NOT EXISTS guards;\n-- plg_financial_movements policies from 004 are skipped).\n--\n-- Canonical RLS form: tenant_id IN (SELECT public.user_tenant_ids()).\n\nDO $$\nDECLARE t text;\nBEGIN\n FOR t IN SELECT unnest(ARRAY[\n 'plg_financial_payment_method_types','plg_financial_payment_methods','plg_financial_bank_accounts',\n 'plg_financial_cash_register_sessions','plg_financial_movements',\n 'plg_financial_chart_of_accounts','plg_financial_cost_centers','plg_financial_card_brands'\n ])\n LOOP\n EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t);\n EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON public.%I TO authenticated', t);\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_select') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR SELECT TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_select', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_insert') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR INSERT TO authenticated WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_insert', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_update') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR UPDATE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_update', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_delete') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR DELETE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_delete', t);\n END IF;\n END LOOP;\nEND $$;\n";
|
|
8
|
+
export declare const MIGRATION_006B_EXTRACT_FEE_AMOUNT = "-- ---------------------------------------------------------------------------\n-- Financial extract (extrato): net card settlement + transfers\n-- ---------------------------------------------------------------------------\n-- Adds the processing/MDR fee column used by the bank/cash account statement so\n-- the running balance reflects the NET cash that actually lands in the account.\n-- gross = paid_amount (settles the receivable/payable)\n-- net cash = paid_amount - fee_amount (credits only; v1 has no fee on debits)\nALTER TABLE public.plg_financial_movements\n ADD COLUMN IF NOT EXISTS fee_amount numeric(14,2) NOT NULL DEFAULT 0;\n\nCOMMENT ON COLUMN public.plg_financial_movements.fee_amount IS\n 'Processing/MDR fee deducted at settlement. Net cash impact = paid_amount - fee_amount (credit). v1: same-day net, no D+N settlement-date modeling.';\n\nCREATE INDEX IF NOT EXISTS idx_plg_financial_movements_statement\n ON public.plg_financial_movements (bank_account_id, payment_date)\n WHERE status IN ('paid', 'partial');\n\n-- Transfers between accounts = a debit row (source) + credit row (destination),\n-- both status='paid', movement_kind='transfer', correlated via metadata jsonb:\n-- metadata->>'transferId' | 'transferRole' ('out'|'in') | 'counterAccountId'\n";
|
|
9
|
+
export declare const MIGRATION_007_RECONCILIATION = "-- ---------------------------------------------------------------------------\n-- Reconciliation (concilia\u00E7\u00E3o): bank-statement lines \u2194 internal movements\n-- ---------------------------------------------------------------------------\n-- An integration (e.g. open banking) imports bank-statement lines as\n-- plg_financial_movements tagged with (external_source, external_id). The matching\n-- UI then links each imported line to the internal movement it settles, or\n-- accepts it standalone. These columns make a movement carry its bank-line\n-- identity and its reconciliation state.\n-- external_source / external_id : the bank line's provider + unique id\n-- reconciled_at : when the line was matched/accepted (NULL = pending)\n-- matched_movement_id : the internal movement this line reconciles (NULL = standalone)\nALTER TABLE public.plg_financial_movements\n ADD COLUMN IF NOT EXISTS external_id text,\n ADD COLUMN IF NOT EXISTS external_source text,\n ADD COLUMN IF NOT EXISTS reconciled_at timestamptz,\n ADD COLUMN IF NOT EXISTS matched_movement_id uuid\n REFERENCES public.plg_financial_movements(id) ON DELETE SET NULL;\n\nCOMMENT ON COLUMN public.plg_financial_movements.external_source IS\n 'Provider of an imported bank-statement line (e.g. plugbank, inter). NULL for app-native movements.';\nCOMMENT ON COLUMN public.plg_financial_movements.external_id IS\n 'Provider-unique id of the imported bank line. Forms the import idempotency key with external_source.';\n\n-- Idempotency: a given bank line imports at most once per tenant.\nCREATE UNIQUE INDEX IF NOT EXISTS uq_plg_financial_movements_external\n ON public.plg_financial_movements (tenant_id, external_source, external_id)\n WHERE external_id IS NOT NULL AND external_source IS NOT NULL;\n\n-- Fast lookup of imported-but-unreconciled lines for the matching screen.\nCREATE INDEX IF NOT EXISTS idx_plg_financial_movements_unreconciled\n ON public.plg_financial_movements (tenant_id, payment_date)\n WHERE external_source IS NOT NULL AND reconciled_at IS NULL;\n";
|
|
10
|
+
export declare const MIGRATION_007B_MOVEMENT_PAYMENT_METHOD_TYPE = "-- payment_method_type_id existed on pre-pool installs (added out-of-band on\n-- the salon/beauty DB) but was never captured in the file series; 008 requires\n-- it on plg_financial_movements. No-op where the column already exists.\n\nALTER TABLE public.plg_financial_movements\n ADD COLUMN IF NOT EXISTS payment_method_type_id uuid REFERENCES public.plg_financial_payment_method_types(id);\n";
|
|
11
|
+
export declare const MIGRATION_008_SPLIT_PAYMENT_MOVEMENTS = "-- Split bill (obligation) vs payment (cash event).\n-- Each payment is now its own movement_kind='payment' row (one per cash event), so\n-- two payments on one installment show as two extract rows instead of one summed row.\n-- Bills stay pure obligations; v_invoice_balances already filters movement_kind='bill',\n-- so the new payment rows don't affect invoice balances. Backfill is idempotent.\n-- Requires fee_amount (006b_extract_fee_amount.sql).\n\nINSERT INTO public.plg_financial_movements\n (tenant_id, invoice_id, direction, movement_kind, amount, paid_amount, fee_amount, status,\n due_date, payment_date, installment_number, payment_method_id, payment_method_type_id,\n bank_account_id, cash_session_id, card_brand, card_installments, notes, metadata)\nSELECT\n b.tenant_id, b.invoice_id, b.direction, 'payment', b.paid_amount, b.paid_amount,\n COALESCE(b.fee_amount, 0), 'paid',\n b.due_date, COALESCE(b.payment_date, b.updated_at::date, CURRENT_DATE), b.installment_number,\n b.payment_method_id, b.payment_method_type_id, b.bank_account_id, b.cash_session_id,\n b.card_brand, b.card_installments, b.notes,\n jsonb_build_object('backfilledFromBill', b.id)\nFROM public.plg_financial_movements b\nWHERE b.movement_kind = 'bill' AND b.paid_amount > 0\n AND NOT EXISTS (\n SELECT 1 FROM public.plg_financial_movements p\n WHERE p.movement_kind = 'payment' AND p.metadata->>'backfilledFromBill' = b.id::text\n );\n\nUPDATE public.plg_financial_movements\nSET payment_date = NULL, bank_account_id = NULL, payment_method_id = NULL,\n payment_method_type_id = NULL, cash_session_id = NULL, card_brand = NULL, card_installments = NULL\nWHERE movement_kind = 'bill';\n";
|
|
12
|
+
export declare const MIGRATIONS: Array<{
|
|
13
|
+
id: string;
|
|
14
|
+
sql: string;
|
|
15
|
+
}>;
|
|
16
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,wBAAwB,8+DA8BpC,CAAA;AAED,eAAO,MAAM,4BAA4B,woKA6GxC,CAAA;AAED,eAAO,MAAM,+BAA+B,67CA4B3C,CAAA;AAED,eAAO,MAAM,yBAAyB,0kBAYrC,CAAA;AAED,eAAO,MAAM,2BAA2B,yqOAoKvC,CAAA;AAED,eAAO,MAAM,2BAA2B,y6CAsCvC,CAAA;AAED,eAAO,MAAM,0BAA0B,k3EAqCtC,CAAA;AAED,eAAO,MAAM,iCAAiC,kxCAoB7C,CAAA;AAED,eAAO,MAAM,4BAA4B,sjEAgCxC,CAAA;AAED,eAAO,MAAM,2CAA2C,8YAMvD,CAAA;AAED,eAAO,MAAM,qCAAqC,qqDA6BjD,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAYzD,CAAA"}
|
package/dist/registries.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registries.d.ts","sourceRoot":"","sources":["../src/registries.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;
|
|
1
|
+
{"version":3,"file":"registries.d.ts","sourceRoot":"","sources":["../src/registries.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAwMtD,eAAO,MAAM,mBAAmB,EAAE,iBAAiB,EA2GlD,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fayz-ai/plugin-financial",
|
|
3
|
-
"
|
|
3
|
+
"fayz": {
|
|
4
|
+
"status": "beta"
|
|
5
|
+
},
|
|
6
|
+
"version": "0.8.0",
|
|
4
7
|
"description": "Fayz SDK — plugin-financial plugin",
|
|
5
8
|
"type": "module",
|
|
6
9
|
"main": "./dist/index.cjs",
|
|
@@ -26,9 +29,9 @@
|
|
|
26
29
|
"lucide-react": "^0.400.0",
|
|
27
30
|
"zustand": "^4.5.0",
|
|
28
31
|
"@tanstack/react-table": "^8.20.0",
|
|
29
|
-
"@fayz-ai/ui": "^0.
|
|
30
|
-
"@fayz-ai/saas": "^0.
|
|
31
|
-
"@fayz-ai/core": "^0.
|
|
32
|
+
"@fayz-ai/ui": "^0.8.0",
|
|
33
|
+
"@fayz-ai/saas": "^0.8.0",
|
|
34
|
+
"@fayz-ai/core": "^0.8.0"
|
|
32
35
|
},
|
|
33
36
|
"devDependencies": {
|
|
34
37
|
"@types/react": "^18.3.0",
|
|
@@ -45,6 +48,9 @@
|
|
|
45
48
|
"fayz-plugin",
|
|
46
49
|
"fayz-sdk"
|
|
47
50
|
],
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public"
|
|
53
|
+
},
|
|
48
54
|
"scripts": {
|
|
49
55
|
"build": "tsup && tsc --emitDeclarationOnly --declaration --declarationMap --noEmit false",
|
|
50
56
|
"dev": "tsup --watch",
|
package/src/README.md
CHANGED
|
@@ -7,7 +7,7 @@ Accounts payable/receivable, cash registers, bank statements, and financial repo
|
|
|
7
7
|
```typescript
|
|
8
8
|
import { createFinancialPlugin } from '@fayz-ai/saas-core/plugins/financial'
|
|
9
9
|
|
|
10
|
-
// In your
|
|
10
|
+
// In your defineSaas config:
|
|
11
11
|
plugins: [
|
|
12
12
|
createFinancialPlugin({
|
|
13
13
|
currency: { code: 'BRL', locale: 'pt-BR', symbol: 'R$' },
|
|
@@ -100,11 +100,11 @@ Accessible via gear icon in Financial module or in global Settings > Financial t
|
|
|
100
100
|
|
|
101
101
|
Run in order:
|
|
102
102
|
|
|
103
|
-
1. `001_financial_base.sql` — Core tables:
|
|
104
|
-
2. `002_chart_of_accounts.sql` —
|
|
105
|
-
3. `003_card_brands.sql` —
|
|
103
|
+
1. `001_financial_base.sql` — Core tables: plg_financial_payment_method_types, plg_financial_payment_methods, plg_financial_bank_accounts, plg_financial_cash_register_sessions, invoices, invoice_items, plg_financial_movements
|
|
104
|
+
2. `002_chart_of_accounts.sql` — plg_financial_chart_of_accounts (self-referencing tree), plg_financial_cost_centers
|
|
105
|
+
3. `003_card_brands.sql` — plg_financial_card_brands
|
|
106
106
|
|
|
107
|
-
All tables use `tenant_id` referencing `
|
|
107
|
+
All tables use `tenant_id` referencing `public.tenants(id)` for multi-tenant isolation.
|
|
108
108
|
|
|
109
109
|
## Views
|
|
110
110
|
|
package/src/contract.test.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Exercises the gate's rules with inline manifests (no UI import) so the tool
|
|
3
3
|
// itself is proven: a conformant manifest passes; each malformed shape throws.
|
|
4
4
|
// Real plugins call assertPluginManifestContract(theirManifest) in an env where
|
|
5
|
-
// their UI bundle loads (app-level / jsdom). See
|
|
5
|
+
// their UI bundle loads (app-level / jsdom). See docs/PLUGIN-PATTERNS.md → integrity.
|
|
6
6
|
import { describe, it, expect } from 'vitest'
|
|
7
7
|
import { assertPluginManifestContract, PluginContractError } from '@fayz-ai/core/testing'
|
|
8
8
|
import type { PluginManifest } from '@fayz-ai/core'
|
package/src/data/supabase.ts
CHANGED
|
@@ -11,6 +11,7 @@ import type {
|
|
|
11
11
|
} from '../types'
|
|
12
12
|
import { getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core'
|
|
13
13
|
import { getFinancialTenantId } from '../lib/tenant'
|
|
14
|
+
import { T } from './tables'
|
|
14
15
|
|
|
15
16
|
function getTenantId(): string | undefined {
|
|
16
17
|
// Local override wins; else use the app's active tenant so writes pass RLS.
|
|
@@ -37,7 +38,9 @@ function camelToSnake(obj: Record<string, unknown>): Record<string, unknown> {
|
|
|
37
38
|
function getClients() {
|
|
38
39
|
const supabase = getSupabaseClientOptional() as any
|
|
39
40
|
if (!supabase) throw new Error('Supabase not initialized')
|
|
40
|
-
|
|
41
|
+
// Core tables now live in PUBLIC (legacy dedicated core schema is gone). Both
|
|
42
|
+
// handles are the single public client; `core` retained for call-site readability.
|
|
43
|
+
return { core: supabase, pub: supabase }
|
|
41
44
|
}
|
|
42
45
|
|
|
43
46
|
/** Map order stage to InvoiceStatus for the financial UI */
|
|
@@ -64,7 +67,7 @@ async function sweepOverdue() {
|
|
|
64
67
|
const today = new Date().toISOString().slice(0, 10)
|
|
65
68
|
|
|
66
69
|
// Mark overdue movements
|
|
67
|
-
const { data: overdueMovs } = await pub.from(
|
|
70
|
+
const { data: overdueMovs } = await pub.from(T.movements)
|
|
68
71
|
.update({ status: 'overdue' })
|
|
69
72
|
.in('status', ['pending', 'partial'])
|
|
70
73
|
.lt('due_date', today)
|
|
@@ -74,7 +77,7 @@ async function sweepOverdue() {
|
|
|
74
77
|
if (overdueMovs && overdueMovs.length > 0) {
|
|
75
78
|
const invoiceIds = [...new Set(overdueMovs.map((m: any) => m.invoice_id).filter(Boolean))]
|
|
76
79
|
for (const invId of invoiceIds) {
|
|
77
|
-
const { data: allMovs } = await pub.from(
|
|
80
|
+
const { data: allMovs } = await pub.from(T.movements)
|
|
78
81
|
.select('status')
|
|
79
82
|
.eq('invoice_id', invId)
|
|
80
83
|
.eq('movement_kind', 'bill')
|
|
@@ -95,7 +98,7 @@ async function sweepOverdue() {
|
|
|
95
98
|
// S2 (data-model refactor): paid amount, balance and status are DERIVED from the
|
|
96
99
|
// append-only ledger via v_invoice_balances — the single source of truth — not
|
|
97
100
|
// from stored order.stage / metadata.paidAmount (which drift). See
|
|
98
|
-
// docs/
|
|
101
|
+
// docs/DATA-MODEL.md.
|
|
99
102
|
async function fetchInvoiceBalances(
|
|
100
103
|
pub: any,
|
|
101
104
|
ids: string[],
|
|
@@ -137,7 +140,7 @@ async function findOrderIdsByItemMetadata(
|
|
|
137
140
|
/** Card/MDR fee percent for a configured payment method (0 when none / not a fee method). */
|
|
138
141
|
async function getMethodFeePct(pub: any, paymentMethodId?: string): Promise<number> {
|
|
139
142
|
if (!paymentMethodId) return 0
|
|
140
|
-
const { data } = await pub.from(
|
|
143
|
+
const { data } = await pub.from(T.paymentMethods).select('discount_value').eq('id', paymentMethodId).single()
|
|
141
144
|
return Number(data?.discount_value) || 0
|
|
142
145
|
}
|
|
143
146
|
|
|
@@ -220,7 +223,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
220
223
|
const meta = data.metadata ?? {}
|
|
221
224
|
// Paid amount + status are DERIVED from the ledger view (single source of truth).
|
|
222
225
|
const balance = (await fetchInvoiceBalances(pub, [id])).get(id)
|
|
223
|
-
const { data: movs } = await pub.from(
|
|
226
|
+
const { data: movs } = await pub.from(T.movements)
|
|
224
227
|
.select('paid_amount')
|
|
225
228
|
.eq('invoice_id', id)
|
|
226
229
|
.eq('movement_kind', 'bill')
|
|
@@ -303,7 +306,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
303
306
|
|
|
304
307
|
// Create installment movements
|
|
305
308
|
if (order && input.installments.length > 0) {
|
|
306
|
-
await pub.from(
|
|
309
|
+
await pub.from(T.movements).insert(
|
|
307
310
|
input.installments.map((inst, i) => ({
|
|
308
311
|
tenant_id: tenantId, invoice_id: order.id,
|
|
309
312
|
direction: input.direction, movement_kind: inst.movementKind,
|
|
@@ -335,13 +338,13 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
335
338
|
async cancelInvoice(id: string): Promise<void> {
|
|
336
339
|
const { core, pub } = getClients()
|
|
337
340
|
await core.from('orders').update({ status: 'cancelled' }).eq('id', id)
|
|
338
|
-
await pub.from(
|
|
341
|
+
await pub.from(T.movements).update({ status: 'cancelled' }).eq('invoice_id', id).eq('status', 'pending')
|
|
339
342
|
},
|
|
340
343
|
|
|
341
344
|
// --- Movements (public.financial_movements) ---
|
|
342
345
|
async getMovements(query: MovementQuery): Promise<PaginatedResult<FinancialMovement>> {
|
|
343
346
|
const { core, pub } = getClients()
|
|
344
|
-
let qb = pub.from(
|
|
347
|
+
let qb = pub.from(T.movements).select('*', { count: 'exact' })
|
|
345
348
|
if (query.direction) qb = qb.eq('direction', query.direction)
|
|
346
349
|
if (query.status) {
|
|
347
350
|
const statuses = Array.isArray(query.status) ? query.status : [query.status]
|
|
@@ -359,7 +362,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
359
362
|
|
|
360
363
|
async payMovement(input: PayMovementInput): Promise<FinancialMovement> {
|
|
361
364
|
const { core, pub } = getClients()
|
|
362
|
-
const { data: mov } = await pub.from(
|
|
365
|
+
const { data: mov } = await pub.from(T.movements).select('*').eq('id', input.movementId).single()
|
|
363
366
|
if (!mov) throw new Error('Movement not found')
|
|
364
367
|
const tenantId = mov.tenant_id ?? getTenantId()
|
|
365
368
|
|
|
@@ -389,11 +392,11 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
389
392
|
card_installments: input.cardInstallments ?? null,
|
|
390
393
|
notes: input.notes ?? null,
|
|
391
394
|
}
|
|
392
|
-
let { data, error } = await pub.from(
|
|
395
|
+
let { data, error } = await pub.from(T.movements).insert(paymentRow).select().single()
|
|
393
396
|
// Graceful fallback if the fee_amount migration hasn't been applied yet.
|
|
394
397
|
if (error && /fee_amount/i.test(error.message ?? '')) {
|
|
395
398
|
const { fee_amount, ...rest } = paymentRow
|
|
396
|
-
;({ data, error } = await pub.from(
|
|
399
|
+
;({ data, error } = await pub.from(T.movements).insert(rest).select().single())
|
|
397
400
|
}
|
|
398
401
|
if (error) throw error
|
|
399
402
|
|
|
@@ -404,13 +407,13 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
404
407
|
const billStatus = newPaid >= mov.amount ? 'paid' : 'partial'
|
|
405
408
|
// Clear the bill's cash fields so it stops being a cash event (the payment row is now
|
|
406
409
|
// the cash event) — prevents double-counting legacy in-place-paid bills.
|
|
407
|
-
await pub.from(
|
|
410
|
+
await pub.from(T.movements)
|
|
408
411
|
.update({ paid_amount: newPaid, status: billStatus, payment_date: null, bank_account_id: null })
|
|
409
412
|
.eq('id', mov.id)
|
|
410
413
|
|
|
411
414
|
// 3. Update invoice (order) status based on its bills
|
|
412
415
|
if (mov.invoice_id) {
|
|
413
|
-
const { data: allMovs } = await pub.from(
|
|
416
|
+
const { data: allMovs } = await pub.from(T.movements)
|
|
414
417
|
.select('status, amount, paid_amount')
|
|
415
418
|
.eq('invoice_id', mov.invoice_id)
|
|
416
419
|
.eq('movement_kind', 'bill')
|
|
@@ -423,7 +426,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
423
426
|
const { data: order } = await core.from('orders').select('metadata').eq('id', mov.invoice_id).single()
|
|
424
427
|
const meta = (order?.metadata as any) ?? {}
|
|
425
428
|
const invoiceStage = allPaid ? 'paid' : anyPaid ? 'partial' : 'invoiced'
|
|
426
|
-
// Only update financial order status. Agenda status lives on
|
|
429
|
+
// Only update financial order status. Agenda status lives on public.appointments.
|
|
427
430
|
await core.from('orders').update({
|
|
428
431
|
status: invoiceStage,
|
|
429
432
|
metadata: { ...meta, paidAmount: totalPaid },
|
|
@@ -435,7 +438,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
435
438
|
|
|
436
439
|
async cancelMovement(id: string): Promise<void> {
|
|
437
440
|
const { core, pub } = getClients()
|
|
438
|
-
await pub.from(
|
|
441
|
+
await pub.from(T.movements).update({ status: 'cancelled' }).eq('id', id)
|
|
439
442
|
},
|
|
440
443
|
|
|
441
444
|
// --- Transfers (between accounts) ---
|
|
@@ -472,11 +475,11 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
472
475
|
metadata: { transferId, transferRole: 'in', counterAccountId: input.fromAccountId },
|
|
473
476
|
},
|
|
474
477
|
]
|
|
475
|
-
let { data, error } = await pub.from(
|
|
478
|
+
let { data, error } = await pub.from(T.movements).insert(rowsToInsert).select('id, direction')
|
|
476
479
|
// Graceful fallback if the fee_amount migration hasn't been applied yet.
|
|
477
480
|
if (error && /fee_amount/i.test(error.message ?? '')) {
|
|
478
481
|
const stripped = rowsToInsert.map(({ fee_amount, ...rest }) => rest)
|
|
479
|
-
;({ data, error } = await pub.from(
|
|
482
|
+
;({ data, error } = await pub.from(T.movements).insert(stripped).select('id, direction'))
|
|
480
483
|
}
|
|
481
484
|
if (error) throw error
|
|
482
485
|
const rows = (data ?? []) as Array<{ id: string; direction: string }>
|
|
@@ -488,14 +491,14 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
488
491
|
// --- Bank Accounts ---
|
|
489
492
|
async getBankAccounts(): Promise<BankAccount[]> {
|
|
490
493
|
const { core, pub } = getClients()
|
|
491
|
-
const { data } = await pub.from(
|
|
494
|
+
const { data } = await pub.from(T.bankAccounts).select('*').eq('is_active', true).order('name')
|
|
492
495
|
return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as BankAccount)
|
|
493
496
|
},
|
|
494
497
|
|
|
495
498
|
async createBankAccount(input: CreateBankAccountInput): Promise<BankAccount> {
|
|
496
499
|
const { core, pub } = getClients()
|
|
497
500
|
const tenantId = getTenantId()
|
|
498
|
-
const { data } = await pub.from(
|
|
501
|
+
const { data } = await pub.from(T.bankAccounts).insert({
|
|
499
502
|
...camelToSnake(input as any), tenant_id: tenantId, current_balance: input.initialBalance ?? 0,
|
|
500
503
|
}).select().single()
|
|
501
504
|
return snakeToCamel(data!) as unknown as BankAccount
|
|
@@ -505,14 +508,14 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
505
508
|
const { core, pub } = getClients()
|
|
506
509
|
const row = camelToSnake(partial as any)
|
|
507
510
|
delete row.id; delete row.tenant_id
|
|
508
|
-
const { data } = await pub.from(
|
|
511
|
+
const { data } = await pub.from(T.bankAccounts).update(row).eq('id', id).select().single()
|
|
509
512
|
return snakeToCamel(data!) as unknown as BankAccount
|
|
510
513
|
},
|
|
511
514
|
|
|
512
515
|
// --- Cash Sessions ---
|
|
513
516
|
async getCashSessions(bankAccountId?: string): Promise<CashSession[]> {
|
|
514
517
|
const { core, pub } = getClients()
|
|
515
|
-
let qb = pub.from(
|
|
518
|
+
let qb = pub.from(T.cashRegisterSessions).select('*')
|
|
516
519
|
if (bankAccountId) qb = qb.eq('bank_account_id', bankAccountId)
|
|
517
520
|
const { data } = await qb.order('opened_at', { ascending: false })
|
|
518
521
|
return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as CashSession)
|
|
@@ -520,14 +523,14 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
520
523
|
|
|
521
524
|
async getOpenSession(bankAccountId: string): Promise<CashSession | null> {
|
|
522
525
|
const { core, pub } = getClients()
|
|
523
|
-
const { data } = await pub.from(
|
|
526
|
+
const { data } = await pub.from(T.cashRegisterSessions).select('*').eq('bank_account_id', bankAccountId).eq('status', 'open').single()
|
|
524
527
|
return data ? snakeToCamel(data) as unknown as CashSession : null
|
|
525
528
|
},
|
|
526
529
|
|
|
527
530
|
async openCashSession(input: OpenCashSessionInput): Promise<CashSession> {
|
|
528
531
|
const { core, pub } = getClients()
|
|
529
532
|
const tenantId = getTenantId()
|
|
530
|
-
const { data } = await pub.from(
|
|
533
|
+
const { data } = await pub.from(T.cashRegisterSessions).insert({
|
|
531
534
|
tenant_id: tenantId, bank_account_id: input.bankAccountId,
|
|
532
535
|
status: 'open', opening_balance: input.openingBalance,
|
|
533
536
|
opened_by_user_id: input.openedByUserId, opened_by_name: input.openedByName,
|
|
@@ -538,7 +541,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
538
541
|
|
|
539
542
|
async closeCashSession(input: CloseCashSessionInput): Promise<CashSession> {
|
|
540
543
|
const { core, pub } = getClients()
|
|
541
|
-
const { data } = await pub.from(
|
|
544
|
+
const { data } = await pub.from(T.cashRegisterSessions).update({
|
|
542
545
|
status: 'closed', closing_balance: input.closingBalance,
|
|
543
546
|
closed_at: new Date().toISOString(),
|
|
544
547
|
closed_by_user_id: input.closedByUserId, closed_by_name: input.closedByName,
|
|
@@ -549,8 +552,8 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
549
552
|
|
|
550
553
|
async getCashSessionSummary(sessionId: string): Promise<CashSessionSummary> {
|
|
551
554
|
const { core, pub } = getClients()
|
|
552
|
-
const session = (await pub.from(
|
|
553
|
-
const { data: movs } = await pub.from(
|
|
555
|
+
const session = (await pub.from(T.cashRegisterSessions).select('*').eq('id', sessionId).single()).data
|
|
556
|
+
const { data: movs } = await pub.from(T.movements).select('direction, paid_amount').eq('cash_session_id', sessionId).eq('status', 'paid')
|
|
554
557
|
const movements = movs ?? []
|
|
555
558
|
return {
|
|
556
559
|
session: snakeToCamel(session!) as unknown as CashSession,
|
|
@@ -563,26 +566,26 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
563
566
|
// --- Payment Methods ---
|
|
564
567
|
async getPaymentMethods(): Promise<PaymentMethod[]> {
|
|
565
568
|
const { core, pub } = getClients()
|
|
566
|
-
const { data } = await pub.from(
|
|
569
|
+
const { data } = await pub.from(T.paymentMethods).select('*').eq('is_active', true).order('name')
|
|
567
570
|
return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as PaymentMethod)
|
|
568
571
|
},
|
|
569
572
|
|
|
570
573
|
async getPaymentMethodTypes(): Promise<PaymentMethodType[]> {
|
|
571
574
|
const { core, pub } = getClients()
|
|
572
|
-
const { data } = await pub.from(
|
|
575
|
+
const { data } = await pub.from(T.paymentMethodTypes).select('*').eq('is_active', true).order('name')
|
|
573
576
|
return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as PaymentMethodType)
|
|
574
577
|
},
|
|
575
578
|
|
|
576
579
|
// --- Chart of Accounts ---
|
|
577
580
|
async getChartOfAccounts(): Promise<ChartOfAccountsNode[]> {
|
|
578
581
|
const { core, pub } = getClients()
|
|
579
|
-
const { data } = await pub.from(
|
|
582
|
+
const { data } = await pub.from(T.chartOfAccounts).select('*').eq('is_active', true).order('code')
|
|
580
583
|
return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as ChartOfAccountsNode)
|
|
581
584
|
},
|
|
582
585
|
|
|
583
586
|
async getCostCenters(): Promise<CostCenter[]> {
|
|
584
587
|
const { core, pub } = getClients()
|
|
585
|
-
const { data } = await pub.from(
|
|
588
|
+
const { data } = await pub.from(T.costCenters).select('*').eq('is_active', true).order('code')
|
|
586
589
|
return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as CostCenter)
|
|
587
590
|
},
|
|
588
591
|
|
|
@@ -604,7 +607,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
604
607
|
|
|
605
608
|
// 1. Resolve in-scope accounts. No bankAccountId => consolidated: ALL realized cash
|
|
606
609
|
// (including movements with no bank_account_id, e.g. cash/card payments not tied to an account).
|
|
607
|
-
const { data: acctRows } = await pub.from(
|
|
610
|
+
const { data: acctRows } = await pub.from(T.bankAccounts).select('id, name, initial_balance, is_active')
|
|
608
611
|
const allAccounts = (acctRows ?? []) as any[]
|
|
609
612
|
const consolidated = !query.bankAccountId
|
|
610
613
|
const scopeAccounts = consolidated
|
|
@@ -626,7 +629,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
626
629
|
|
|
627
630
|
// 2. Opening balance = Σ initial_balance + prior net (payment_date < from).
|
|
628
631
|
// Select '*' so this still works before the fee_amount migration lands (fee → 0).
|
|
629
|
-
const { data: priorRows } = await scopeFilter(pub.from(
|
|
632
|
+
const { data: priorRows } = await scopeFilter(pub.from(T.movements)
|
|
630
633
|
.select('*')
|
|
631
634
|
.neq('status', 'cancelled')
|
|
632
635
|
.lt('payment_date', query.dateRange.from))
|
|
@@ -634,7 +637,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
634
637
|
const openingBalance = round2(initialSum + priorNet)
|
|
635
638
|
|
|
636
639
|
// 3. In-range realized rows.
|
|
637
|
-
const { data: movs } = await scopeFilter(pub.from(
|
|
640
|
+
const { data: movs } = await scopeFilter(pub.from(T.movements)
|
|
638
641
|
.select('*')
|
|
639
642
|
.neq('status', 'cancelled')
|
|
640
643
|
.gte('payment_date', query.dateRange.from).lte('payment_date', query.dateRange.to)
|
|
@@ -687,7 +690,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
687
690
|
// extract row can link to the internal transaction it was conciliated with.
|
|
688
691
|
const matchedIds = [...new Set(entries.map((e) => e.movement.matchedMovementId).filter(Boolean))] as string[]
|
|
689
692
|
if (matchedIds.length) {
|
|
690
|
-
const { data: matched } = await pub.from(
|
|
693
|
+
const { data: matched } = await pub.from(T.movements).select('id, invoice_id, notes').in('id', matchedIds)
|
|
691
694
|
const matchedById = new Map<string, any>((matched ?? []).map((m: any) => [m.id, m]))
|
|
692
695
|
const matchedInvoiceIds = [...new Set((matched ?? []).map((m: any) => m.invoice_id).filter(Boolean))] as string[]
|
|
693
696
|
const invById = new Map<string, any>()
|
|
@@ -711,7 +714,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
711
714
|
}
|
|
712
715
|
|
|
713
716
|
// 6. Account current balance (ledger as-of-today).
|
|
714
|
-
const { data: todayRows } = await scopeFilter(pub.from(
|
|
717
|
+
const { data: todayRows } = await scopeFilter(pub.from(T.movements)
|
|
715
718
|
.select('*')
|
|
716
719
|
.neq('status', 'cancelled')
|
|
717
720
|
.lte('payment_date', today))
|
|
@@ -735,10 +738,10 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
735
738
|
// Sweep overdue on first load (background, non-blocking)
|
|
736
739
|
sweepOverdue()
|
|
737
740
|
const { core, pub } = getClients()
|
|
738
|
-
const { data: accounts } = await pub.from(
|
|
741
|
+
const { data: accounts } = await pub.from(T.bankAccounts).select('current_balance').eq('is_active', true)
|
|
739
742
|
const totalBalance = (accounts ?? []).reduce((s: number, a: any) => s + (a.current_balance ?? 0), 0)
|
|
740
743
|
|
|
741
|
-
const { data: movs } = await pub.from(
|
|
744
|
+
const { data: movs } = await pub.from(T.movements).select('direction, movement_kind, amount, paid_amount, status, due_date, payment_date')
|
|
742
745
|
const allMovs = movs ?? []
|
|
743
746
|
const unpaid = allMovs.filter((m: any) => ['pending', 'partial', 'overdue'].includes(m.status))
|
|
744
747
|
const today = new Date().toISOString().slice(0, 10)
|
|
@@ -778,7 +781,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
778
781
|
const tenantId = getTenantId()
|
|
779
782
|
let imported = 0, duplicates = 0
|
|
780
783
|
for (const line of input.lines) {
|
|
781
|
-
const { error } = await pub.from(
|
|
784
|
+
const { error } = await pub.from(T.movements).insert({
|
|
782
785
|
tenant_id: tenantId,
|
|
783
786
|
direction: line.direction,
|
|
784
787
|
movement_kind: 'payment',
|
|
@@ -803,7 +806,7 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
803
806
|
|
|
804
807
|
async getUnreconciled(query) {
|
|
805
808
|
const { pub } = getClients()
|
|
806
|
-
let qb = pub.from(
|
|
809
|
+
let qb = pub.from(T.movements).select('*')
|
|
807
810
|
.not('external_source', 'is', null)
|
|
808
811
|
.is('reconciled_at', null)
|
|
809
812
|
if (query?.bankAccountId) qb = qb.eq('bank_account_id', query.bankAccountId)
|
|
@@ -814,13 +817,13 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
814
817
|
|
|
815
818
|
async suggestReconciliation(bankMovementId) {
|
|
816
819
|
const { core, pub } = getClients()
|
|
817
|
-
const { data: line } = await pub.from(
|
|
820
|
+
const { data: line } = await pub.from(T.movements).select('*').eq('id', bankMovementId).single()
|
|
818
821
|
if (!line) return []
|
|
819
822
|
const amount = Number(line.amount) || 0
|
|
820
823
|
const lineDate = line.payment_date ?? line.due_date
|
|
821
824
|
// Candidates: app-native (non-imported), same direction, not reconciled, amount within ±2%.
|
|
822
825
|
const tol = Math.max(0.01, round2(amount * 0.02))
|
|
823
|
-
const { data } = await pub.from(
|
|
826
|
+
const { data } = await pub.from(T.movements).select('*')
|
|
824
827
|
.is('external_source', null)
|
|
825
828
|
.is('reconciled_at', null)
|
|
826
829
|
.eq('direction', line.direction)
|
|
@@ -857,22 +860,22 @@ export function createSupabaseFinancialProvider(): FinancialDataProvider {
|
|
|
857
860
|
async reconcileMovement(input) {
|
|
858
861
|
const { pub } = getClients()
|
|
859
862
|
const now = new Date().toISOString()
|
|
860
|
-
await pub.from(
|
|
863
|
+
await pub.from(T.movements).update({
|
|
861
864
|
reconciled_at: now,
|
|
862
865
|
matched_movement_id: input.matchedMovementId ?? null,
|
|
863
866
|
}).eq('id', input.bankMovementId)
|
|
864
867
|
if (input.matchedMovementId) {
|
|
865
868
|
// The internal movement is now settled+reconciled by the bank line.
|
|
866
|
-
await pub.from(
|
|
869
|
+
await pub.from(T.movements).update({ reconciled_at: now }).eq('id', input.matchedMovementId)
|
|
867
870
|
}
|
|
868
871
|
},
|
|
869
872
|
|
|
870
873
|
async unreconcileMovement(bankMovementId) {
|
|
871
874
|
const { pub } = getClients()
|
|
872
|
-
const { data: line } = await pub.from(
|
|
873
|
-
await pub.from(
|
|
875
|
+
const { data: line } = await pub.from(T.movements).select('matched_movement_id').eq('id', bankMovementId).single()
|
|
876
|
+
await pub.from(T.movements).update({ reconciled_at: null, matched_movement_id: null }).eq('id', bankMovementId)
|
|
874
877
|
if (line?.matched_movement_id) {
|
|
875
|
-
await pub.from(
|
|
878
|
+
await pub.from(T.movements).update({ reconciled_at: null }).eq('id', line.matched_movement_id)
|
|
876
879
|
}
|
|
877
880
|
},
|
|
878
881
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Central physical-table-name registry for plugin-financial. Providers import T so
|
|
2
|
+
// the plg_financial_* strings live in one place.
|
|
3
|
+
export const T = {
|
|
4
|
+
movements: 'plg_financial_movements',
|
|
5
|
+
chartOfAccounts: 'plg_financial_chart_of_accounts',
|
|
6
|
+
bankAccounts: 'plg_financial_bank_accounts',
|
|
7
|
+
cardBrands: 'plg_financial_card_brands',
|
|
8
|
+
costCenters: 'plg_financial_cost_centers',
|
|
9
|
+
cashRegisterSessions: 'plg_financial_cash_register_sessions',
|
|
10
|
+
paymentMethods: 'plg_financial_payment_methods',
|
|
11
|
+
paymentMethodTypes: 'plg_financial_payment_method_types',
|
|
12
|
+
} as const
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
-- 000_plg_rename.sql — rename legacy financial tables to plg_financial_* for pools
|
|
2
|
+
-- provisioned before the industry-pool rename. Guarded: fires only when the legacy
|
|
3
|
+
-- name exists and the target does not, so fresh pools skip every branch.
|
|
4
|
+
DO $$
|
|
5
|
+
BEGIN
|
|
6
|
+
IF to_regclass('public.financial_movements') IS NOT NULL AND to_regclass('public.plg_financial_movements') IS NULL THEN
|
|
7
|
+
ALTER TABLE public.financial_movements RENAME TO plg_financial_movements;
|
|
8
|
+
END IF;
|
|
9
|
+
IF to_regclass('public.chart_of_accounts') IS NOT NULL AND to_regclass('public.plg_financial_chart_of_accounts') IS NULL THEN
|
|
10
|
+
ALTER TABLE public.chart_of_accounts RENAME TO plg_financial_chart_of_accounts;
|
|
11
|
+
END IF;
|
|
12
|
+
IF to_regclass('public.bank_accounts') IS NOT NULL AND to_regclass('public.plg_financial_bank_accounts') IS NULL THEN
|
|
13
|
+
ALTER TABLE public.bank_accounts RENAME TO plg_financial_bank_accounts;
|
|
14
|
+
END IF;
|
|
15
|
+
IF to_regclass('public.card_brands') IS NOT NULL AND to_regclass('public.plg_financial_card_brands') IS NULL THEN
|
|
16
|
+
ALTER TABLE public.card_brands RENAME TO plg_financial_card_brands;
|
|
17
|
+
END IF;
|
|
18
|
+
IF to_regclass('public.cost_centers') IS NOT NULL AND to_regclass('public.plg_financial_cost_centers') IS NULL THEN
|
|
19
|
+
ALTER TABLE public.cost_centers RENAME TO plg_financial_cost_centers;
|
|
20
|
+
END IF;
|
|
21
|
+
IF to_regclass('public.cash_register_sessions') IS NOT NULL AND to_regclass('public.plg_financial_cash_register_sessions') IS NULL THEN
|
|
22
|
+
ALTER TABLE public.cash_register_sessions RENAME TO plg_financial_cash_register_sessions;
|
|
23
|
+
END IF;
|
|
24
|
+
IF to_regclass('public.payment_methods') IS NOT NULL AND to_regclass('public.plg_financial_payment_methods') IS NULL THEN
|
|
25
|
+
ALTER TABLE public.payment_methods RENAME TO plg_financial_payment_methods;
|
|
26
|
+
END IF;
|
|
27
|
+
IF to_regclass('public.payment_method_types') IS NOT NULL AND to_regclass('public.plg_financial_payment_method_types') IS NULL THEN
|
|
28
|
+
ALTER TABLE public.payment_method_types RENAME TO plg_financial_payment_method_types;
|
|
29
|
+
END IF;
|
|
30
|
+
END $$;
|