@fayz-ai/plugin-fiscal-br 0.14.0 → 0.15.1
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/dist/InboundNotesPage-UQH2YG3E.js +6 -0
- package/dist/{InboundNotesPage-R72EC5E4.js.map → InboundNotesPage-UQH2YG3E.js.map} +1 -1
- package/dist/NoteReceiptCard-H5BMFPU7.js +4 -0
- package/dist/{NoteReconcileView-3KVXZLCG.js.map → NoteReceiptCard-H5BMFPU7.js.map} +1 -1
- package/dist/NoteReconcileView-QSRL6NKQ.js +5 -0
- package/dist/NoteReconcileView-QSRL6NKQ.js.map +1 -0
- package/dist/chunk-3BDFMEYY.js +231 -0
- package/dist/chunk-3BDFMEYY.js.map +1 -0
- package/dist/chunk-DHCCZXUM.js +50 -0
- package/dist/chunk-DHCCZXUM.js.map +1 -0
- package/dist/{chunk-OGXYHL3Z.js → chunk-LHH2YIDB.js} +30 -15
- package/dist/chunk-LHH2YIDB.js.map +1 -0
- package/dist/{chunk-UYGGBJCR.js → chunk-TZH7AWBD.js} +187 -54
- package/dist/chunk-TZH7AWBD.js.map +1 -0
- package/dist/data/inbox.d.ts +5 -1
- package/dist/data/inbox.d.ts.map +1 -1
- package/dist/data/receipt.d.ts +45 -0
- package/dist/data/receipt.d.ts.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +148 -7
- package/dist/index.js.map +1 -1
- package/dist/lib/receipt.d.ts +39 -0
- package/dist/lib/receipt.d.ts.map +1 -0
- package/dist/locales/en.d.ts +2 -0
- package/dist/locales/en.d.ts.map +1 -0
- package/dist/locales/index.d.ts +2 -0
- package/dist/locales/index.d.ts.map +1 -0
- package/dist/locales/pt-BR.d.ts +2 -0
- package/dist/locales/pt-BR.d.ts.map +1 -0
- package/dist/migrations/index.d.ts +1 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/migrations/main.browser.js +2 -1
- package/dist/migrations/main.browser.js.map +1 -1
- package/dist/migrations/main.js +524 -2
- package/dist/migrations/main.js.map +1 -1
- package/dist/types.d.ts +8 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/views/InboundNotesView.d.ts.map +1 -1
- package/dist/views/NoteReceiptCard.d.ts +4 -0
- package/dist/views/NoteReceiptCard.d.ts.map +1 -0
- package/dist/views/NoteReconcileView.d.ts.map +1 -1
- package/package.json +5 -5
- package/dist/InboundNotesPage-R72EC5E4.js +0 -5
- package/dist/NoteReconcileView-3KVXZLCG.js +0 -4
- package/dist/chunk-OGXYHL3Z.js.map +0 -1
- package/dist/chunk-UYGGBJCR.js.map +0 -1
|
@@ -32,6 +32,7 @@ export declare const MIGRATION_030_THE_SERVICE_ONBOARDS_THE_EMITTER = "-- ======
|
|
|
32
32
|
export declare const MIGRATION_031_THE_SERVICE_ISSUES_THE_NOTE = "-- ============================================================================\n-- 031 \u2014 the integration service issues the order's note\n--\n-- control-sdk-backend ADR 0008, step 2: an operator clicks \"Emitir NFC-e\" on\n-- an order and the integration service builds the note with the V1's rules,\n-- sends it to PlugNotas and records what comes back. The note is the record\n-- 005 already defined (public.documents + plg_fiscalbr_documents, linked to\n-- the order by plg_fiscalbr_document_orders); these are the service's doors to\n-- it, one function per action, the tenant explicit, open only to\n-- `fayz_integration`.\n--\n-- fiscalbr_order_for_note_for_service what the note is made of\n-- fiscalbr_note_open_for_service the note, opened before the call\n-- fiscalbr_note_apply_for_service what PlugNotas answered\n-- fiscalbr_notes_for_service an order's notes\n-- fiscalbr_note_for_service one note\n-- fiscalbr_notes_to_follow_for_service notes still waiting on PlugNotas\n-- fiscalbr_note_by_integration_for_service where a webhook belongs\n--\n-- A note is opened BEFORE PlugNotas is called, with the idIntegracao it will\n-- carry, so a call whose answer is lost is found again by that id instead of\n-- being sent twice (the V1's FISCAL_PROVIDER_RESULT_UNCERTAIN rule).\n-- ============================================================================\n\n-- What the note of an order is made of: the order, its lines with their tax\n-- data, what was paid and how, who bought and where it goes. The service\n-- applies the rules; this only gathers.\nCREATE OR REPLACE FUNCTION public.fiscalbr_order_for_note_for_service(p_tenant uuid, p_order uuid)\nRETURNS jsonb\nLANGUAGE plpgsql STABLE SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE\n v_checkout jsonb;\nBEGIN\n -- The shop is optional: a site order says how it was paid on its checkout,\n -- read only where the shop's table exists.\n IF to_regclass('public.plg_shop_checkout_sessions') IS NOT NULL THEN\n EXECUTE $q$\n SELECT jsonb_build_object(\n 'paymentMethod', s.payment_method, 'provider', s.provider, 'total', s.total, 'status', s.status,\n 'customerName', s.customer_name, 'customerDocument', s.customer_document,\n 'destinationState', s.shipping_address ->> 'state', 'destinationCity', s.shipping_address ->> 'city')\n FROM public.plg_shop_checkout_sessions s\n WHERE s.order_id = $1 AND s.tenant_id = $2 AND s.status = 'paid'\n ORDER BY s.updated_at DESC LIMIT 1 $q$\n INTO v_checkout USING p_order, p_tenant;\n END IF;\n\n RETURN (SELECT jsonb_build_object(\n 'orderId', o.id,\n 'tenantId', o.tenant_id,\n 'unitId', o.unit_id,\n 'kind', o.kind,\n 'status', o.status,\n 'channel', o.channel,\n 'createdAt', o.created_at,\n 'subtotal', o.subtotal,\n 'discount', o.discount,\n 'shipping', o.shipping,\n 'total', o.total,\n 'legalEntityId', u.company_legal_entity_id,\n 'items', coalesce((\n SELECT jsonb_agg(jsonb_build_object(\n 'itemId', i.id,\n 'productId', i.product_id,\n 'code', coalesce(nullif(p.sku, ''), i.product_id::text, i.id::text),\n 'name', i.name,\n 'quantity', i.quantity,\n 'unitPrice', i.unit_price,\n 'discount', i.discount,\n 'total', i.total,\n 'cancelled', i.cancelled_at IS NOT NULL,\n -- The product's own value wins, field by field, over its group's (V1).\n 'tax', CASE WHEN t.product_id IS NULL AND g.id IS NULL THEN NULL ELSE jsonb_build_object(\n 'ncm', t.ncm,\n 'cest', coalesce(t.cest, g.cest),\n 'cfop', coalesce(nullif(t.cfop, ''), g.cfop),\n 'cst', coalesce(nullif(t.cst, ''), g.cst),\n 'csosn', g.csosn,\n 'origin', coalesce(nullif(t.icms_origin, ''), g.icms_origin),\n 'icmsRate', CASE WHEN coalesce(t.icms_rate, 0) > 0 THEN t.icms_rate ELSE g.icms_rate END,\n 'icmsBaseMode', g.icms_bc_mode,\n 'pisSituation', coalesce(nullif(t.pis_situation, ''), g.pis_situation),\n 'pisRate', CASE WHEN coalesce(t.pis_rate, 0) > 0 THEN t.pis_rate ELSE g.pis_rate END,\n 'cofinsSituation', coalesce(nullif(t.cofins_situation, ''), g.cofins_situation),\n 'cofinsRate', CASE WHEN coalesce(t.cofins_rate, 0) > 0 THEN t.cofins_rate ELSE g.cofins_rate END,\n 'ibsCbsSituation', coalesce(nullif(t.ibs_cbs_situation, ''), g.ibs_cbs_situation),\n 'ibsCbsClassification', coalesce(nullif(t.ibs_cbs_classification, ''), g.ibs_cbs_classification),\n 'group', g.name\n ) END\n ) ORDER BY i.sort_order, i.created_at)\n FROM public.items i\n LEFT JOIN public.products p ON p.id = i.product_id AND p.tenant_id = i.tenant_id\n LEFT JOIN public.plg_fiscalbr_product_tax_info t ON t.product_id = i.product_id AND t.tenant_id = i.tenant_id\n LEFT JOIN public.plg_fiscalbr_tax_groups g ON g.id = t.tax_group_id AND g.tenant_id = i.tenant_id\n WHERE i.order_id = o.id AND i.tenant_id = o.tenant_id\n ), '[]'::jsonb),\n -- Anything that is not a site order is paid through the movements the\n -- order received, net of reversals, by method.\n 'checkout', v_checkout,\n 'payments', coalesce((\n SELECT jsonb_agg(jsonb_build_object('method', x.method, 'methodType', x.method_type, 'amount', x.amount))\n FROM (\n SELECT pm.name AS method, pt.name AS method_type,\n sum(CASE WHEN m.direction = 'credit' THEN m.paid_amount ELSE -m.paid_amount END) AS amount\n FROM public.plg_financial_movements m\n LEFT JOIN public.plg_financial_payment_methods pm ON pm.id = m.payment_method_id\n LEFT JOIN public.plg_financial_payment_method_types pt ON pt.id = pm.payment_method_type_id\n WHERE m.tenant_id = o.tenant_id AND m.movement_kind = 'payment' AND m.status = 'paid'\n AND (m.invoice_id = o.id OR m.financial_invoice_id IN (\n SELECT fi.id FROM public.plg_financial_invoices fi WHERE fi.order_id = o.id AND fi.tenant_id = o.tenant_id))\n GROUP BY pm.name, pt.name\n ) x WHERE x.amount <> 0\n ), '[]'::jsonb),\n 'notes', coalesce((\n SELECT jsonb_agg(jsonb_build_object('documentId', d.document_id, 'model', d.model, 'status', d.status))\n FROM public.plg_fiscalbr_documents d\n WHERE d.tenant_id = o.tenant_id AND d.order_id = o.id\n ), '[]'::jsonb)\n )\n FROM public.orders o\n LEFT JOIN app.units u ON u.id = o.unit_id AND u.tenant_id = o.tenant_id\n WHERE o.id = p_order AND o.tenant_id = p_tenant);\nEND\n$$;\n\n-- The note, opened before PlugNotas is called. One live note per order and\n-- model: a second \"Emitir\" while one is processing or authorized is refused\n-- (P0001 note_exists), so a double click never issues twice.\nCREATE OR REPLACE FUNCTION public.fiscalbr_note_open_for_service(\n p_tenant uuid, p_order uuid, p_model text, p_input jsonb\n)\nRETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE\n v_order public.orders%ROWTYPE;\n v_doc uuid := gen_random_uuid();\n v_integration text;\n v_existing uuid;\nBEGIN\n IF p_model NOT IN ('nfce', 'nfe') THEN\n RAISE EXCEPTION 'fiscalbr_note_open: model % is not issued here', p_model USING ERRCODE = '22023';\n END IF;\n SELECT * INTO v_order FROM public.orders WHERE id = p_order AND tenant_id = p_tenant FOR UPDATE;\n IF NOT FOUND THEN\n RAISE EXCEPTION 'fiscalbr_note_open: order % is not of tenant %', p_order, p_tenant USING ERRCODE = 'P0002';\n END IF;\n SELECT document_id INTO v_existing FROM public.plg_fiscalbr_documents\n WHERE tenant_id = p_tenant AND order_id = p_order AND model = p_model AND status IN ('processing', 'authorized')\n LIMIT 1;\n IF v_existing IS NOT NULL THEN\n RAISE EXCEPTION 'note_exists' USING ERRCODE = 'P0001', DETAIL = v_existing::text;\n END IF;\n\n -- Ours, and unique per company at PlugNotas: how a lost answer is found again.\n v_integration := 'csb-' || v_doc::text;\n\n INSERT INTO public.documents (id, tenant_id, kind, title, status, unit_id, subject_type, subject_id, created_by, metadata)\n VALUES (v_doc, p_tenant, 'fiscal_document', upper(p_model) || ' do pedido', 'processing', v_order.unit_id,\n 'order', p_order, nullif(p_input ->> 'userId', '')::uuid, jsonb_build_object('source', 'integration-service'));\n\n INSERT INTO public.plg_fiscalbr_documents (\n document_id, tenant_id, unit_id, order_id, model, environment, status, series, provider,\n provider_integration_id, total_value, recipient_snapshot, request_payload, source_snapshot, emitted_by_user_id, metadata)\n VALUES (\n v_doc, p_tenant, v_order.unit_id, p_order, p_model, p_input ->> 'environment', 'processing', p_input ->> 'series', 'plugnotas',\n v_integration, (p_input ->> 'total')::numeric, p_input -> 'recipient', p_input -> 'request', p_input -> 'source',\n nullif(p_input ->> 'userId', '')::uuid, jsonb_build_object('emitterCnpj', p_input ->> 'emitterCnpj'));\n\n INSERT INTO public.plg_fiscalbr_document_orders (tenant_id, document_id, order_id)\n VALUES (p_tenant, v_doc, p_order);\n\n INSERT INTO public.plg_fiscalbr_document_events (tenant_id, unit_id, document_id, event_type, status, created_by_user_id)\n VALUES (p_tenant, v_order.unit_id, v_doc, 'issue_requested', 'processing', nullif(p_input ->> 'userId', '')::uuid);\n\n RETURN jsonb_build_object('documentId', v_doc, 'integrationId', v_integration);\nEND\n$$;\n\n-- What PlugNotas answered, on the note and on its public.documents row (the\n-- same note seen from two places, 005). Identity (model, unit, order) never moves.\nCREATE OR REPLACE FUNCTION public.fiscalbr_note_apply_for_service(\n p_tenant uuid, p_document uuid, p_patch jsonb, p_event jsonb DEFAULT NULL\n)\nRETURNS void\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE\n v public.plg_fiscalbr_documents%ROWTYPE;\n v_status text := p_patch ->> 'status';\nBEGIN\n SELECT * INTO v FROM public.plg_fiscalbr_documents\n WHERE document_id = p_document AND tenant_id = p_tenant FOR UPDATE;\n IF NOT FOUND THEN\n RAISE EXCEPTION 'fiscalbr_note_apply: note % is not of tenant %', p_document, p_tenant USING ERRCODE = 'P0002';\n END IF;\n IF v_status IS NOT NULL AND v_status NOT IN ('processing', 'authorized', 'rejected', 'error', 'cancelled', 'substituted') THEN\n RAISE EXCEPTION 'fiscalbr_note_apply: unknown status %', v_status USING ERRCODE = '22023';\n END IF;\n\n UPDATE public.plg_fiscalbr_documents SET\n status = coalesce(v_status, status),\n number = coalesce(p_patch ->> 'number', number),\n series = coalesce(p_patch ->> 'series', series),\n access_key = coalesce(p_patch ->> 'access_key', access_key),\n protocol = coalesce(p_patch ->> 'protocol', protocol),\n provider_document_id = coalesce(p_patch ->> 'provider_document_id', provider_document_id),\n response_payload = coalesce(p_patch -> 'response_payload', response_payload),\n status_payload = coalesce(p_patch -> 'status_payload', status_payload),\n rejection_payload = CASE WHEN p_patch ? 'rejection_payload' THEN p_patch -> 'rejection_payload' ELSE rejection_payload END,\n xml = coalesce(p_patch ->> 'xml', xml),\n authorized_at = coalesce((p_patch ->> 'authorized_at')::timestamptz, authorized_at),\n last_polled_at = CASE WHEN p_patch ? 'polled' THEN now() ELSE last_polled_at END,\n cancelled_at = CASE WHEN p_patch ? 'cancelled_at' THEN (p_patch ->> 'cancelled_at')::timestamptz ELSE cancelled_at END,\n cancel_reason = CASE WHEN p_patch ? 'cancel_reason' THEN p_patch ->> 'cancel_reason' ELSE cancel_reason END,\n cancelled_by_user_id = CASE WHEN p_patch ? 'cancelled_by_user_id' THEN nullif(p_patch ->> 'cancelled_by_user_id', '')::uuid ELSE cancelled_by_user_id END,\n metadata = metadata || coalesce(p_patch -> 'metadata', '{}'::jsonb)\n WHERE document_id = p_document;\n\n IF v_status IS NOT NULL THEN\n UPDATE public.documents SET status = v_status WHERE id = p_document AND status IS DISTINCT FROM v_status;\n END IF;\n\n IF p_event IS NOT NULL THEN\n INSERT INTO public.plg_fiscalbr_document_events\n (tenant_id, unit_id, document_id, event_type, status, justification, response_payload, created_by_user_id)\n VALUES (v.tenant_id, v.unit_id, p_document, p_event ->> 'event_type', p_event ->> 'status',\n p_event ->> 'justification', p_event -> 'response_payload', nullif(p_event ->> 'userId', '')::uuid);\n END IF;\nEND\n$$;\n\nCREATE OR REPLACE FUNCTION public.fiscalbr_note_for_service(p_tenant uuid, p_document uuid)\nRETURNS jsonb\nLANGUAGE sql STABLE SECURITY DEFINER\nSET search_path TO ''\nAS $$\n SELECT jsonb_build_object(\n 'documentId', d.document_id, 'tenantId', d.tenant_id, 'unitId', d.unit_id, 'orderId', d.order_id,\n 'model', d.model, 'environment', d.environment, 'status', d.status, 'series', d.series, 'number', d.number,\n 'accessKey', d.access_key, 'protocol', d.protocol, 'provider', d.provider,\n 'providerDocumentId', d.provider_document_id, 'integrationId', d.provider_integration_id,\n 'total', d.total_value, 'recipient', d.recipient_snapshot, 'rejection', d.rejection_payload,\n 'hasXml', d.xml IS NOT NULL, 'authorizedAt', d.authorized_at, 'lastPolledAt', d.last_polled_at,\n 'cancelledAt', d.cancelled_at, 'cancelReason', d.cancel_reason, 'createdAt', d.created_at,\n 'emitterCnpj', d.metadata ->> 'emitterCnpj', 'metadata', d.metadata)\n FROM public.plg_fiscalbr_documents d\n WHERE d.document_id = p_document AND d.tenant_id = p_tenant\n$$;\n\nCREATE OR REPLACE FUNCTION public.fiscalbr_notes_for_service(p_tenant uuid, p_order uuid)\nRETURNS SETOF jsonb\nLANGUAGE sql STABLE SECURITY DEFINER\nSET search_path TO ''\nAS $$\n SELECT public.fiscalbr_note_for_service(p_tenant, d.document_id)\n FROM public.plg_fiscalbr_documents d\n WHERE d.tenant_id = p_tenant AND d.order_id = p_order\n ORDER BY d.created_at DESC\n$$;\n\n-- The XML is large and read only on download.\nCREATE OR REPLACE FUNCTION public.fiscalbr_note_xml_for_service(p_tenant uuid, p_document uuid)\nRETURNS text\nLANGUAGE sql STABLE SECURITY DEFINER\nSET search_path TO ''\nAS $$\n SELECT d.xml FROM public.plg_fiscalbr_documents d WHERE d.document_id = p_document AND d.tenant_id = p_tenant\n$$;\n\n-- Where a PlugNotas webhook belongs: our idIntegracao names the note.\nCREATE OR REPLACE FUNCTION public.fiscalbr_note_by_integration_for_service(p_integration text)\nRETURNS jsonb\nLANGUAGE sql STABLE SECURITY DEFINER\nSET search_path TO ''\nAS $$\n SELECT jsonb_build_object('tenantId', d.tenant_id, 'documentId', d.document_id)\n FROM public.plg_fiscalbr_documents d\n WHERE d.provider_integration_id = p_integration AND d.provider = 'plugnotas'\n LIMIT 1\n$$;\n\n-- Notes this service sent that PlugNotas has not settled: the fallback when a\n-- webhook does not arrive. Oldest poll first.\nCREATE OR REPLACE FUNCTION public.fiscalbr_notes_to_follow_for_service(p_limit integer DEFAULT 25)\nRETURNS SETOF jsonb\nLANGUAGE sql STABLE SECURITY DEFINER\nSET search_path TO ''\nAS $$\n SELECT public.fiscalbr_note_for_service(d.tenant_id, d.document_id)\n FROM public.plg_fiscalbr_documents d\n WHERE d.provider = 'plugnotas' AND d.status = 'processing' AND d.provider_integration_id LIKE 'csb-%'\n AND d.created_at > now() - interval '7 days'\n ORDER BY coalesce(d.last_polled_at, d.created_at)\n LIMIT greatest(1, least(p_limit, 100))\n$$;\n\nDO $$\nDECLARE\n f text;\nBEGIN\n FOREACH f IN ARRAY ARRAY[\n 'public.fiscalbr_order_for_note_for_service(uuid, uuid)',\n 'public.fiscalbr_note_open_for_service(uuid, uuid, text, jsonb)',\n 'public.fiscalbr_note_apply_for_service(uuid, uuid, jsonb, jsonb)',\n 'public.fiscalbr_note_for_service(uuid, uuid)',\n 'public.fiscalbr_notes_for_service(uuid, uuid)',\n 'public.fiscalbr_note_xml_for_service(uuid, uuid)',\n 'public.fiscalbr_notes_to_follow_for_service(integer)',\n 'public.fiscalbr_note_by_integration_for_service(text)'\n ] LOOP\n EXECUTE format('REVOKE ALL ON FUNCTION %s FROM PUBLIC, anon, authenticated', f);\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'fayz_integration') THEN\n EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO fayz_integration', f);\n END IF;\n END LOOP;\nEND\n$$;\n";
|
|
33
33
|
export declare const MIGRATION_032_A_DELIVERED_NOTE_CARRIES_WHERE_IT_GOES = "-- ============================================================================\n-- 032 \u2014 a home-delivery NFC-e carries where it goes\n--\n-- The SEFAZ rejected Artorius' NFC-e delivered at home with \"NFC-e de entrega\n-- a domicilio sem o endereco do destinatario\": indPres 4 requires the\n-- recipient's address. The order's source for its note now carries the\n-- checkout's delivery address and the customer's email; the integration\n-- service adds the city's IBGE code (control-sdk-backend ADR 0008).\n-- ============================================================================\n\nCREATE OR REPLACE FUNCTION public.fiscalbr_order_for_note_for_service(p_tenant uuid, p_order uuid)\nRETURNS jsonb\nLANGUAGE plpgsql STABLE SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE\n v_checkout jsonb;\nBEGIN\n -- The shop is optional: a site order says how it was paid on its checkout,\n -- read only where the shop's table exists.\n IF to_regclass('public.plg_shop_checkout_sessions') IS NOT NULL THEN\n EXECUTE $q$\n SELECT jsonb_build_object(\n 'paymentMethod', s.payment_method, 'provider', s.provider, 'total', s.total, 'status', s.status,\n 'customerName', s.customer_name, 'customerDocument', s.customer_document,\n 'destinationState', s.shipping_address ->> 'state', 'destinationCity', s.shipping_address ->> 'city',\n 'customerEmail', s.customer_email,\n 'shippingAddress', CASE WHEN s.shipping_address IS NULL THEN NULL ELSE jsonb_build_object(\n 'street', s.shipping_address ->> 'street', 'number', s.shipping_address ->> 'number',\n 'complement', s.shipping_address ->> 'complement', 'district', s.shipping_address ->> 'district',\n 'city', s.shipping_address ->> 'city', 'state', s.shipping_address ->> 'state',\n 'postalCode', coalesce(s.shipping_address ->> 'postalCode', s.shipping_address ->> 'postal_code')) END)\n FROM public.plg_shop_checkout_sessions s\n WHERE s.order_id = $1 AND s.tenant_id = $2 AND s.status = 'paid'\n ORDER BY s.updated_at DESC LIMIT 1 $q$\n INTO v_checkout USING p_order, p_tenant;\n END IF;\n\n RETURN (SELECT jsonb_build_object(\n 'orderId', o.id,\n 'tenantId', o.tenant_id,\n 'unitId', o.unit_id,\n 'kind', o.kind,\n 'status', o.status,\n 'channel', o.channel,\n 'createdAt', o.created_at,\n 'subtotal', o.subtotal,\n 'discount', o.discount,\n 'shipping', o.shipping,\n 'total', o.total,\n 'legalEntityId', u.company_legal_entity_id,\n 'items', coalesce((\n SELECT jsonb_agg(jsonb_build_object(\n 'itemId', i.id,\n 'productId', i.product_id,\n 'code', coalesce(nullif(p.sku, ''), i.product_id::text, i.id::text),\n 'name', i.name,\n 'quantity', i.quantity,\n 'unitPrice', i.unit_price,\n 'discount', i.discount,\n 'total', i.total,\n 'cancelled', i.cancelled_at IS NOT NULL,\n -- The product's own value wins, field by field, over its group's (V1).\n 'tax', CASE WHEN t.product_id IS NULL AND g.id IS NULL THEN NULL ELSE jsonb_build_object(\n 'ncm', t.ncm,\n 'cest', coalesce(t.cest, g.cest),\n 'cfop', coalesce(nullif(t.cfop, ''), g.cfop),\n 'cst', coalesce(nullif(t.cst, ''), g.cst),\n 'csosn', g.csosn,\n 'origin', coalesce(nullif(t.icms_origin, ''), g.icms_origin),\n 'icmsRate', CASE WHEN coalesce(t.icms_rate, 0) > 0 THEN t.icms_rate ELSE g.icms_rate END,\n 'icmsBaseMode', g.icms_bc_mode,\n 'pisSituation', coalesce(nullif(t.pis_situation, ''), g.pis_situation),\n 'pisRate', CASE WHEN coalesce(t.pis_rate, 0) > 0 THEN t.pis_rate ELSE g.pis_rate END,\n 'cofinsSituation', coalesce(nullif(t.cofins_situation, ''), g.cofins_situation),\n 'cofinsRate', CASE WHEN coalesce(t.cofins_rate, 0) > 0 THEN t.cofins_rate ELSE g.cofins_rate END,\n 'ibsCbsSituation', coalesce(nullif(t.ibs_cbs_situation, ''), g.ibs_cbs_situation),\n 'ibsCbsClassification', coalesce(nullif(t.ibs_cbs_classification, ''), g.ibs_cbs_classification),\n 'group', g.name\n ) END\n ) ORDER BY i.sort_order, i.created_at)\n FROM public.items i\n LEFT JOIN public.products p ON p.id = i.product_id AND p.tenant_id = i.tenant_id\n LEFT JOIN public.plg_fiscalbr_product_tax_info t ON t.product_id = i.product_id AND t.tenant_id = i.tenant_id\n LEFT JOIN public.plg_fiscalbr_tax_groups g ON g.id = t.tax_group_id AND g.tenant_id = i.tenant_id\n WHERE i.order_id = o.id AND i.tenant_id = o.tenant_id\n ), '[]'::jsonb),\n -- Anything that is not a site order is paid through the movements the\n -- order received, net of reversals, by method.\n 'checkout', v_checkout,\n 'payments', coalesce((\n SELECT jsonb_agg(jsonb_build_object('method', x.method, 'methodType', x.method_type, 'amount', x.amount))\n FROM (\n SELECT pm.name AS method, pt.name AS method_type,\n sum(CASE WHEN m.direction = 'credit' THEN m.paid_amount ELSE -m.paid_amount END) AS amount\n FROM public.plg_financial_movements m\n LEFT JOIN public.plg_financial_payment_methods pm ON pm.id = m.payment_method_id\n LEFT JOIN public.plg_financial_payment_method_types pt ON pt.id = pm.payment_method_type_id\n WHERE m.tenant_id = o.tenant_id AND m.movement_kind = 'payment' AND m.status = 'paid'\n AND (m.invoice_id = o.id OR m.financial_invoice_id IN (\n SELECT fi.id FROM public.plg_financial_invoices fi WHERE fi.order_id = o.id AND fi.tenant_id = o.tenant_id))\n GROUP BY pm.name, pt.name\n ) x WHERE x.amount <> 0\n ), '[]'::jsonb),\n 'notes', coalesce((\n SELECT jsonb_agg(jsonb_build_object('documentId', d.document_id, 'model', d.model, 'status', d.status))\n FROM public.plg_fiscalbr_documents d\n WHERE d.tenant_id = o.tenant_id AND d.order_id = o.id\n ), '[]'::jsonb)\n )\n FROM public.orders o\n LEFT JOIN app.units u ON u.id = o.unit_id AND u.tenant_id = o.tenant_id\n WHERE o.id = p_order AND o.tenant_id = p_tenant);\nEND\n$$;\n\nREVOKE ALL ON FUNCTION public.fiscalbr_order_for_note_for_service(uuid, uuid) FROM PUBLIC, anon, authenticated;\nDO $$\nBEGIN\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'fayz_integration') THEN\n GRANT EXECUTE ON FUNCTION public.fiscalbr_order_for_note_for_service(uuid, uuid) TO fayz_integration;\n END IF;\nEND\n$$;\n";
|
|
34
34
|
export declare const MIGRATION_033_A_COMPANY_BUYER_GETS_ITS_NFE = "-- ============================================================================\n-- 033 \u2014 a company buyer gets its NF-e\n--\n-- control-sdk-backend ADR 0008, decisions 15 to 23: the operator chooses, on\n-- the order, between the NFC-e (a consumer) and the NF-e (model 55, the DANFE\n-- a company books). Artorius sells to restaurants and mini-markets. An NF-e\n-- names its buyer, so the order's source for its note now carries who the\n-- order is with (`orders.party_id`): document, legal name, email, state\n-- registration and address. The integration service applies the rules; this\n-- only gathers.\n--\n-- Where each piece comes from:\n-- * state registration: `custom_fields.stateRegistration`, then the\n-- supplier form's `registrationNumber`, then the V1's\n-- `metadata.legal.state_registration`, then \u2014 only for a CNPJ \u2014 the\n-- V1 client's `rg`, which the V1 used to hold a company client's IE\n-- (beautyplace src/lib/clientPersonType.ts) and the import kept in\n-- `metadata.documents.rg`.\n-- * address: the person's address book (`public.addresses`), fiscal first,\n-- then billing, then the default; else the legacy fields the import left\n-- on the person.\n--\n-- And one sale, one note: a note of either model is opened only while the\n-- order has no live note of the OTHER model either, so a double click on\n-- \"Emitir NF-e\" and \"Emitir NFC-e\" never issues both.\n--\n-- Additive: two CREATE OR REPLACE FUNCTION, same signatures and grants.\n-- ============================================================================\n\nCREATE OR REPLACE FUNCTION public.fiscalbr_order_for_note_for_service(p_tenant uuid, p_order uuid)\nRETURNS jsonb\nLANGUAGE plpgsql STABLE SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE\n v_checkout jsonb;\nBEGIN\n -- The shop is optional: a site order says how it was paid on its checkout,\n -- read only where the shop's table exists.\n IF to_regclass('public.plg_shop_checkout_sessions') IS NOT NULL THEN\n EXECUTE $q$\n SELECT jsonb_build_object(\n 'paymentMethod', s.payment_method, 'provider', s.provider, 'total', s.total, 'status', s.status,\n 'customerName', s.customer_name, 'customerDocument', s.customer_document,\n 'destinationState', s.shipping_address ->> 'state', 'destinationCity', s.shipping_address ->> 'city',\n 'customerEmail', s.customer_email,\n 'shippingAddress', CASE WHEN s.shipping_address IS NULL THEN NULL ELSE jsonb_build_object(\n 'street', s.shipping_address ->> 'street', 'number', s.shipping_address ->> 'number',\n 'complement', s.shipping_address ->> 'complement', 'district', s.shipping_address ->> 'district',\n 'city', s.shipping_address ->> 'city', 'state', s.shipping_address ->> 'state',\n 'postalCode', coalesce(s.shipping_address ->> 'postalCode', s.shipping_address ->> 'postal_code')) END)\n FROM public.plg_shop_checkout_sessions s\n WHERE s.order_id = $1 AND s.tenant_id = $2 AND s.status = 'paid'\n ORDER BY s.updated_at DESC LIMIT 1 $q$\n INTO v_checkout USING p_order, p_tenant;\n END IF;\n\n RETURN (SELECT jsonb_build_object(\n 'orderId', o.id,\n 'tenantId', o.tenant_id,\n 'unitId', o.unit_id,\n 'kind', o.kind,\n 'status', o.status,\n 'channel', o.channel,\n 'createdAt', o.created_at,\n 'subtotal', o.subtotal,\n 'discount', o.discount,\n 'shipping', o.shipping,\n 'total', o.total,\n 'legalEntityId', u.company_legal_entity_id,\n 'items', coalesce((\n SELECT jsonb_agg(jsonb_build_object(\n 'itemId', i.id,\n 'productId', i.product_id,\n 'code', coalesce(nullif(p.sku, ''), i.product_id::text, i.id::text),\n 'name', i.name,\n 'quantity', i.quantity,\n 'unitPrice', i.unit_price,\n 'discount', i.discount,\n 'total', i.total,\n 'cancelled', i.cancelled_at IS NOT NULL,\n -- The product's own value wins, field by field, over its group's (V1).\n 'tax', CASE WHEN t.product_id IS NULL AND g.id IS NULL THEN NULL ELSE jsonb_build_object(\n 'ncm', t.ncm,\n 'cest', coalesce(t.cest, g.cest),\n 'cfop', coalesce(nullif(t.cfop, ''), g.cfop),\n 'cst', coalesce(nullif(t.cst, ''), g.cst),\n 'csosn', g.csosn,\n 'origin', coalesce(nullif(t.icms_origin, ''), g.icms_origin),\n 'icmsRate', CASE WHEN coalesce(t.icms_rate, 0) > 0 THEN t.icms_rate ELSE g.icms_rate END,\n 'icmsBaseMode', g.icms_bc_mode,\n 'pisSituation', coalesce(nullif(t.pis_situation, ''), g.pis_situation),\n 'pisRate', CASE WHEN coalesce(t.pis_rate, 0) > 0 THEN t.pis_rate ELSE g.pis_rate END,\n 'cofinsSituation', coalesce(nullif(t.cofins_situation, ''), g.cofins_situation),\n 'cofinsRate', CASE WHEN coalesce(t.cofins_rate, 0) > 0 THEN t.cofins_rate ELSE g.cofins_rate END,\n 'ibsCbsSituation', coalesce(nullif(t.ibs_cbs_situation, ''), g.ibs_cbs_situation),\n 'ibsCbsClassification', coalesce(nullif(t.ibs_cbs_classification, ''), g.ibs_cbs_classification),\n 'group', g.name\n ) END\n ) ORDER BY i.sort_order, i.created_at)\n FROM public.items i\n LEFT JOIN public.products p ON p.id = i.product_id AND p.tenant_id = i.tenant_id\n LEFT JOIN public.plg_fiscalbr_product_tax_info t ON t.product_id = i.product_id AND t.tenant_id = i.tenant_id\n LEFT JOIN public.plg_fiscalbr_tax_groups g ON g.id = t.tax_group_id AND g.tenant_id = i.tenant_id\n WHERE i.order_id = o.id AND i.tenant_id = o.tenant_id\n ), '[]'::jsonb),\n -- Who the order is with: the buyer an NF-e names.\n 'customer', (\n SELECT jsonb_build_object(\n 'personId', c.id,\n 'name', c.name,\n 'document', c.document_number,\n 'email', c.email,\n 'stateRegistration', coalesce(\n nullif(btrim(c.custom_fields ->> 'stateRegistration'), ''),\n nullif(btrim(c.custom_fields ->> 'registrationNumber'), ''),\n nullif(btrim(c.metadata #>> '{legal,state_registration}'), ''),\n CASE WHEN length(regexp_replace(coalesce(c.document_number, ''), '\\D', '', 'g')) = 14\n THEN nullif(btrim(c.metadata #>> '{documents,rg}'), '') END),\n 'address', coalesce(\n (SELECT jsonb_build_object(\n 'street', a.street, 'number', a.number, 'complement', a.complement, 'district', a.district,\n 'city', a.city, 'state', a.state, 'postalCode', a.postal_code)\n FROM public.addresses a\n WHERE a.tenant_id = c.tenant_id AND a.owner_type = 'person' AND a.owner_id = c.id\n ORDER BY (a.kind = 'fiscal') DESC, (a.kind = 'billing') DESC, a.is_default DESC,\n (a.kind IN ('main', 'both')) DESC, a.updated_at DESC\n LIMIT 1),\n CASE WHEN nullif(btrim(c.address), '') IS NOT NULL THEN jsonb_build_object(\n 'street', c.address, 'number', c.metadata #>> '{address,number}',\n 'complement', c.metadata #>> '{address,complement}', 'district', c.metadata #>> '{address,neighborhood}',\n 'city', c.city, 'state', c.state, 'postalCode', c.postal_code) END)\n )\n FROM public.people c\n WHERE c.id = o.party_id AND c.tenant_id = o.tenant_id\n ),\n -- Anything that is not a site order is paid through the movements the\n -- order received, net of reversals, by method.\n 'checkout', v_checkout,\n 'payments', coalesce((\n SELECT jsonb_agg(jsonb_build_object('method', x.method, 'methodType', x.method_type, 'amount', x.amount))\n FROM (\n SELECT pm.name AS method, pt.name AS method_type,\n sum(CASE WHEN m.direction = 'credit' THEN m.paid_amount ELSE -m.paid_amount END) AS amount\n FROM public.plg_financial_movements m\n LEFT JOIN public.plg_financial_payment_methods pm ON pm.id = m.payment_method_id\n LEFT JOIN public.plg_financial_payment_method_types pt ON pt.id = pm.payment_method_type_id\n WHERE m.tenant_id = o.tenant_id AND m.movement_kind = 'payment' AND m.status = 'paid'\n AND (m.invoice_id = o.id OR m.financial_invoice_id IN (\n SELECT fi.id FROM public.plg_financial_invoices fi WHERE fi.order_id = o.id AND fi.tenant_id = o.tenant_id))\n GROUP BY pm.name, pt.name\n ) x WHERE x.amount <> 0\n ), '[]'::jsonb),\n 'notes', coalesce((\n SELECT jsonb_agg(jsonb_build_object('documentId', d.document_id, 'model', d.model, 'status', d.status))\n FROM public.plg_fiscalbr_documents d\n WHERE d.tenant_id = o.tenant_id AND d.order_id = o.id\n ), '[]'::jsonb)\n )\n FROM public.orders o\n LEFT JOIN app.units u ON u.id = o.unit_id AND u.tenant_id = o.tenant_id\n WHERE o.id = p_order AND o.tenant_id = p_tenant);\nEND\n$$;\n\n-- The note, opened before PlugNotas is called. One live note per order,\n-- whatever the model: a second \"Emitir\" while one is processing or authorized\n-- is refused (P0001 note_exists), so a double click never issues twice and an\n-- order never carries an NFC-e and an NF-e at once.\nCREATE OR REPLACE FUNCTION public.fiscalbr_note_open_for_service(\n p_tenant uuid, p_order uuid, p_model text, p_input jsonb\n)\nRETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE\n v_order public.orders%ROWTYPE;\n v_doc uuid := gen_random_uuid();\n v_integration text;\n v_existing uuid;\nBEGIN\n IF p_model NOT IN ('nfce', 'nfe') THEN\n RAISE EXCEPTION 'fiscalbr_note_open: model % is not issued here', p_model USING ERRCODE = '22023';\n END IF;\n SELECT * INTO v_order FROM public.orders WHERE id = p_order AND tenant_id = p_tenant FOR UPDATE;\n IF NOT FOUND THEN\n RAISE EXCEPTION 'fiscalbr_note_open: order % is not of tenant %', p_order, p_tenant USING ERRCODE = 'P0002';\n END IF;\n SELECT document_id INTO v_existing FROM public.plg_fiscalbr_documents\n WHERE tenant_id = p_tenant AND order_id = p_order AND model IN ('nfce', 'nfe') AND status IN ('processing', 'authorized')\n LIMIT 1;\n IF v_existing IS NOT NULL THEN\n RAISE EXCEPTION 'note_exists' USING ERRCODE = 'P0001', DETAIL = v_existing::text;\n END IF;\n\n -- Ours, and unique per company at PlugNotas: how a lost answer is found again.\n v_integration := 'csb-' || v_doc::text;\n\n INSERT INTO public.documents (id, tenant_id, kind, title, status, unit_id, subject_type, subject_id, created_by, metadata)\n VALUES (v_doc, p_tenant, 'fiscal_document', CASE p_model WHEN 'nfe' THEN 'NF-e' ELSE 'NFC-e' END || ' do pedido', 'processing', v_order.unit_id,\n 'order', p_order, nullif(p_input ->> 'userId', '')::uuid, jsonb_build_object('source', 'integration-service'));\n\n INSERT INTO public.plg_fiscalbr_documents (\n document_id, tenant_id, unit_id, order_id, model, environment, status, series, provider,\n provider_integration_id, total_value, recipient_snapshot, request_payload, source_snapshot, emitted_by_user_id, metadata)\n VALUES (\n v_doc, p_tenant, v_order.unit_id, p_order, p_model, p_input ->> 'environment', 'processing', p_input ->> 'series', 'plugnotas',\n v_integration, (p_input ->> 'total')::numeric, p_input -> 'recipient', p_input -> 'request', p_input -> 'source',\n nullif(p_input ->> 'userId', '')::uuid, jsonb_build_object('emitterCnpj', p_input ->> 'emitterCnpj'));\n\n INSERT INTO public.plg_fiscalbr_document_orders (tenant_id, document_id, order_id)\n VALUES (p_tenant, v_doc, p_order);\n\n INSERT INTO public.plg_fiscalbr_document_events (tenant_id, unit_id, document_id, event_type, status, created_by_user_id)\n VALUES (p_tenant, v_order.unit_id, v_doc, 'issue_requested', 'processing', nullif(p_input ->> 'userId', '')::uuid);\n\n RETURN jsonb_build_object('documentId', v_doc, 'integrationId', v_integration);\nEND\n$$;\n\nDO $$\nDECLARE\n f text;\nBEGIN\n FOREACH f IN ARRAY ARRAY[\n 'public.fiscalbr_order_for_note_for_service(uuid, uuid)',\n 'public.fiscalbr_note_open_for_service(uuid, uuid, text, jsonb)'\n ] LOOP\n EXECUTE format('REVOKE ALL ON FUNCTION %s FROM PUBLIC, anon, authenticated', f);\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'fayz_integration') THEN\n EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO fayz_integration', f);\n END IF;\n END LOOP;\nEND\n$$;\n";
|
|
35
|
+
export declare const MIGRATION_034_ONLY_WHAT_ARRIVED_ENTERS_STOCK = "-- ============================================================================\n-- 034 \u2014 only what arrived enters stock\n--\n-- Artorius accepted a Rio Quality note where a box of milk never came, and the\n-- milk went into stock anyway: accepting a note brought in every line as the\n-- note reads.\n--\n-- V1 contract: beautyplace #1031 (\"Nota de compra, fase 3\", migration\n-- 20261020160000, src/lib/danfeReceipt.ts, danfeStockEntry.ts):\n--\n-- * whoever receives the goods records, per line, how much did NOT arrive \u2014\n-- in the NOTE's unit (8 UN, 3 CX: the paper in their hand) \u2014 with a reason\n-- (faltou | avariado | vencido | recusado | outro) and a free note;\n-- * stock takes only what arrived: stock quantity \u00D7 (1 \u2212 missing / billed).\n-- What is missing is not \"to be received later\" \u2014 it is not coming;\n-- * a line where nothing arrived enters nothing and asks for nothing\n-- (no unit, no product to name);\n-- * once the note entered stock the receipt no longer changes;\n-- * the payable is still born at the note's FULL value, and the finance\n-- person abates what did not arrive from it (financial/137,\n-- `financial_abate_invoice_item`). What is still to abate is derived \u2014\n-- line total \u2212 value received \u2014 so it cannot drift.\n--\n-- V2 already had the three columns (008) and a \"Falta (qtd)\" box, but the box\n-- was in STOCK units, subtracted only when the decision was saved, with no\n-- reason, no note and nothing on the payable. This file:\n--\n-- 1. converts what was recorded in stock units to note units (once \u2014 the\n-- block is skipped when the new save function is already in place);\n-- 2. constrains the reason vocabulary and the range;\n-- 3. rewrites fiscalbr_save_inbox_decision: the receipt travels under a NEW\n-- key, `missing_quantity` (note units), with `shortage_reason` and\n-- `shortage_note`. A payload without that key leaves the receipt as it\n-- is \u2014 so an app still on an older plugin, which sends the old\n-- stock-unit `shortage_quantity`, can no longer write a wrong number.\n-- `stock_quantity` goes back to what was billed (quantity \u00D7 factor);\n-- 4. rewrites fiscalbr_accept_inbox_document as a whole (it had been patched\n-- in place by 015, 021, 025, 027 and 028; this is that body plus the\n-- receipt): each stock line enters as stock_quantity \u00D7 received fraction,\n-- fully-missing lines are skipped, the payable line remembers which note\n-- line it came from (`inboxItemId`), and the result says how many lines\n-- came short and for how much;\n-- 5. adds fiscalbr_note_receipt_occurrences(invoice): what did not arrive,\n-- per line of the payable, and how much is still to abate.\n--\n-- Replay-safe: the conversion is gated, everything else is CREATE OR REPLACE\n-- or guarded DDL.\n-- ============================================================================\n\n-- \u2500\u2500 1. What was recorded in stock units becomes note units \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nDO $m$\nDECLARE v_def text;\nBEGIN\n SELECT pg_get_functiondef(p.oid) INTO v_def FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = 'public' AND p.proname = 'fiscalbr_save_inbox_decision';\n IF v_def IS NOT NULL AND position('missing_quantity' in v_def) > 0 THEN RETURN; END IF;\n\n -- The old save wrote stock_quantity = billed \u00D7 factor \u2212 missing(stock units).\n -- missing / factor is the same goods in the note's unit, and billed \u00D7 factor\n -- is what stock_quantity means from here on; the accepted quantity is unchanged.\n UPDATE public.plg_fiscalbr_inbox_items\n SET shortage_quantity = round(shortage_quantity / conversion_factor, 4),\n updated_at = now()\n WHERE shortage_quantity > 0 AND conversion_factor > 0 AND conversion_factor <> 1;\n UPDATE public.plg_fiscalbr_inbox_items\n SET stock_quantity = quantity_commercial * conversion_factor,\n shortage_reason = coalesce(shortage_reason, 'faltou'),\n updated_at = now()\n WHERE shortage_quantity > 0 AND stock_movement_id IS NULL;\n UPDATE public.plg_fiscalbr_inbox_items\n SET shortage_quantity = NULL, shortage_reason = NULL, shortage_note = NULL, updated_at = now()\n WHERE shortage_quantity IS NOT NULL AND shortage_quantity <= 0;\n UPDATE public.plg_fiscalbr_inbox_items\n SET shortage_quantity = quantity_commercial, updated_at = now()\n WHERE shortage_quantity > quantity_commercial;\nEND\n$m$;\n\n-- \u2500\u2500 2. The vocabulary and the range \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- NOT VALID: rows from before this file are not re-judged; every write is.\nALTER TABLE public.plg_fiscalbr_inbox_items DROP CONSTRAINT IF EXISTS plg_fiscalbr_inbox_items_shortage_chk;\nALTER TABLE public.plg_fiscalbr_inbox_items ADD CONSTRAINT plg_fiscalbr_inbox_items_shortage_chk CHECK (\n (shortage_quantity IS NULL OR (shortage_quantity > 0 AND shortage_quantity <= quantity_commercial))\n AND (shortage_reason IS NULL OR shortage_reason IN ('faltou', 'avariado', 'vencido', 'recusado', 'outro'))\n) NOT VALID;\n\nCOMMENT ON COLUMN public.plg_fiscalbr_inbox_items.shortage_quantity IS\n 'Receipt check: how much of this line did NOT arrive, in the note''s unit. Stock takes only what arrived.';\nCOMMENT ON COLUMN public.plg_fiscalbr_inbox_items.shortage_reason IS\n 'faltou | avariado | vencido | recusado | outro';\nCOMMENT ON COLUMN public.plg_fiscalbr_inbox_items.stock_quantity IS\n 'What the note bills, in stock units (quantity \u00D7 conversion factor). What enters is this \u00D7 the received fraction.';\n\n-- \u2500\u2500 3. Saving the decision carries the receipt \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nCREATE OR REPLACE FUNCTION public.fiscalbr_save_inbox_decision(\n p_document_id uuid,\n p_items jsonb,\n p_default_chart_account_id uuid DEFAULT NULL,\n p_default_location_id uuid DEFAULT NULL,\n p_duplicates jsonb DEFAULT NULL)\nRETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO '' AS $function$\nDECLARE\n v_tenant uuid := public.plg_financial_require_tenant();\n v_doc public.plg_fiscalbr_inbox_documents%ROWTYPE;\n v_row jsonb;\n v_done integer := 0;\n v_total integer;\n v_line public.plg_fiscalbr_inbox_items%ROWTYPE;\n v_missing numeric;\n v_reason text;\nBEGIN\n SELECT * INTO v_doc FROM public.plg_fiscalbr_inbox_documents\n WHERE tenant_id = v_tenant AND id = p_document_id;\n IF NOT FOUND THEN\n RAISE EXCEPTION 'fiscalbr: nota % n\u00E3o encontrada neste tenant', p_document_id USING ERRCODE = 'P0002';\n END IF;\n PERFORM public.plg_financial_require_permission('financial.edit', v_doc.unit_id);\n\n -- Settled = stocked, or a payable with no stock line left to receive (027).\n IF v_doc.stocked_at IS NOT NULL OR (v_doc.invoice_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM public.plg_fiscalbr_inbox_items x\n WHERE x.tenant_id = v_tenant AND x.inbox_document_id = v_doc.id\n AND x.stock_movement_id IS NULL\n AND (x.entry_type IS NULL OR x.entry_type = '' OR x.entry_type IN ('insumo','revenda','patrimonio','uso_consumo')))) THEN\n RAISE EXCEPTION 'fiscalbr: nota % j\u00E1 foi aceita \u2014 a decis\u00E3o n\u00E3o muda depois do estoque', p_document_id\n USING ERRCODE = '23514';\n END IF;\n\n UPDATE public.plg_fiscalbr_inbox_documents SET\n default_chart_account_id = coalesce(p_default_chart_account_id, default_chart_account_id),\n default_location_id = coalesce(p_default_location_id, default_location_id),\n reviewed_at = now(), updated_at = now()\n WHERE id = v_doc.id;\n\n FOR v_row IN SELECT * FROM jsonb_array_elements(coalesce(p_items, '[]'::jsonb)) LOOP\n SELECT * INTO v_line FROM public.plg_fiscalbr_inbox_items\n WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id AND id = (v_row->>'id')::uuid;\n CONTINUE WHEN NOT FOUND;\n\n -- The receipt: only a payload that names `missing_quantity` (note units)\n -- writes it. Without the key it stays as it is.\n v_missing := CASE WHEN v_line.shortage_quantity > 0\n THEN least(v_line.shortage_quantity, v_line.quantity_commercial) END;\n v_reason := CASE WHEN v_missing IS NOT NULL THEN coalesce(v_line.shortage_reason, 'faltou') END;\n IF v_row ? 'missing_quantity' THEN\n BEGIN\n v_missing := nullif(v_row->>'missing_quantity', '')::numeric;\n EXCEPTION WHEN OTHERS THEN\n RAISE EXCEPTION 'fiscalbr: item %: missing quantity is not a number', v_line.item_number\n USING ERRCODE = '22023', HINT = 'RECEIPT_BAD_QUANTITY';\n END;\n IF v_missing IS NOT NULL AND v_missing <= 0 THEN v_missing := NULL; END IF;\n IF v_missing IS NOT NULL AND v_missing > coalesce(v_line.quantity_commercial, 0) THEN\n RAISE EXCEPTION 'fiscalbr: item %: % did not arrive, but the note bills only %',\n v_line.item_number, v_missing, v_line.quantity_commercial\n USING ERRCODE = '22023', HINT = 'RECEIPT_MORE_THAN_BILLED';\n END IF;\n v_reason := CASE WHEN v_missing IS NULL THEN NULL\n ELSE coalesce(nullif(v_row->>'shortage_reason', ''), 'faltou') END;\n IF v_reason IS NOT NULL AND v_reason NOT IN ('faltou', 'avariado', 'vencido', 'recusado', 'outro') THEN\n RAISE EXCEPTION 'fiscalbr: item %: unknown reason %', v_line.item_number, v_reason\n USING ERRCODE = '22023', HINT = 'RECEIPT_BAD_REASON';\n END IF;\n END IF;\n\n UPDATE public.plg_fiscalbr_inbox_items i SET\n product_id = nullif(v_row->>'product_id', '')::uuid,\n entry_type = nullif(v_row->>'entry_type', ''),\n chart_account_id = nullif(v_row->>'chart_account_id', '')::uuid,\n stock_unit_id = nullif(v_row->>'stock_unit_id', '')::uuid,\n conversion_factor = coalesce(nullif(v_row->>'conversion_factor', '')::numeric, 1),\n cost_mode = coalesce(nullif(v_row->>'cost_mode', ''), 'novo'),\n shortage_quantity = v_missing,\n shortage_reason = v_reason,\n shortage_note = CASE WHEN v_missing IS NULL THEN NULL\n WHEN v_row ? 'missing_quantity' THEN nullif(btrim(coalesce(v_row->>'shortage_note', '')), '')\n ELSE i.shortage_note END,\n -- Quem escreveu. Ausente na chave \u00E9 NULL, que \u00E9 \u00ABuma pessoa escolheu\u00BB.\n suggested_by = nullif(v_row->>'suggested_by', ''),\n suggestion_confidence = nullif(v_row->>'suggestion_confidence', '')::numeric,\n -- What the note bills, in stock units. The receipt is applied on accept.\n stock_quantity = i.quantity_commercial * coalesce(nullif(v_row->>'conversion_factor', '')::numeric, 1),\n unit_cost_new = CASE WHEN coalesce(nullif(v_row->>'conversion_factor', '')::numeric, 1) > 0\n THEN i.unit_price_commercial / coalesce(nullif(v_row->>'conversion_factor', '')::numeric, 1) END,\n -- Uma linha est\u00E1 conciliada quando sabe o que \u00E9. Despesa e servi\u00E7o n\u00E3o\n -- pedem produto: elas nunca v\u00E3o virar estoque.\n reconciled = CASE\n WHEN nullif(v_row->>'entry_type', '') IN ('despesa','servico') THEN true\n ELSE nullif(v_row->>'product_id', '') IS NOT NULL\n END,\n updated_at = now()\n WHERE i.tenant_id = v_tenant AND i.inbox_document_id = v_doc.id AND i.id = v_line.id;\n v_done := v_done + 1;\n END LOOP;\n\n IF p_duplicates IS NOT NULL THEN\n DELETE FROM public.plg_fiscalbr_inbox_duplicates\n WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id;\n INSERT INTO public.plg_fiscalbr_inbox_duplicates (\n tenant_id, inbox_document_id, duplicate_index, number, due_date, value,\n payment_type, barcode, pix_key, payment_method_id)\n SELECT v_tenant, v_doc.id, coalesce((d->>'index')::int, ord), d->>'number',\n nullif(d->>'due_date', '')::date, (d->>'value')::numeric,\n nullif(d->>'payment_type', ''), nullif(d->>'barcode', ''),\n nullif(d->>'pix_key', ''), nullif(d->>'payment_method_id', '')::uuid\n FROM jsonb_array_elements(p_duplicates) WITH ORDINALITY AS t(d, ord);\n END IF;\n\n SELECT count(*) INTO v_total FROM public.plg_fiscalbr_inbox_items\n WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id;\n\n UPDATE public.plg_fiscalbr_inbox_documents SET status = CASE\n WHEN (SELECT count(*) FROM public.plg_fiscalbr_inbox_items\n WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id AND reconciled) = v_total\n THEN 'accepted' ELSE 'partial' END\n WHERE id = v_doc.id;\n\n RETURN jsonb_build_object('document_id', v_doc.id, 'saved', v_done, 'items', v_total,\n 'reconciled', (SELECT count(*) FROM public.plg_fiscalbr_inbox_items\n WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id AND reconciled));\nEND $function$;\n\nREVOKE ALL ON FUNCTION public.fiscalbr_save_inbox_decision(uuid, jsonb, uuid, uuid, jsonb) FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.fiscalbr_save_inbox_decision(uuid, jsonb, uuid, uuid, jsonb) TO authenticated;\n\n-- \u2500\u2500 4. Accepting brings in what arrived \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nCREATE OR REPLACE FUNCTION public.fiscalbr_accept_inbox_document(\n p_document_id uuid,\n p_location_id uuid DEFAULT NULL)\nRETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO '' AS $function$\nDECLARE\n v_tenant uuid := public.plg_financial_require_tenant();\n v_doc public.plg_fiscalbr_inbox_documents%ROWTYPE;\n v_loc uuid;\n v_lines jsonb := '[]'::jsonb;\n v_insts jsonb := '[]'::jsonb;\n v_recv jsonb;\n v_inv jsonb;\n v_it record;\n v_no integer := 0;\n v_bearing integer := 0;\n v_total numeric := 0;\n v_stock_n integer := 0;\n v_key text;\n v_invoice uuid;\n v_item_ids uuid[] := '{}';\n v_fraction numeric;\n v_qty numeric;\n v_short_n integer := 0;\n v_short_v numeric := 0;\n -- A compet\u00EAncia: o DIA da emiss\u00E3o, n\u00E3o o instante.\n v_competence date;\nBEGIN\n SELECT * INTO v_doc FROM public.plg_fiscalbr_inbox_documents\n WHERE tenant_id = v_tenant AND id = p_document_id;\n IF NOT FOUND THEN\n RAISE EXCEPTION 'fiscalbr: nota % n\u00E3o encontrada neste tenant', p_document_id USING ERRCODE = 'P0002';\n END IF;\n PERFORM public.plg_financial_require_permission('financial.create', v_doc.unit_id);\n\n -- Settled = stocked, or a payable with no stock line left to receive (027).\n IF v_doc.stocked_at IS NOT NULL OR (v_doc.invoice_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM public.plg_fiscalbr_inbox_items x\n WHERE x.tenant_id = v_tenant AND x.inbox_document_id = v_doc.id\n AND x.stock_movement_id IS NULL\n AND (x.entry_type IS NULL OR x.entry_type = '' OR x.entry_type IN ('insumo','revenda','patrimonio','uso_consumo')))) THEN\n RETURN jsonb_build_object('document_id', v_doc.id, 'already_accepted', true,\n 'invoice_id', v_doc.invoice_id, 'operation_id', v_doc.inventory_operation_id);\n END IF;\n\n v_loc := coalesce(p_location_id, v_doc.default_location_id);\n v_competence := (v_doc.issue_date)::date;\n\n IF EXISTS (SELECT 1 FROM public.plg_fiscalbr_inbox_items\n WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id\n AND (entry_type IS NULL OR entry_type = '')) THEN\n RAISE EXCEPTION 'fiscalbr: h\u00E1 item sem tipo de registro \u2014 conciliar antes de aceitar'\n USING ERRCODE = '23514';\n END IF;\n\n -- What did not arrive, on every line (stock-bearing or not): it is what the\n -- finance person will abate from the payable.\n SELECT count(*), coalesce(sum(round(coalesce(i.total_price, 0) * least(i.shortage_quantity, i.quantity_commercial)\n / nullif(i.quantity_commercial, 0), 2)), 0)\n INTO v_short_n, v_short_v\n FROM public.plg_fiscalbr_inbox_items i\n WHERE i.tenant_id = v_tenant AND i.inbox_document_id = v_doc.id AND i.shortage_quantity > 0;\n\n FOR v_it IN\n SELECT * FROM public.plg_fiscalbr_inbox_items\n WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id\n AND entry_type IN ('insumo','revenda','patrimonio','uso_consumo')\n ORDER BY item_number\n LOOP\n v_bearing := v_bearing + 1;\n -- The received fraction: 1 = all of it, 0 = nothing came.\n v_fraction := CASE WHEN coalesce(v_it.quantity_commercial, 0) <= 0 THEN 1\n ELSE 1 - least(greatest(coalesce(v_it.shortage_quantity, 0), 0), v_it.quantity_commercial)\n / v_it.quantity_commercial END;\n -- Nothing came: nothing enters, and there is nothing to name.\n CONTINUE WHEN v_fraction <= 0.000001;\n IF v_it.stock_unit_id IS NULL THEN\n RAISE EXCEPTION 'fiscalbr: item % entra no estoque sem unidade \u2014 escolha a unidade de estoque', v_it.item_number\n USING ERRCODE = '23514';\n END IF;\n IF v_it.product_id IS NULL THEN\n RAISE EXCEPTION 'fiscalbr: item % \u00E9 % e n\u00E3o tem produto vinculado', v_it.item_number, v_it.entry_type\n USING ERRCODE = '23514';\n END IF;\n v_qty := round(coalesce(v_it.stock_quantity, v_it.quantity_commercial * v_it.conversion_factor) * v_fraction, 4);\n CONTINUE WHEN v_qty <= 0;\n v_no := v_no + 1;\n v_item_ids := v_item_ids || v_it.id;\n v_lines := v_lines || jsonb_build_object(\n 'product_id', v_it.product_id,\n 'quantity', v_qty,\n 'unit_cost', coalesce(v_it.unit_cost_new, v_it.unit_price_commercial / v_it.conversion_factor),\n 'measurement_unit_id', v_it.stock_unit_id,\n 'notes', v_it.description);\n END LOOP;\n v_stock_n := v_no;\n\n IF v_stock_n > 0 THEN\n IF v_loc IS NULL THEN\n RAISE EXCEPTION 'fiscalbr: a nota tem % linha(s) de estoque e nenhum local de estoque escolhido', v_stock_n\n USING ERRCODE = '22023';\n END IF;\n v_recv := public.inventory_receive(\n v_loc::uuid,\n v_lines::jsonb,\n jsonb_build_object(\n 'supplier_id', v_doc.supplier_party_id,\n -- O documento do estoque tamb\u00E9m quer o DIA.\n 'date', v_competence,\n 'type', 'nfe',\n 'ref', 'NF-e ' || coalesce(v_doc.nfe_number, '?'),\n 'notes', 'Entrada via DANFE NF-e ' || coalesce(v_doc.nfe_number, '?'),\n 'reason', 'Entrada via DANFE NF-e ' || coalesce(v_doc.nfe_number, '?')),\n ('nfe:' || v_doc.access_key)::text);\n\n UPDATE public.plg_fiscalbr_inbox_items i\n SET stock_movement_id = m.movement_id, updated_at = now()\n FROM (\n SELECT v_item_ids[(mov->>'line_no')::int] AS item_id, (mov->>'id')::uuid AS movement_id\n FROM jsonb_array_elements(coalesce(v_recv->'movements', '[]'::jsonb)) AS t(mov)\n WHERE (mov->>'line_no') IS NOT NULL\n ) m\n WHERE i.tenant_id = v_tenant AND i.id = m.item_id;\n END IF;\n\n IF v_doc.invoice_id IS NOT NULL THEN\n -- Half-done in the V1: the payable exists; only the stock is missing.\n v_invoice := v_doc.invoice_id;\n SELECT total INTO v_total FROM public.plg_financial_invoices WHERE id = v_invoice;\n v_insts := '[]'::jsonb;\n ELSE\n SELECT coalesce(sum(value), 0),\n coalesce(jsonb_agg(jsonb_build_object(\n 'number', coalesce(duplicate_index, 1),\n 'due_date', coalesce(due_date, v_competence, current_date),\n 'amount', round(value, 2),\n 'metadata', jsonb_strip_nulls(jsonb_build_object(\n 'barcode', barcode, 'pixKey', pix_key, 'paymentType', payment_type,\n 'danfeNumber', number))) ORDER BY duplicate_index), '[]'::jsonb)\n INTO v_total, v_insts\n FROM public.plg_fiscalbr_inbox_duplicates\n WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id;\n\n IF jsonb_array_length(v_insts) = 0 THEN\n v_total := round(coalesce(v_doc.total_value, 0), 2);\n v_insts := jsonb_build_array(jsonb_build_object(\n 'number', 1, 'due_date', coalesce(v_competence, current_date), 'amount', v_total));\n ELSE\n v_total := round(v_total, 2);\n END IF;\n\n v_key := 'danfe:' || v_doc.access_key;\n\n -- The payable is born at the note's full value (V1 rule): the supplier\n -- billed it, and what did not arrive is abated by finance.\n v_inv := public.financial_create_invoice(\n 'payable'::text,\n v_total::numeric,\n v_doc.supplier_party_id::uuid,\n NULL::uuid,\n v_doc.unit_id::uuid,\n v_insts::jsonb,\n v_competence::date,\n ('NF-e ' || coalesce(v_doc.nfe_number, '?') || ' \u00B7 ' || coalesce(v_doc.supplier_name, 'fornecedor'))::text,\n NULL::text,\n jsonb_build_object(\n 'source', 'danfe',\n 'danfe', jsonb_strip_nulls(jsonb_build_object(\n 'accessKey', v_doc.access_key, 'number', v_doc.nfe_number,\n 'series', v_doc.nfe_series, 'supplierName', v_doc.supplier_name,\n 'supplierCnpj', v_doc.supplier_cnpj,\n 'noteTotal', v_doc.total_value,\n 'inboxDocumentId', v_doc.id)))::jsonb,\n v_key::text);\n v_invoice := (v_inv->>'invoice_id')::uuid;\n\n INSERT INTO public.items (tenant_id, invoice_id, product_id, chart_account_id, name, quantity, unit_price, total, sort_order, metadata)\n SELECT v_tenant, v_invoice, i.product_id, coalesce(i.chart_account_id, v_doc.default_chart_account_id),\n i.description, i.quantity_commercial, i.unit_price_commercial,\n round(coalesce(i.total_price, 0), 2), i.item_number,\n jsonb_strip_nulls(jsonb_build_object(\n 'itemKind', CASE WHEN i.product_id IS NOT NULL THEN 'product' ELSE 'other' END,\n 'referenceId', i.product_id, 'entryType', i.entry_type,\n 'chartAccountId', coalesce(i.chart_account_id, v_doc.default_chart_account_id),\n 'ncm', i.ncm, 'cfop', i.cfop,\n 'supplierProductCode', i.supplier_product_code,\n -- The note line this payable line came from: the receipt check\n -- reaches the payable through it.\n 'inboxItemId', i.id))\n FROM public.plg_fiscalbr_inbox_items i\n WHERE i.tenant_id = v_tenant AND i.inbox_document_id = v_doc.id\n ORDER BY i.item_number\n ON CONFLICT DO NOTHING;\n PERFORM public.plg_fiscalbr_note_charge_lines(v_tenant, v_doc.id, v_invoice, v_total);\n END IF;\n\n UPDATE public.plg_fiscalbr_inbox_documents SET\n invoice_id = v_invoice,\n inventory_operation_id = coalesce((v_recv->>'operation_id')::uuid, inventory_operation_id),\n -- A note whose stock lines all came short was still received: nothing is\n -- left to enter, so it is settled too.\n stocked_at = CASE WHEN v_bearing > 0 THEN now() ELSE stocked_at END,\n status = 'accepted', updated_at = now()\n WHERE id = v_doc.id;\n\n INSERT INTO public.plg_fiscalbr_supplier_product_map (\n tenant_id, supplier_cnpj, supplier_product_code, product_id, entry_type,\n chart_account_id, stock_unit_id, conversion_factor, cost_mode, hit_count, last_used_at)\n SELECT v_tenant, v_doc.supplier_cnpj, i.supplier_product_code, i.product_id,\n i.entry_type, coalesce(i.chart_account_id, v_doc.default_chart_account_id),\n i.stock_unit_id, i.conversion_factor, i.cost_mode, 1, now()\n FROM public.plg_fiscalbr_inbox_items i\n WHERE i.tenant_id = v_tenant AND i.inbox_document_id = v_doc.id\n AND i.product_id IS NOT NULL\n AND coalesce(v_doc.supplier_cnpj, '') <> ''\n AND coalesce(i.supplier_product_code, '') <> ''\n ON CONFLICT (tenant_id, supplier_cnpj, supplier_product_code) DO UPDATE SET\n product_id = EXCLUDED.product_id,\n entry_type = EXCLUDED.entry_type,\n chart_account_id = coalesce(EXCLUDED.chart_account_id, public.plg_fiscalbr_supplier_product_map.chart_account_id),\n stock_unit_id = coalesce(EXCLUDED.stock_unit_id, public.plg_fiscalbr_supplier_product_map.stock_unit_id),\n conversion_factor = EXCLUDED.conversion_factor,\n cost_mode = EXCLUDED.cost_mode,\n hit_count = public.plg_fiscalbr_supplier_product_map.hit_count + 1,\n last_used_at = now(),\n updated_at = now();\n\n RETURN jsonb_build_object(\n 'document_id', v_doc.id, 'already_accepted', false,\n 'invoice_id', v_invoice, 'invoice_total', v_total,\n 'installments', jsonb_array_length(v_insts),\n 'operation_id', v_recv->>'operation_id',\n 'stock_lines', v_stock_n,\n 'shortage_lines', v_short_n,\n 'shortage_value', v_short_v,\n 'movements', coalesce(v_recv->'movements', '[]'::jsonb));\nEND $function$;\n\nREVOKE ALL ON FUNCTION public.fiscalbr_accept_inbox_document(uuid, uuid) FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.fiscalbr_accept_inbox_document(uuid, uuid) TO authenticated;\n\n-- \u2500\u2500 5. What did not arrive, as the payable sees it \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n-- One row per note line with a shortage. `pending` is what is still to abate:\n-- the payable line bills more than what arrived is worth. A cancelled line, or\n-- a note line with no payable line (a V1 copy), has nothing pending.\nCREATE OR REPLACE FUNCTION public.fiscalbr_note_receipt_occurrences(p_invoice_id uuid)\nRETURNS TABLE (\n inbox_item_id uuid, document_id uuid, nfe_number text, item_number integer, description text, unit text,\n note_quantity numeric, shortage_quantity numeric, shortage_reason text, shortage_note text,\n shortage_value numeric, received_value numeric,\n invoice_item_id uuid, invoice_item_total numeric, invoice_item_cancelled boolean, pending numeric)\nLANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO '' AS $function$\nDECLARE\n v_tenant uuid := public.plg_financial_require_tenant();\n v_unit uuid;\nBEGIN\n SELECT f.unit_id INTO v_unit FROM public.plg_financial_invoices f\n WHERE f.id = p_invoice_id AND f.tenant_id = v_tenant AND f.direction = 'payable';\n IF NOT FOUND THEN RETURN; END IF;\n PERFORM public.plg_financial_require_permission('financial.read', v_unit);\n\n RETURN QUERY\n WITH short AS (\n SELECT i.id, d.id AS doc_id, d.nfe_number, i.item_number, i.description, i.unit_commercial,\n i.quantity_commercial AS q,\n least(i.shortage_quantity, i.quantity_commercial) AS s,\n i.shortage_reason, i.shortage_note,\n round(coalesce(i.total_price, 0) * least(i.shortage_quantity, i.quantity_commercial)\n / nullif(i.quantity_commercial, 0), 2) AS sv,\n round(coalesce(i.total_price, 0), 2) AS tp\n FROM public.plg_fiscalbr_inbox_documents d\n JOIN public.plg_fiscalbr_inbox_items i ON i.inbox_document_id = d.id AND i.tenant_id = d.tenant_id\n WHERE d.tenant_id = v_tenant AND d.invoice_id = p_invoice_id AND i.shortage_quantity > 0\n )\n SELECT s.id, s.doc_id, s.nfe_number, s.item_number, s.description, s.unit_commercial,\n s.q, s.s, s.shortage_reason, s.shortage_note,\n coalesce(s.sv, 0), s.tp - coalesce(s.sv, 0),\n it.id, it.total, it.cancelled_at IS NOT NULL,\n CASE WHEN it.id IS NULL OR it.cancelled_at IS NOT NULL THEN 0::numeric\n ELSE greatest(round(it.total - (s.tp - coalesce(s.sv, 0)), 2), 0) END\n FROM short s\n LEFT JOIN LATERAL (\n SELECT x.id, x.total, x.cancelled_at FROM public.items x\n WHERE x.tenant_id = v_tenant AND x.invoice_id = p_invoice_id\n AND (x.metadata->>'inboxItemId' = s.id::text\n -- Payables opened before 034 carry no inboxItemId: the note's\n -- product lines are written in item order with their CFOP.\n OR (NOT x.metadata ? 'inboxItemId' AND x.metadata ? 'cfop'\n AND NOT x.metadata ? 'noteCharge' AND x.sort_order = s.item_number))\n ORDER BY (x.metadata ? 'inboxItemId') DESC\n LIMIT 1\n ) it ON true\n ORDER BY s.item_number;\nEND $function$;\n\nREVOKE ALL ON FUNCTION public.fiscalbr_note_receipt_occurrences(uuid) FROM PUBLIC, anon;\nGRANT EXECUTE ON FUNCTION public.fiscalbr_note_receipt_occurrences(uuid) TO authenticated, service_role;\n";
|
|
35
36
|
export declare const MIGRATIONS: Array<{
|
|
36
37
|
id: string;
|
|
37
38
|
sql: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,sBAAsB,2g0BA2jBlC,CAAA;AAED,eAAO,MAAM,0DAA0D,uzRAmMtE,CAAA;AAED,eAAO,MAAM,+CAA+C,m5oBAyW3D,CAAA;AAED,eAAO,MAAM,0CAA0C,o1XAgPtD,CAAA;AAED,eAAO,MAAM,8CAA8C,6qCAsB1D,CAAA;AAED,eAAO,MAAM,2CAA2C,w8dA6MvD,CAAA;AAED,eAAO,MAAM,yCAAyC,42BAkBrD,CAAA;AAED,eAAO,MAAM,oDAAoD,4oDA+BhE,CAAA;AAED,eAAO,MAAM,yDAAyD,otbA0NrE,CAAA;AAED,eAAO,MAAM,gEAAgE,q1+BAoiB5E,CAAA;AAED,eAAO,MAAM,gEAAgE,mqVAgO5E,CAAA;AAED,eAAO,MAAM,8CAA8C,k/HAiF1D,CAAA;AAED,eAAO,MAAM,oDAAoD,w2OA4JhE,CAAA;AAED,eAAO,MAAM,oDAAoD,gvRAwJhE,CAAA;AAED,eAAO,MAAM,kDAAkD,shPAoK9D,CAAA;AAED,eAAO,MAAM,8CAA8C,8/EA0C1D,CAAA;AAED,eAAO,MAAM,yCAAyC,2mJA2ErD,CAAA;AAED,eAAO,MAAM,4CAA4C,68QA0IxD,CAAA;AAED,eAAO,MAAM,0CAA0C,83CAwBtD,CAAA;AAED,eAAO,MAAM,+CAA+C,81JAiG3D,CAAA;AAED,eAAO,MAAM,gDAAgD,y+IAgH5D,CAAA;AAED,eAAO,MAAM,4CAA4C,ylEA4CxD,CAAA;AAED,eAAO,MAAM,qCAAqC,8kCAkBjD,CAAA;AAED,eAAO,MAAM,uDAAuD,u6HAyEnE,CAAA;AAED,eAAO,MAAM,oDAAoD,6/KAoHhE,CAAA;AAED,eAAO,MAAM,+CAA+C,uqPAwJ3D,CAAA;AAED,eAAO,MAAM,8CAA8C,myCAoB1D,CAAA;AAED,eAAO,MAAM,0DAA0D,yyHAsEtE,CAAA;AAED,eAAO,MAAM,4CAA4C,+jDA8BxD,CAAA;AAED,eAAO,MAAM,kDAAkD,0pDA2B9D,CAAA;AAED,eAAO,MAAM,8CAA8C,m3VAyK1D,CAAA;AAED,eAAO,MAAM,yCAAyC,kogBAkUrD,CAAA;AAED,eAAO,MAAM,oDAAoD,y2MA4HhE,CAAA;AAED,eAAO,MAAM,0CAA0C,8lYA4OtD,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,sBAAsB,2g0BA2jBlC,CAAA;AAED,eAAO,MAAM,0DAA0D,uzRAmMtE,CAAA;AAED,eAAO,MAAM,+CAA+C,m5oBAyW3D,CAAA;AAED,eAAO,MAAM,0CAA0C,o1XAgPtD,CAAA;AAED,eAAO,MAAM,8CAA8C,6qCAsB1D,CAAA;AAED,eAAO,MAAM,2CAA2C,w8dA6MvD,CAAA;AAED,eAAO,MAAM,yCAAyC,42BAkBrD,CAAA;AAED,eAAO,MAAM,oDAAoD,4oDA+BhE,CAAA;AAED,eAAO,MAAM,yDAAyD,otbA0NrE,CAAA;AAED,eAAO,MAAM,gEAAgE,q1+BAoiB5E,CAAA;AAED,eAAO,MAAM,gEAAgE,mqVAgO5E,CAAA;AAED,eAAO,MAAM,8CAA8C,k/HAiF1D,CAAA;AAED,eAAO,MAAM,oDAAoD,w2OA4JhE,CAAA;AAED,eAAO,MAAM,oDAAoD,gvRAwJhE,CAAA;AAED,eAAO,MAAM,kDAAkD,shPAoK9D,CAAA;AAED,eAAO,MAAM,8CAA8C,8/EA0C1D,CAAA;AAED,eAAO,MAAM,yCAAyC,2mJA2ErD,CAAA;AAED,eAAO,MAAM,4CAA4C,68QA0IxD,CAAA;AAED,eAAO,MAAM,0CAA0C,83CAwBtD,CAAA;AAED,eAAO,MAAM,+CAA+C,81JAiG3D,CAAA;AAED,eAAO,MAAM,gDAAgD,y+IAgH5D,CAAA;AAED,eAAO,MAAM,4CAA4C,ylEA4CxD,CAAA;AAED,eAAO,MAAM,qCAAqC,8kCAkBjD,CAAA;AAED,eAAO,MAAM,uDAAuD,u6HAyEnE,CAAA;AAED,eAAO,MAAM,oDAAoD,6/KAoHhE,CAAA;AAED,eAAO,MAAM,+CAA+C,uqPAwJ3D,CAAA;AAED,eAAO,MAAM,8CAA8C,myCAoB1D,CAAA;AAED,eAAO,MAAM,0DAA0D,yyHAsEtE,CAAA;AAED,eAAO,MAAM,4CAA4C,+jDA8BxD,CAAA;AAED,eAAO,MAAM,kDAAkD,0pDA2B9D,CAAA;AAED,eAAO,MAAM,8CAA8C,m3VAyK1D,CAAA;AAED,eAAO,MAAM,yCAAyC,kogBAkUrD,CAAA;AAED,eAAO,MAAM,oDAAoD,y2MA4HhE,CAAA;AAED,eAAO,MAAM,0CAA0C,8lYA4OtD,CAAA;AAED,eAAO,MAAM,4CAA4C,y24BAwgBxD,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAoCzD,CAAA"}
|
|
@@ -33,8 +33,9 @@ var MIGRATION_030_THE_SERVICE_ONBOARDS_THE_EMITTER = "";
|
|
|
33
33
|
var MIGRATION_031_THE_SERVICE_ISSUES_THE_NOTE = "";
|
|
34
34
|
var MIGRATION_032_A_DELIVERED_NOTE_CARRIES_WHERE_IT_GOES = "";
|
|
35
35
|
var MIGRATION_033_A_COMPANY_BUYER_GETS_ITS_NFE = "";
|
|
36
|
+
var MIGRATION_034_ONLY_WHAT_ARRIVED_ENTERS_STOCK = "";
|
|
36
37
|
var MIGRATIONS = [];
|
|
37
38
|
|
|
38
|
-
export { MIGRATIONS, MIGRATION_000_BASELINE, MIGRATION_001_PRESERVE_TERMINAL_RESULTS_AND_RECOVER_LEASES, MIGRATION_002_A_NOTA_QUE_CHEGA_TEM_ONDE_ESPERAR, MIGRATION_003_A_CAIXA_DE_ENTRADA_ATRAVESSA, MIGRATION_004_O_GRUPO_FISCAL_DO_V1_REPETE_NOME, MIGRATION_005_A_NOTA_EMITIDA_E_UM_DOCUMENTO, MIGRATION_006_O_GRUPO_FISCAL_GANHA_O_RAIL, MIGRATION_007_A_RLS_DO_DOCUMENTO_PASSA_A_SER_LEGIVEL, MIGRATION_008_A_NOTA_RECEBIDA_GUARDA_A_DECISAO_DE_ENTRADA, MIGRATION_009_ACEITAR_A_NOTA_ESCREVE_ESTOQUE_E_TITULO_DE_UMA_VEZ, MIGRATION_010_A_DATA_DE_EMISSAO_E_INSTANTE_E_A_COMPETENCIA_E_DIA, MIGRATION_011_O_IMPOSTO_DO_PRODUTO_E_DO_FISCAL, MIGRATION_012_QUEM_E_O_PRODUTO_SE_PERGUNTA_AO_INDICE, MIGRATION_013_A_SUGESTAO_SOBREVIVE_A_FECHAR_A_JANELA, MIGRATION_014_A_DESCRICAO_DA_NOTA_TEM_LIXO_NO_MEIO, MIGRATION_015_O_MOVIMENTO_DIZ_QUE_VEIO_DA_NOTA, MIGRATION_016_A_NOTA_GUARDA_O_PROPRIO_XML, MIGRATION_017_QUEM_EMITE_E_O_CNPJ_NAO_A_LOJA, MIGRATION_018_A_NOTA_DO_V1_ALCANCA_A_CONTA, MIGRATION_019_A_NOTA_EMITIDA_SE_CANCELA_PELO_V2, MIGRATION_020_A_NOTA_ACHA_O_FORNECEDOR_PELO_CNPJ, MIGRATION_021_USO_E_CONSUMO_ENTRA_NO_ESTOQUE, MIGRATION_022_A_NOTA_DO_V1_TRAZ_O_XML, MIGRATION_023_A_NOTA_ACEITA_SEM_LINHAS_RECEBE_AS_LINHAS, MIGRATION_024_A_NOTA_NAO_APONTA_PARA_CONTA_QUE_SUMIU, MIGRATION_025_A_CONTA_DA_NOTA_FECHA_COM_O_TOTAL, MIGRATION_026_O_RECEBIMENTO_PARADO_DIZ_POR_QUE, MIGRATION_027_A_NOTA_COM_CONTA_E_SEM_ESTOQUE_TERMINA_NO_V2, MIGRATION_028_A_LINHA_DE_ESTOQUE_TEM_UNIDADE, MIGRATION_029_THE_SERVICE_WRITES_THE_INTAKE_HEALTH, MIGRATION_030_THE_SERVICE_ONBOARDS_THE_EMITTER, MIGRATION_031_THE_SERVICE_ISSUES_THE_NOTE, MIGRATION_032_A_DELIVERED_NOTE_CARRIES_WHERE_IT_GOES, MIGRATION_033_A_COMPANY_BUYER_GETS_ITS_NFE };
|
|
39
|
+
export { MIGRATIONS, MIGRATION_000_BASELINE, MIGRATION_001_PRESERVE_TERMINAL_RESULTS_AND_RECOVER_LEASES, MIGRATION_002_A_NOTA_QUE_CHEGA_TEM_ONDE_ESPERAR, MIGRATION_003_A_CAIXA_DE_ENTRADA_ATRAVESSA, MIGRATION_004_O_GRUPO_FISCAL_DO_V1_REPETE_NOME, MIGRATION_005_A_NOTA_EMITIDA_E_UM_DOCUMENTO, MIGRATION_006_O_GRUPO_FISCAL_GANHA_O_RAIL, MIGRATION_007_A_RLS_DO_DOCUMENTO_PASSA_A_SER_LEGIVEL, MIGRATION_008_A_NOTA_RECEBIDA_GUARDA_A_DECISAO_DE_ENTRADA, MIGRATION_009_ACEITAR_A_NOTA_ESCREVE_ESTOQUE_E_TITULO_DE_UMA_VEZ, MIGRATION_010_A_DATA_DE_EMISSAO_E_INSTANTE_E_A_COMPETENCIA_E_DIA, MIGRATION_011_O_IMPOSTO_DO_PRODUTO_E_DO_FISCAL, MIGRATION_012_QUEM_E_O_PRODUTO_SE_PERGUNTA_AO_INDICE, MIGRATION_013_A_SUGESTAO_SOBREVIVE_A_FECHAR_A_JANELA, MIGRATION_014_A_DESCRICAO_DA_NOTA_TEM_LIXO_NO_MEIO, MIGRATION_015_O_MOVIMENTO_DIZ_QUE_VEIO_DA_NOTA, MIGRATION_016_A_NOTA_GUARDA_O_PROPRIO_XML, MIGRATION_017_QUEM_EMITE_E_O_CNPJ_NAO_A_LOJA, MIGRATION_018_A_NOTA_DO_V1_ALCANCA_A_CONTA, MIGRATION_019_A_NOTA_EMITIDA_SE_CANCELA_PELO_V2, MIGRATION_020_A_NOTA_ACHA_O_FORNECEDOR_PELO_CNPJ, MIGRATION_021_USO_E_CONSUMO_ENTRA_NO_ESTOQUE, MIGRATION_022_A_NOTA_DO_V1_TRAZ_O_XML, MIGRATION_023_A_NOTA_ACEITA_SEM_LINHAS_RECEBE_AS_LINHAS, MIGRATION_024_A_NOTA_NAO_APONTA_PARA_CONTA_QUE_SUMIU, MIGRATION_025_A_CONTA_DA_NOTA_FECHA_COM_O_TOTAL, MIGRATION_026_O_RECEBIMENTO_PARADO_DIZ_POR_QUE, MIGRATION_027_A_NOTA_COM_CONTA_E_SEM_ESTOQUE_TERMINA_NO_V2, MIGRATION_028_A_LINHA_DE_ESTOQUE_TEM_UNIDADE, MIGRATION_029_THE_SERVICE_WRITES_THE_INTAKE_HEALTH, MIGRATION_030_THE_SERVICE_ONBOARDS_THE_EMITTER, MIGRATION_031_THE_SERVICE_ISSUES_THE_NOTE, MIGRATION_032_A_DELIVERED_NOTE_CARRIES_WHERE_IT_GOES, MIGRATION_033_A_COMPANY_BUYER_GETS_ITS_NFE, MIGRATION_034_ONLY_WHAT_ARRIVED_ENTERS_STOCK };
|
|
39
40
|
//# sourceMappingURL=main.browser.js.map
|
|
40
41
|
//# sourceMappingURL=main.browser.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../node_modules/.cache/fayz-migration-stubs/main.ts"],"names":[],"mappings":";AAEO,IAAM,sBAAA,GAAyB;AAC/B,IAAM,0DAAA,GAA6D;AACnE,IAAM,+CAAA,GAAkD;AACxD,IAAM,0CAAA,GAA6C;AACnD,IAAM,8CAAA,GAAiD;AACvD,IAAM,2CAAA,GAA8C;AACpD,IAAM,yCAAA,GAA4C;AAClD,IAAM,oDAAA,GAAuD;AAC7D,IAAM,yDAAA,GAA4D;AAClE,IAAM,gEAAA,GAAmE;AACzE,IAAM,gEAAA,GAAmE;AACzE,IAAM,8CAAA,GAAiD;AACvD,IAAM,oDAAA,GAAuD;AAC7D,IAAM,oDAAA,GAAuD;AAC7D,IAAM,kDAAA,GAAqD;AAC3D,IAAM,8CAAA,GAAiD;AACvD,IAAM,yCAAA,GAA4C;AAClD,IAAM,4CAAA,GAA+C;AACrD,IAAM,0CAAA,GAA6C;AACnD,IAAM,+CAAA,GAAkD;AACxD,IAAM,gDAAA,GAAmD;AACzD,IAAM,4CAAA,GAA+C;AACrD,IAAM,qCAAA,GAAwC;AAC9C,IAAM,uDAAA,GAA0D;AAChE,IAAM,oDAAA,GAAuD;AAC7D,IAAM,+CAAA,GAAkD;AACxD,IAAM,8CAAA,GAAiD;AACvD,IAAM,0DAAA,GAA6D;AACnE,IAAM,4CAAA,GAA+C;AACrD,IAAM,kDAAA,GAAqD;AAC3D,IAAM,8CAAA,GAAiD;AACvD,IAAM,yCAAA,GAA4C;AAClD,IAAM,oDAAA,GAAuD;AAC7D,IAAM,0CAAA,GAA6C;AACnD,IAAM,aAAiD","file":"main.browser.js","sourcesContent":["// GENERATED by scripts/tsup-migrations.mjs — the browser build of a\n// migrations barrel: the same names, no SQL. See that script for why.\nexport const MIGRATION_000_BASELINE = ''\nexport const MIGRATION_001_PRESERVE_TERMINAL_RESULTS_AND_RECOVER_LEASES = ''\nexport const MIGRATION_002_A_NOTA_QUE_CHEGA_TEM_ONDE_ESPERAR = ''\nexport const MIGRATION_003_A_CAIXA_DE_ENTRADA_ATRAVESSA = ''\nexport const MIGRATION_004_O_GRUPO_FISCAL_DO_V1_REPETE_NOME = ''\nexport const MIGRATION_005_A_NOTA_EMITIDA_E_UM_DOCUMENTO = ''\nexport const MIGRATION_006_O_GRUPO_FISCAL_GANHA_O_RAIL = ''\nexport const MIGRATION_007_A_RLS_DO_DOCUMENTO_PASSA_A_SER_LEGIVEL = ''\nexport const MIGRATION_008_A_NOTA_RECEBIDA_GUARDA_A_DECISAO_DE_ENTRADA = ''\nexport const MIGRATION_009_ACEITAR_A_NOTA_ESCREVE_ESTOQUE_E_TITULO_DE_UMA_VEZ = ''\nexport const MIGRATION_010_A_DATA_DE_EMISSAO_E_INSTANTE_E_A_COMPETENCIA_E_DIA = ''\nexport const MIGRATION_011_O_IMPOSTO_DO_PRODUTO_E_DO_FISCAL = ''\nexport const MIGRATION_012_QUEM_E_O_PRODUTO_SE_PERGUNTA_AO_INDICE = ''\nexport const MIGRATION_013_A_SUGESTAO_SOBREVIVE_A_FECHAR_A_JANELA = ''\nexport const MIGRATION_014_A_DESCRICAO_DA_NOTA_TEM_LIXO_NO_MEIO = ''\nexport const MIGRATION_015_O_MOVIMENTO_DIZ_QUE_VEIO_DA_NOTA = ''\nexport const MIGRATION_016_A_NOTA_GUARDA_O_PROPRIO_XML = ''\nexport const MIGRATION_017_QUEM_EMITE_E_O_CNPJ_NAO_A_LOJA = ''\nexport const MIGRATION_018_A_NOTA_DO_V1_ALCANCA_A_CONTA = ''\nexport const MIGRATION_019_A_NOTA_EMITIDA_SE_CANCELA_PELO_V2 = ''\nexport const MIGRATION_020_A_NOTA_ACHA_O_FORNECEDOR_PELO_CNPJ = ''\nexport const MIGRATION_021_USO_E_CONSUMO_ENTRA_NO_ESTOQUE = ''\nexport const MIGRATION_022_A_NOTA_DO_V1_TRAZ_O_XML = ''\nexport const MIGRATION_023_A_NOTA_ACEITA_SEM_LINHAS_RECEBE_AS_LINHAS = ''\nexport const MIGRATION_024_A_NOTA_NAO_APONTA_PARA_CONTA_QUE_SUMIU = ''\nexport const MIGRATION_025_A_CONTA_DA_NOTA_FECHA_COM_O_TOTAL = ''\nexport const MIGRATION_026_O_RECEBIMENTO_PARADO_DIZ_POR_QUE = ''\nexport const MIGRATION_027_A_NOTA_COM_CONTA_E_SEM_ESTOQUE_TERMINA_NO_V2 = ''\nexport const MIGRATION_028_A_LINHA_DE_ESTOQUE_TEM_UNIDADE = ''\nexport const MIGRATION_029_THE_SERVICE_WRITES_THE_INTAKE_HEALTH = ''\nexport const MIGRATION_030_THE_SERVICE_ONBOARDS_THE_EMITTER = ''\nexport const MIGRATION_031_THE_SERVICE_ISSUES_THE_NOTE = ''\nexport const MIGRATION_032_A_DELIVERED_NOTE_CARRIES_WHERE_IT_GOES = ''\nexport const MIGRATION_033_A_COMPANY_BUYER_GETS_ITS_NFE = ''\nexport const MIGRATIONS: Array<{ id: string; sql: string }> = []\n"]}
|
|
1
|
+
{"version":3,"sources":["../../node_modules/.cache/fayz-migration-stubs/main.ts"],"names":[],"mappings":";AAEO,IAAM,sBAAA,GAAyB;AAC/B,IAAM,0DAAA,GAA6D;AACnE,IAAM,+CAAA,GAAkD;AACxD,IAAM,0CAAA,GAA6C;AACnD,IAAM,8CAAA,GAAiD;AACvD,IAAM,2CAAA,GAA8C;AACpD,IAAM,yCAAA,GAA4C;AAClD,IAAM,oDAAA,GAAuD;AAC7D,IAAM,yDAAA,GAA4D;AAClE,IAAM,gEAAA,GAAmE;AACzE,IAAM,gEAAA,GAAmE;AACzE,IAAM,8CAAA,GAAiD;AACvD,IAAM,oDAAA,GAAuD;AAC7D,IAAM,oDAAA,GAAuD;AAC7D,IAAM,kDAAA,GAAqD;AAC3D,IAAM,8CAAA,GAAiD;AACvD,IAAM,yCAAA,GAA4C;AAClD,IAAM,4CAAA,GAA+C;AACrD,IAAM,0CAAA,GAA6C;AACnD,IAAM,+CAAA,GAAkD;AACxD,IAAM,gDAAA,GAAmD;AACzD,IAAM,4CAAA,GAA+C;AACrD,IAAM,qCAAA,GAAwC;AAC9C,IAAM,uDAAA,GAA0D;AAChE,IAAM,oDAAA,GAAuD;AAC7D,IAAM,+CAAA,GAAkD;AACxD,IAAM,8CAAA,GAAiD;AACvD,IAAM,0DAAA,GAA6D;AACnE,IAAM,4CAAA,GAA+C;AACrD,IAAM,kDAAA,GAAqD;AAC3D,IAAM,8CAAA,GAAiD;AACvD,IAAM,yCAAA,GAA4C;AAClD,IAAM,oDAAA,GAAuD;AAC7D,IAAM,0CAAA,GAA6C;AACnD,IAAM,4CAAA,GAA+C;AACrD,IAAM,aAAiD","file":"main.browser.js","sourcesContent":["// GENERATED by scripts/tsup-migrations.mjs — the browser build of a\n// migrations barrel: the same names, no SQL. See that script for why.\nexport const MIGRATION_000_BASELINE = ''\nexport const MIGRATION_001_PRESERVE_TERMINAL_RESULTS_AND_RECOVER_LEASES = ''\nexport const MIGRATION_002_A_NOTA_QUE_CHEGA_TEM_ONDE_ESPERAR = ''\nexport const MIGRATION_003_A_CAIXA_DE_ENTRADA_ATRAVESSA = ''\nexport const MIGRATION_004_O_GRUPO_FISCAL_DO_V1_REPETE_NOME = ''\nexport const MIGRATION_005_A_NOTA_EMITIDA_E_UM_DOCUMENTO = ''\nexport const MIGRATION_006_O_GRUPO_FISCAL_GANHA_O_RAIL = ''\nexport const MIGRATION_007_A_RLS_DO_DOCUMENTO_PASSA_A_SER_LEGIVEL = ''\nexport const MIGRATION_008_A_NOTA_RECEBIDA_GUARDA_A_DECISAO_DE_ENTRADA = ''\nexport const MIGRATION_009_ACEITAR_A_NOTA_ESCREVE_ESTOQUE_E_TITULO_DE_UMA_VEZ = ''\nexport const MIGRATION_010_A_DATA_DE_EMISSAO_E_INSTANTE_E_A_COMPETENCIA_E_DIA = ''\nexport const MIGRATION_011_O_IMPOSTO_DO_PRODUTO_E_DO_FISCAL = ''\nexport const MIGRATION_012_QUEM_E_O_PRODUTO_SE_PERGUNTA_AO_INDICE = ''\nexport const MIGRATION_013_A_SUGESTAO_SOBREVIVE_A_FECHAR_A_JANELA = ''\nexport const MIGRATION_014_A_DESCRICAO_DA_NOTA_TEM_LIXO_NO_MEIO = ''\nexport const MIGRATION_015_O_MOVIMENTO_DIZ_QUE_VEIO_DA_NOTA = ''\nexport const MIGRATION_016_A_NOTA_GUARDA_O_PROPRIO_XML = ''\nexport const MIGRATION_017_QUEM_EMITE_E_O_CNPJ_NAO_A_LOJA = ''\nexport const MIGRATION_018_A_NOTA_DO_V1_ALCANCA_A_CONTA = ''\nexport const MIGRATION_019_A_NOTA_EMITIDA_SE_CANCELA_PELO_V2 = ''\nexport const MIGRATION_020_A_NOTA_ACHA_O_FORNECEDOR_PELO_CNPJ = ''\nexport const MIGRATION_021_USO_E_CONSUMO_ENTRA_NO_ESTOQUE = ''\nexport const MIGRATION_022_A_NOTA_DO_V1_TRAZ_O_XML = ''\nexport const MIGRATION_023_A_NOTA_ACEITA_SEM_LINHAS_RECEBE_AS_LINHAS = ''\nexport const MIGRATION_024_A_NOTA_NAO_APONTA_PARA_CONTA_QUE_SUMIU = ''\nexport const MIGRATION_025_A_CONTA_DA_NOTA_FECHA_COM_O_TOTAL = ''\nexport const MIGRATION_026_O_RECEBIMENTO_PARADO_DIZ_POR_QUE = ''\nexport const MIGRATION_027_A_NOTA_COM_CONTA_E_SEM_ESTOQUE_TERMINA_NO_V2 = ''\nexport const MIGRATION_028_A_LINHA_DE_ESTOQUE_TEM_UNIDADE = ''\nexport const MIGRATION_029_THE_SERVICE_WRITES_THE_INTAKE_HEALTH = ''\nexport const MIGRATION_030_THE_SERVICE_ONBOARDS_THE_EMITTER = ''\nexport const MIGRATION_031_THE_SERVICE_ISSUES_THE_NOTE = ''\nexport const MIGRATION_032_A_DELIVERED_NOTE_CARRIES_WHERE_IT_GOES = ''\nexport const MIGRATION_033_A_COMPANY_BUYER_GETS_ITS_NFE = ''\nexport const MIGRATION_034_ONLY_WHAT_ARRIVED_ENTERS_STOCK = ''\nexport const MIGRATIONS: Array<{ id: string; sql: string }> = []\n"]}
|