@fayz-ai/plugin-fiscal-br 0.13.7 → 0.15.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.
Files changed (73) hide show
  1. package/dist/InboundNotesPage-CZVSXCJA.js +6 -0
  2. package/dist/{InboundNotesPage-R72EC5E4.js.map → InboundNotesPage-CZVSXCJA.js.map} +1 -1
  3. package/dist/InvoiceNotesButton-SC3G7FUR.js +5 -0
  4. package/dist/{InvoiceNotesButton-3SMNHWMQ.js.map → InvoiceNotesButton-SC3G7FUR.js.map} +1 -1
  5. package/dist/NoteReceiptCard-H5BMFPU7.js +4 -0
  6. package/dist/{NoteReconcileView-3KVXZLCG.js.map → NoteReceiptCard-H5BMFPU7.js.map} +1 -1
  7. package/dist/NoteReconcileView-QSRL6NKQ.js +5 -0
  8. package/dist/NoteReconcileView-QSRL6NKQ.js.map +1 -0
  9. package/dist/OrderNoteCard-PDSK2AS3.js +5 -0
  10. package/dist/{OrderNoteCard-H6P66R4J.js.map → OrderNoteCard-PDSK2AS3.js.map} +1 -1
  11. package/dist/{UnitFiscalWidgets-KCHSISBS.js → UnitFiscalWidgets-K4PX3HWG.js} +3 -3
  12. package/dist/{UnitFiscalWidgets-KCHSISBS.js.map → UnitFiscalWidgets-K4PX3HWG.js.map} +1 -1
  13. package/dist/chunk-3BDFMEYY.js +231 -0
  14. package/dist/chunk-3BDFMEYY.js.map +1 -0
  15. package/dist/{chunk-OGXYHL3Z.js → chunk-DBWRGUIV.js} +20 -5
  16. package/dist/chunk-DBWRGUIV.js.map +1 -0
  17. package/dist/chunk-DHCCZXUM.js +50 -0
  18. package/dist/chunk-DHCCZXUM.js.map +1 -0
  19. package/dist/{chunk-WID54RUV.js → chunk-F325US5P.js} +4 -115
  20. package/dist/chunk-F325US5P.js.map +1 -0
  21. package/dist/chunk-ODMEESFD.js +222 -0
  22. package/dist/chunk-ODMEESFD.js.map +1 -0
  23. package/dist/{chunk-G7T5YMNY.js → chunk-SSPDH22E.js} +78 -41
  24. package/dist/chunk-SSPDH22E.js.map +1 -0
  25. package/dist/{chunk-UYGGBJCR.js → chunk-TZH7AWBD.js} +187 -54
  26. package/dist/chunk-TZH7AWBD.js.map +1 -0
  27. package/dist/{chunk-7NW3EBOQ.js → chunk-ZJGXUJKM.js} +5 -3
  28. package/dist/chunk-ZJGXUJKM.js.map +1 -0
  29. package/dist/data/inbox.d.ts +5 -1
  30. package/dist/data/inbox.d.ts.map +1 -1
  31. package/dist/data/receipt.d.ts +45 -0
  32. package/dist/data/receipt.d.ts.map +1 -0
  33. package/dist/index.d.ts +3 -0
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +188 -16
  36. package/dist/index.js.map +1 -1
  37. package/dist/lib/emitters.d.ts +7 -0
  38. package/dist/lib/emitters.d.ts.map +1 -1
  39. package/dist/lib/notes.d.ts +19 -3
  40. package/dist/lib/notes.d.ts.map +1 -1
  41. package/dist/lib/receipt.d.ts +39 -0
  42. package/dist/lib/receipt.d.ts.map +1 -0
  43. package/dist/locales/en.d.ts +2 -0
  44. package/dist/locales/en.d.ts.map +1 -0
  45. package/dist/locales/index.d.ts +2 -0
  46. package/dist/locales/index.d.ts.map +1 -0
  47. package/dist/locales/pt-BR.d.ts +2 -0
  48. package/dist/locales/pt-BR.d.ts.map +1 -0
  49. package/dist/migrations/index.d.ts +2 -0
  50. package/dist/migrations/index.d.ts.map +1 -1
  51. package/dist/migrations/main.browser.js +3 -1
  52. package/dist/migrations/main.browser.js.map +1 -1
  53. package/dist/migrations/main.js +762 -2
  54. package/dist/migrations/main.js.map +1 -1
  55. package/dist/types.d.ts +8 -1
  56. package/dist/types.d.ts.map +1 -1
  57. package/dist/views/InboundNotesView.d.ts.map +1 -1
  58. package/dist/views/NoteReceiptCard.d.ts +4 -0
  59. package/dist/views/NoteReceiptCard.d.ts.map +1 -0
  60. package/dist/views/NoteReconcileView.d.ts.map +1 -1
  61. package/dist/views/OrderNoteCard.d.ts.map +1 -1
  62. package/package.json +5 -5
  63. package/dist/InboundNotesPage-R72EC5E4.js +0 -5
  64. package/dist/InvoiceNotesButton-3SMNHWMQ.js +0 -5
  65. package/dist/NoteReconcileView-3KVXZLCG.js +0 -4
  66. package/dist/OrderNoteCard-H6P66R4J.js +0 -5
  67. package/dist/chunk-7NW3EBOQ.js.map +0 -1
  68. package/dist/chunk-G7T5YMNY.js.map +0 -1
  69. package/dist/chunk-OGXYHL3Z.js.map +0 -1
  70. package/dist/chunk-RZT2BO6E.js +0 -64
  71. package/dist/chunk-RZT2BO6E.js.map +0 -1
  72. package/dist/chunk-UYGGBJCR.js.map +0 -1
  73. package/dist/chunk-WID54RUV.js.map +0 -1
@@ -4871,6 +4871,764 @@ BEGIN
4871
4871
  END
4872
4872
  $$;
4873
4873
  `;
4874
+ var MIGRATION_033_A_COMPANY_BUYER_GETS_ITS_NFE = `-- ============================================================================
4875
+ -- 033 \u2014 a company buyer gets its NF-e
4876
+ --
4877
+ -- control-sdk-backend ADR 0008, decisions 15 to 23: the operator chooses, on
4878
+ -- the order, between the NFC-e (a consumer) and the NF-e (model 55, the DANFE
4879
+ -- a company books). Artorius sells to restaurants and mini-markets. An NF-e
4880
+ -- names its buyer, so the order's source for its note now carries who the
4881
+ -- order is with (\`orders.party_id\`): document, legal name, email, state
4882
+ -- registration and address. The integration service applies the rules; this
4883
+ -- only gathers.
4884
+ --
4885
+ -- Where each piece comes from:
4886
+ -- * state registration: \`custom_fields.stateRegistration\`, then the
4887
+ -- supplier form's \`registrationNumber\`, then the V1's
4888
+ -- \`metadata.legal.state_registration\`, then \u2014 only for a CNPJ \u2014 the
4889
+ -- V1 client's \`rg\`, which the V1 used to hold a company client's IE
4890
+ -- (beautyplace src/lib/clientPersonType.ts) and the import kept in
4891
+ -- \`metadata.documents.rg\`.
4892
+ -- * address: the person's address book (\`public.addresses\`), fiscal first,
4893
+ -- then billing, then the default; else the legacy fields the import left
4894
+ -- on the person.
4895
+ --
4896
+ -- And one sale, one note: a note of either model is opened only while the
4897
+ -- order has no live note of the OTHER model either, so a double click on
4898
+ -- "Emitir NF-e" and "Emitir NFC-e" never issues both.
4899
+ --
4900
+ -- Additive: two CREATE OR REPLACE FUNCTION, same signatures and grants.
4901
+ -- ============================================================================
4902
+
4903
+ CREATE OR REPLACE FUNCTION public.fiscalbr_order_for_note_for_service(p_tenant uuid, p_order uuid)
4904
+ RETURNS jsonb
4905
+ LANGUAGE plpgsql STABLE SECURITY DEFINER
4906
+ SET search_path TO ''
4907
+ AS $$
4908
+ DECLARE
4909
+ v_checkout jsonb;
4910
+ BEGIN
4911
+ -- The shop is optional: a site order says how it was paid on its checkout,
4912
+ -- read only where the shop's table exists.
4913
+ IF to_regclass('public.plg_shop_checkout_sessions') IS NOT NULL THEN
4914
+ EXECUTE $q$
4915
+ SELECT jsonb_build_object(
4916
+ 'paymentMethod', s.payment_method, 'provider', s.provider, 'total', s.total, 'status', s.status,
4917
+ 'customerName', s.customer_name, 'customerDocument', s.customer_document,
4918
+ 'destinationState', s.shipping_address ->> 'state', 'destinationCity', s.shipping_address ->> 'city',
4919
+ 'customerEmail', s.customer_email,
4920
+ 'shippingAddress', CASE WHEN s.shipping_address IS NULL THEN NULL ELSE jsonb_build_object(
4921
+ 'street', s.shipping_address ->> 'street', 'number', s.shipping_address ->> 'number',
4922
+ 'complement', s.shipping_address ->> 'complement', 'district', s.shipping_address ->> 'district',
4923
+ 'city', s.shipping_address ->> 'city', 'state', s.shipping_address ->> 'state',
4924
+ 'postalCode', coalesce(s.shipping_address ->> 'postalCode', s.shipping_address ->> 'postal_code')) END)
4925
+ FROM public.plg_shop_checkout_sessions s
4926
+ WHERE s.order_id = $1 AND s.tenant_id = $2 AND s.status = 'paid'
4927
+ ORDER BY s.updated_at DESC LIMIT 1 $q$
4928
+ INTO v_checkout USING p_order, p_tenant;
4929
+ END IF;
4930
+
4931
+ RETURN (SELECT jsonb_build_object(
4932
+ 'orderId', o.id,
4933
+ 'tenantId', o.tenant_id,
4934
+ 'unitId', o.unit_id,
4935
+ 'kind', o.kind,
4936
+ 'status', o.status,
4937
+ 'channel', o.channel,
4938
+ 'createdAt', o.created_at,
4939
+ 'subtotal', o.subtotal,
4940
+ 'discount', o.discount,
4941
+ 'shipping', o.shipping,
4942
+ 'total', o.total,
4943
+ 'legalEntityId', u.company_legal_entity_id,
4944
+ 'items', coalesce((
4945
+ SELECT jsonb_agg(jsonb_build_object(
4946
+ 'itemId', i.id,
4947
+ 'productId', i.product_id,
4948
+ 'code', coalesce(nullif(p.sku, ''), i.product_id::text, i.id::text),
4949
+ 'name', i.name,
4950
+ 'quantity', i.quantity,
4951
+ 'unitPrice', i.unit_price,
4952
+ 'discount', i.discount,
4953
+ 'total', i.total,
4954
+ 'cancelled', i.cancelled_at IS NOT NULL,
4955
+ -- The product's own value wins, field by field, over its group's (V1).
4956
+ 'tax', CASE WHEN t.product_id IS NULL AND g.id IS NULL THEN NULL ELSE jsonb_build_object(
4957
+ 'ncm', t.ncm,
4958
+ 'cest', coalesce(t.cest, g.cest),
4959
+ 'cfop', coalesce(nullif(t.cfop, ''), g.cfop),
4960
+ 'cst', coalesce(nullif(t.cst, ''), g.cst),
4961
+ 'csosn', g.csosn,
4962
+ 'origin', coalesce(nullif(t.icms_origin, ''), g.icms_origin),
4963
+ 'icmsRate', CASE WHEN coalesce(t.icms_rate, 0) > 0 THEN t.icms_rate ELSE g.icms_rate END,
4964
+ 'icmsBaseMode', g.icms_bc_mode,
4965
+ 'pisSituation', coalesce(nullif(t.pis_situation, ''), g.pis_situation),
4966
+ 'pisRate', CASE WHEN coalesce(t.pis_rate, 0) > 0 THEN t.pis_rate ELSE g.pis_rate END,
4967
+ 'cofinsSituation', coalesce(nullif(t.cofins_situation, ''), g.cofins_situation),
4968
+ 'cofinsRate', CASE WHEN coalesce(t.cofins_rate, 0) > 0 THEN t.cofins_rate ELSE g.cofins_rate END,
4969
+ 'ibsCbsSituation', coalesce(nullif(t.ibs_cbs_situation, ''), g.ibs_cbs_situation),
4970
+ 'ibsCbsClassification', coalesce(nullif(t.ibs_cbs_classification, ''), g.ibs_cbs_classification),
4971
+ 'group', g.name
4972
+ ) END
4973
+ ) ORDER BY i.sort_order, i.created_at)
4974
+ FROM public.items i
4975
+ LEFT JOIN public.products p ON p.id = i.product_id AND p.tenant_id = i.tenant_id
4976
+ LEFT JOIN public.plg_fiscalbr_product_tax_info t ON t.product_id = i.product_id AND t.tenant_id = i.tenant_id
4977
+ LEFT JOIN public.plg_fiscalbr_tax_groups g ON g.id = t.tax_group_id AND g.tenant_id = i.tenant_id
4978
+ WHERE i.order_id = o.id AND i.tenant_id = o.tenant_id
4979
+ ), '[]'::jsonb),
4980
+ -- Who the order is with: the buyer an NF-e names.
4981
+ 'customer', (
4982
+ SELECT jsonb_build_object(
4983
+ 'personId', c.id,
4984
+ 'name', c.name,
4985
+ 'document', c.document_number,
4986
+ 'email', c.email,
4987
+ 'stateRegistration', coalesce(
4988
+ nullif(btrim(c.custom_fields ->> 'stateRegistration'), ''),
4989
+ nullif(btrim(c.custom_fields ->> 'registrationNumber'), ''),
4990
+ nullif(btrim(c.metadata #>> '{legal,state_registration}'), ''),
4991
+ CASE WHEN length(regexp_replace(coalesce(c.document_number, ''), '\\D', '', 'g')) = 14
4992
+ THEN nullif(btrim(c.metadata #>> '{documents,rg}'), '') END),
4993
+ 'address', coalesce(
4994
+ (SELECT jsonb_build_object(
4995
+ 'street', a.street, 'number', a.number, 'complement', a.complement, 'district', a.district,
4996
+ 'city', a.city, 'state', a.state, 'postalCode', a.postal_code)
4997
+ FROM public.addresses a
4998
+ WHERE a.tenant_id = c.tenant_id AND a.owner_type = 'person' AND a.owner_id = c.id
4999
+ ORDER BY (a.kind = 'fiscal') DESC, (a.kind = 'billing') DESC, a.is_default DESC,
5000
+ (a.kind IN ('main', 'both')) DESC, a.updated_at DESC
5001
+ LIMIT 1),
5002
+ CASE WHEN nullif(btrim(c.address), '') IS NOT NULL THEN jsonb_build_object(
5003
+ 'street', c.address, 'number', c.metadata #>> '{address,number}',
5004
+ 'complement', c.metadata #>> '{address,complement}', 'district', c.metadata #>> '{address,neighborhood}',
5005
+ 'city', c.city, 'state', c.state, 'postalCode', c.postal_code) END)
5006
+ )
5007
+ FROM public.people c
5008
+ WHERE c.id = o.party_id AND c.tenant_id = o.tenant_id
5009
+ ),
5010
+ -- Anything that is not a site order is paid through the movements the
5011
+ -- order received, net of reversals, by method.
5012
+ 'checkout', v_checkout,
5013
+ 'payments', coalesce((
5014
+ SELECT jsonb_agg(jsonb_build_object('method', x.method, 'methodType', x.method_type, 'amount', x.amount))
5015
+ FROM (
5016
+ SELECT pm.name AS method, pt.name AS method_type,
5017
+ sum(CASE WHEN m.direction = 'credit' THEN m.paid_amount ELSE -m.paid_amount END) AS amount
5018
+ FROM public.plg_financial_movements m
5019
+ LEFT JOIN public.plg_financial_payment_methods pm ON pm.id = m.payment_method_id
5020
+ LEFT JOIN public.plg_financial_payment_method_types pt ON pt.id = pm.payment_method_type_id
5021
+ WHERE m.tenant_id = o.tenant_id AND m.movement_kind = 'payment' AND m.status = 'paid'
5022
+ AND (m.invoice_id = o.id OR m.financial_invoice_id IN (
5023
+ SELECT fi.id FROM public.plg_financial_invoices fi WHERE fi.order_id = o.id AND fi.tenant_id = o.tenant_id))
5024
+ GROUP BY pm.name, pt.name
5025
+ ) x WHERE x.amount <> 0
5026
+ ), '[]'::jsonb),
5027
+ 'notes', coalesce((
5028
+ SELECT jsonb_agg(jsonb_build_object('documentId', d.document_id, 'model', d.model, 'status', d.status))
5029
+ FROM public.plg_fiscalbr_documents d
5030
+ WHERE d.tenant_id = o.tenant_id AND d.order_id = o.id
5031
+ ), '[]'::jsonb)
5032
+ )
5033
+ FROM public.orders o
5034
+ LEFT JOIN app.units u ON u.id = o.unit_id AND u.tenant_id = o.tenant_id
5035
+ WHERE o.id = p_order AND o.tenant_id = p_tenant);
5036
+ END
5037
+ $$;
5038
+
5039
+ -- The note, opened before PlugNotas is called. One live note per order,
5040
+ -- whatever the model: a second "Emitir" while one is processing or authorized
5041
+ -- is refused (P0001 note_exists), so a double click never issues twice and an
5042
+ -- order never carries an NFC-e and an NF-e at once.
5043
+ CREATE OR REPLACE FUNCTION public.fiscalbr_note_open_for_service(
5044
+ p_tenant uuid, p_order uuid, p_model text, p_input jsonb
5045
+ )
5046
+ RETURNS jsonb
5047
+ LANGUAGE plpgsql SECURITY DEFINER
5048
+ SET search_path TO ''
5049
+ AS $$
5050
+ DECLARE
5051
+ v_order public.orders%ROWTYPE;
5052
+ v_doc uuid := gen_random_uuid();
5053
+ v_integration text;
5054
+ v_existing uuid;
5055
+ BEGIN
5056
+ IF p_model NOT IN ('nfce', 'nfe') THEN
5057
+ RAISE EXCEPTION 'fiscalbr_note_open: model % is not issued here', p_model USING ERRCODE = '22023';
5058
+ END IF;
5059
+ SELECT * INTO v_order FROM public.orders WHERE id = p_order AND tenant_id = p_tenant FOR UPDATE;
5060
+ IF NOT FOUND THEN
5061
+ RAISE EXCEPTION 'fiscalbr_note_open: order % is not of tenant %', p_order, p_tenant USING ERRCODE = 'P0002';
5062
+ END IF;
5063
+ SELECT document_id INTO v_existing FROM public.plg_fiscalbr_documents
5064
+ WHERE tenant_id = p_tenant AND order_id = p_order AND model IN ('nfce', 'nfe') AND status IN ('processing', 'authorized')
5065
+ LIMIT 1;
5066
+ IF v_existing IS NOT NULL THEN
5067
+ RAISE EXCEPTION 'note_exists' USING ERRCODE = 'P0001', DETAIL = v_existing::text;
5068
+ END IF;
5069
+
5070
+ -- Ours, and unique per company at PlugNotas: how a lost answer is found again.
5071
+ v_integration := 'csb-' || v_doc::text;
5072
+
5073
+ INSERT INTO public.documents (id, tenant_id, kind, title, status, unit_id, subject_type, subject_id, created_by, metadata)
5074
+ 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,
5075
+ 'order', p_order, nullif(p_input ->> 'userId', '')::uuid, jsonb_build_object('source', 'integration-service'));
5076
+
5077
+ INSERT INTO public.plg_fiscalbr_documents (
5078
+ document_id, tenant_id, unit_id, order_id, model, environment, status, series, provider,
5079
+ provider_integration_id, total_value, recipient_snapshot, request_payload, source_snapshot, emitted_by_user_id, metadata)
5080
+ VALUES (
5081
+ v_doc, p_tenant, v_order.unit_id, p_order, p_model, p_input ->> 'environment', 'processing', p_input ->> 'series', 'plugnotas',
5082
+ v_integration, (p_input ->> 'total')::numeric, p_input -> 'recipient', p_input -> 'request', p_input -> 'source',
5083
+ nullif(p_input ->> 'userId', '')::uuid, jsonb_build_object('emitterCnpj', p_input ->> 'emitterCnpj'));
5084
+
5085
+ INSERT INTO public.plg_fiscalbr_document_orders (tenant_id, document_id, order_id)
5086
+ VALUES (p_tenant, v_doc, p_order);
5087
+
5088
+ INSERT INTO public.plg_fiscalbr_document_events (tenant_id, unit_id, document_id, event_type, status, created_by_user_id)
5089
+ VALUES (p_tenant, v_order.unit_id, v_doc, 'issue_requested', 'processing', nullif(p_input ->> 'userId', '')::uuid);
5090
+
5091
+ RETURN jsonb_build_object('documentId', v_doc, 'integrationId', v_integration);
5092
+ END
5093
+ $$;
5094
+
5095
+ DO $$
5096
+ DECLARE
5097
+ f text;
5098
+ BEGIN
5099
+ FOREACH f IN ARRAY ARRAY[
5100
+ 'public.fiscalbr_order_for_note_for_service(uuid, uuid)',
5101
+ 'public.fiscalbr_note_open_for_service(uuid, uuid, text, jsonb)'
5102
+ ] LOOP
5103
+ EXECUTE format('REVOKE ALL ON FUNCTION %s FROM PUBLIC, anon, authenticated', f);
5104
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'fayz_integration') THEN
5105
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO fayz_integration', f);
5106
+ END IF;
5107
+ END LOOP;
5108
+ END
5109
+ $$;
5110
+ `;
5111
+ var MIGRATION_034_ONLY_WHAT_ARRIVED_ENTERS_STOCK = `-- ============================================================================
5112
+ -- 034 \u2014 only what arrived enters stock
5113
+ --
5114
+ -- Artorius accepted a Rio Quality note where a box of milk never came, and the
5115
+ -- milk went into stock anyway: accepting a note brought in every line as the
5116
+ -- note reads.
5117
+ --
5118
+ -- V1 contract: beautyplace #1031 ("Nota de compra, fase 3", migration
5119
+ -- 20261020160000, src/lib/danfeReceipt.ts, danfeStockEntry.ts):
5120
+ --
5121
+ -- * whoever receives the goods records, per line, how much did NOT arrive \u2014
5122
+ -- in the NOTE's unit (8 UN, 3 CX: the paper in their hand) \u2014 with a reason
5123
+ -- (faltou | avariado | vencido | recusado | outro) and a free note;
5124
+ -- * stock takes only what arrived: stock quantity \xD7 (1 \u2212 missing / billed).
5125
+ -- What is missing is not "to be received later" \u2014 it is not coming;
5126
+ -- * a line where nothing arrived enters nothing and asks for nothing
5127
+ -- (no unit, no product to name);
5128
+ -- * once the note entered stock the receipt no longer changes;
5129
+ -- * the payable is still born at the note's FULL value, and the finance
5130
+ -- person abates what did not arrive from it (financial/137,
5131
+ -- \`financial_abate_invoice_item\`). What is still to abate is derived \u2014
5132
+ -- line total \u2212 value received \u2014 so it cannot drift.
5133
+ --
5134
+ -- V2 already had the three columns (008) and a "Falta (qtd)" box, but the box
5135
+ -- was in STOCK units, subtracted only when the decision was saved, with no
5136
+ -- reason, no note and nothing on the payable. This file:
5137
+ --
5138
+ -- 1. converts what was recorded in stock units to note units (once \u2014 the
5139
+ -- block is skipped when the new save function is already in place);
5140
+ -- 2. constrains the reason vocabulary and the range;
5141
+ -- 3. rewrites fiscalbr_save_inbox_decision: the receipt travels under a NEW
5142
+ -- key, \`missing_quantity\` (note units), with \`shortage_reason\` and
5143
+ -- \`shortage_note\`. A payload without that key leaves the receipt as it
5144
+ -- is \u2014 so an app still on an older plugin, which sends the old
5145
+ -- stock-unit \`shortage_quantity\`, can no longer write a wrong number.
5146
+ -- \`stock_quantity\` goes back to what was billed (quantity \xD7 factor);
5147
+ -- 4. rewrites fiscalbr_accept_inbox_document as a whole (it had been patched
5148
+ -- in place by 015, 021, 025, 027 and 028; this is that body plus the
5149
+ -- receipt): each stock line enters as stock_quantity \xD7 received fraction,
5150
+ -- fully-missing lines are skipped, the payable line remembers which note
5151
+ -- line it came from (\`inboxItemId\`), and the result says how many lines
5152
+ -- came short and for how much;
5153
+ -- 5. adds fiscalbr_note_receipt_occurrences(invoice): what did not arrive,
5154
+ -- per line of the payable, and how much is still to abate.
5155
+ --
5156
+ -- Replay-safe: the conversion is gated, everything else is CREATE OR REPLACE
5157
+ -- or guarded DDL.
5158
+ -- ============================================================================
5159
+
5160
+ -- \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
5161
+ DO $m$
5162
+ DECLARE v_def text;
5163
+ BEGIN
5164
+ SELECT pg_get_functiondef(p.oid) INTO v_def FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
5165
+ WHERE n.nspname = 'public' AND p.proname = 'fiscalbr_save_inbox_decision';
5166
+ IF v_def IS NOT NULL AND position('missing_quantity' in v_def) > 0 THEN RETURN; END IF;
5167
+
5168
+ -- The old save wrote stock_quantity = billed \xD7 factor \u2212 missing(stock units).
5169
+ -- missing / factor is the same goods in the note's unit, and billed \xD7 factor
5170
+ -- is what stock_quantity means from here on; the accepted quantity is unchanged.
5171
+ UPDATE public.plg_fiscalbr_inbox_items
5172
+ SET shortage_quantity = round(shortage_quantity / conversion_factor, 4),
5173
+ updated_at = now()
5174
+ WHERE shortage_quantity > 0 AND conversion_factor > 0 AND conversion_factor <> 1;
5175
+ UPDATE public.plg_fiscalbr_inbox_items
5176
+ SET stock_quantity = quantity_commercial * conversion_factor,
5177
+ shortage_reason = coalesce(shortage_reason, 'faltou'),
5178
+ updated_at = now()
5179
+ WHERE shortage_quantity > 0 AND stock_movement_id IS NULL;
5180
+ UPDATE public.plg_fiscalbr_inbox_items
5181
+ SET shortage_quantity = NULL, shortage_reason = NULL, shortage_note = NULL, updated_at = now()
5182
+ WHERE shortage_quantity IS NOT NULL AND shortage_quantity <= 0;
5183
+ UPDATE public.plg_fiscalbr_inbox_items
5184
+ SET shortage_quantity = quantity_commercial, updated_at = now()
5185
+ WHERE shortage_quantity > quantity_commercial;
5186
+ END
5187
+ $m$;
5188
+
5189
+ -- \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
5190
+ -- NOT VALID: rows from before this file are not re-judged; every write is.
5191
+ ALTER TABLE public.plg_fiscalbr_inbox_items DROP CONSTRAINT IF EXISTS plg_fiscalbr_inbox_items_shortage_chk;
5192
+ ALTER TABLE public.plg_fiscalbr_inbox_items ADD CONSTRAINT plg_fiscalbr_inbox_items_shortage_chk CHECK (
5193
+ (shortage_quantity IS NULL OR (shortage_quantity > 0 AND shortage_quantity <= quantity_commercial))
5194
+ AND (shortage_reason IS NULL OR shortage_reason IN ('faltou', 'avariado', 'vencido', 'recusado', 'outro'))
5195
+ ) NOT VALID;
5196
+
5197
+ COMMENT ON COLUMN public.plg_fiscalbr_inbox_items.shortage_quantity IS
5198
+ 'Receipt check: how much of this line did NOT arrive, in the note''s unit. Stock takes only what arrived.';
5199
+ COMMENT ON COLUMN public.plg_fiscalbr_inbox_items.shortage_reason IS
5200
+ 'faltou | avariado | vencido | recusado | outro';
5201
+ COMMENT ON COLUMN public.plg_fiscalbr_inbox_items.stock_quantity IS
5202
+ 'What the note bills, in stock units (quantity \xD7 conversion factor). What enters is this \xD7 the received fraction.';
5203
+
5204
+ -- \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
5205
+ CREATE OR REPLACE FUNCTION public.fiscalbr_save_inbox_decision(
5206
+ p_document_id uuid,
5207
+ p_items jsonb,
5208
+ p_default_chart_account_id uuid DEFAULT NULL,
5209
+ p_default_location_id uuid DEFAULT NULL,
5210
+ p_duplicates jsonb DEFAULT NULL)
5211
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO '' AS $function$
5212
+ DECLARE
5213
+ v_tenant uuid := public.plg_financial_require_tenant();
5214
+ v_doc public.plg_fiscalbr_inbox_documents%ROWTYPE;
5215
+ v_row jsonb;
5216
+ v_done integer := 0;
5217
+ v_total integer;
5218
+ v_line public.plg_fiscalbr_inbox_items%ROWTYPE;
5219
+ v_missing numeric;
5220
+ v_reason text;
5221
+ BEGIN
5222
+ SELECT * INTO v_doc FROM public.plg_fiscalbr_inbox_documents
5223
+ WHERE tenant_id = v_tenant AND id = p_document_id;
5224
+ IF NOT FOUND THEN
5225
+ RAISE EXCEPTION 'fiscalbr: nota % n\xE3o encontrada neste tenant', p_document_id USING ERRCODE = 'P0002';
5226
+ END IF;
5227
+ PERFORM public.plg_financial_require_permission('financial.edit', v_doc.unit_id);
5228
+
5229
+ -- Settled = stocked, or a payable with no stock line left to receive (027).
5230
+ 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
5231
+ WHERE x.tenant_id = v_tenant AND x.inbox_document_id = v_doc.id
5232
+ AND x.stock_movement_id IS NULL
5233
+ AND (x.entry_type IS NULL OR x.entry_type = '' OR x.entry_type IN ('insumo','revenda','patrimonio','uso_consumo')))) THEN
5234
+ RAISE EXCEPTION 'fiscalbr: nota % j\xE1 foi aceita \u2014 a decis\xE3o n\xE3o muda depois do estoque', p_document_id
5235
+ USING ERRCODE = '23514';
5236
+ END IF;
5237
+
5238
+ UPDATE public.plg_fiscalbr_inbox_documents SET
5239
+ default_chart_account_id = coalesce(p_default_chart_account_id, default_chart_account_id),
5240
+ default_location_id = coalesce(p_default_location_id, default_location_id),
5241
+ reviewed_at = now(), updated_at = now()
5242
+ WHERE id = v_doc.id;
5243
+
5244
+ FOR v_row IN SELECT * FROM jsonb_array_elements(coalesce(p_items, '[]'::jsonb)) LOOP
5245
+ SELECT * INTO v_line FROM public.plg_fiscalbr_inbox_items
5246
+ WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id AND id = (v_row->>'id')::uuid;
5247
+ CONTINUE WHEN NOT FOUND;
5248
+
5249
+ -- The receipt: only a payload that names \`missing_quantity\` (note units)
5250
+ -- writes it. Without the key it stays as it is.
5251
+ v_missing := CASE WHEN v_line.shortage_quantity > 0
5252
+ THEN least(v_line.shortage_quantity, v_line.quantity_commercial) END;
5253
+ v_reason := CASE WHEN v_missing IS NOT NULL THEN coalesce(v_line.shortage_reason, 'faltou') END;
5254
+ IF v_row ? 'missing_quantity' THEN
5255
+ BEGIN
5256
+ v_missing := nullif(v_row->>'missing_quantity', '')::numeric;
5257
+ EXCEPTION WHEN OTHERS THEN
5258
+ RAISE EXCEPTION 'fiscalbr: item %: missing quantity is not a number', v_line.item_number
5259
+ USING ERRCODE = '22023', HINT = 'RECEIPT_BAD_QUANTITY';
5260
+ END;
5261
+ IF v_missing IS NOT NULL AND v_missing <= 0 THEN v_missing := NULL; END IF;
5262
+ IF v_missing IS NOT NULL AND v_missing > coalesce(v_line.quantity_commercial, 0) THEN
5263
+ RAISE EXCEPTION 'fiscalbr: item %: % did not arrive, but the note bills only %',
5264
+ v_line.item_number, v_missing, v_line.quantity_commercial
5265
+ USING ERRCODE = '22023', HINT = 'RECEIPT_MORE_THAN_BILLED';
5266
+ END IF;
5267
+ v_reason := CASE WHEN v_missing IS NULL THEN NULL
5268
+ ELSE coalesce(nullif(v_row->>'shortage_reason', ''), 'faltou') END;
5269
+ IF v_reason IS NOT NULL AND v_reason NOT IN ('faltou', 'avariado', 'vencido', 'recusado', 'outro') THEN
5270
+ RAISE EXCEPTION 'fiscalbr: item %: unknown reason %', v_line.item_number, v_reason
5271
+ USING ERRCODE = '22023', HINT = 'RECEIPT_BAD_REASON';
5272
+ END IF;
5273
+ END IF;
5274
+
5275
+ UPDATE public.plg_fiscalbr_inbox_items i SET
5276
+ product_id = nullif(v_row->>'product_id', '')::uuid,
5277
+ entry_type = nullif(v_row->>'entry_type', ''),
5278
+ chart_account_id = nullif(v_row->>'chart_account_id', '')::uuid,
5279
+ stock_unit_id = nullif(v_row->>'stock_unit_id', '')::uuid,
5280
+ conversion_factor = coalesce(nullif(v_row->>'conversion_factor', '')::numeric, 1),
5281
+ cost_mode = coalesce(nullif(v_row->>'cost_mode', ''), 'novo'),
5282
+ shortage_quantity = v_missing,
5283
+ shortage_reason = v_reason,
5284
+ shortage_note = CASE WHEN v_missing IS NULL THEN NULL
5285
+ WHEN v_row ? 'missing_quantity' THEN nullif(btrim(coalesce(v_row->>'shortage_note', '')), '')
5286
+ ELSE i.shortage_note END,
5287
+ -- Quem escreveu. Ausente na chave \xE9 NULL, que \xE9 \xABuma pessoa escolheu\xBB.
5288
+ suggested_by = nullif(v_row->>'suggested_by', ''),
5289
+ suggestion_confidence = nullif(v_row->>'suggestion_confidence', '')::numeric,
5290
+ -- What the note bills, in stock units. The receipt is applied on accept.
5291
+ stock_quantity = i.quantity_commercial * coalesce(nullif(v_row->>'conversion_factor', '')::numeric, 1),
5292
+ unit_cost_new = CASE WHEN coalesce(nullif(v_row->>'conversion_factor', '')::numeric, 1) > 0
5293
+ THEN i.unit_price_commercial / coalesce(nullif(v_row->>'conversion_factor', '')::numeric, 1) END,
5294
+ -- Uma linha est\xE1 conciliada quando sabe o que \xE9. Despesa e servi\xE7o n\xE3o
5295
+ -- pedem produto: elas nunca v\xE3o virar estoque.
5296
+ reconciled = CASE
5297
+ WHEN nullif(v_row->>'entry_type', '') IN ('despesa','servico') THEN true
5298
+ ELSE nullif(v_row->>'product_id', '') IS NOT NULL
5299
+ END,
5300
+ updated_at = now()
5301
+ WHERE i.tenant_id = v_tenant AND i.inbox_document_id = v_doc.id AND i.id = v_line.id;
5302
+ v_done := v_done + 1;
5303
+ END LOOP;
5304
+
5305
+ IF p_duplicates IS NOT NULL THEN
5306
+ DELETE FROM public.plg_fiscalbr_inbox_duplicates
5307
+ WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id;
5308
+ INSERT INTO public.plg_fiscalbr_inbox_duplicates (
5309
+ tenant_id, inbox_document_id, duplicate_index, number, due_date, value,
5310
+ payment_type, barcode, pix_key, payment_method_id)
5311
+ SELECT v_tenant, v_doc.id, coalesce((d->>'index')::int, ord), d->>'number',
5312
+ nullif(d->>'due_date', '')::date, (d->>'value')::numeric,
5313
+ nullif(d->>'payment_type', ''), nullif(d->>'barcode', ''),
5314
+ nullif(d->>'pix_key', ''), nullif(d->>'payment_method_id', '')::uuid
5315
+ FROM jsonb_array_elements(p_duplicates) WITH ORDINALITY AS t(d, ord);
5316
+ END IF;
5317
+
5318
+ SELECT count(*) INTO v_total FROM public.plg_fiscalbr_inbox_items
5319
+ WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id;
5320
+
5321
+ UPDATE public.plg_fiscalbr_inbox_documents SET status = CASE
5322
+ WHEN (SELECT count(*) FROM public.plg_fiscalbr_inbox_items
5323
+ WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id AND reconciled) = v_total
5324
+ THEN 'accepted' ELSE 'partial' END
5325
+ WHERE id = v_doc.id;
5326
+
5327
+ RETURN jsonb_build_object('document_id', v_doc.id, 'saved', v_done, 'items', v_total,
5328
+ 'reconciled', (SELECT count(*) FROM public.plg_fiscalbr_inbox_items
5329
+ WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id AND reconciled));
5330
+ END $function$;
5331
+
5332
+ REVOKE ALL ON FUNCTION public.fiscalbr_save_inbox_decision(uuid, jsonb, uuid, uuid, jsonb) FROM PUBLIC;
5333
+ GRANT EXECUTE ON FUNCTION public.fiscalbr_save_inbox_decision(uuid, jsonb, uuid, uuid, jsonb) TO authenticated;
5334
+
5335
+ -- \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
5336
+ CREATE OR REPLACE FUNCTION public.fiscalbr_accept_inbox_document(
5337
+ p_document_id uuid,
5338
+ p_location_id uuid DEFAULT NULL)
5339
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path TO '' AS $function$
5340
+ DECLARE
5341
+ v_tenant uuid := public.plg_financial_require_tenant();
5342
+ v_doc public.plg_fiscalbr_inbox_documents%ROWTYPE;
5343
+ v_loc uuid;
5344
+ v_lines jsonb := '[]'::jsonb;
5345
+ v_insts jsonb := '[]'::jsonb;
5346
+ v_recv jsonb;
5347
+ v_inv jsonb;
5348
+ v_it record;
5349
+ v_no integer := 0;
5350
+ v_bearing integer := 0;
5351
+ v_total numeric := 0;
5352
+ v_stock_n integer := 0;
5353
+ v_key text;
5354
+ v_invoice uuid;
5355
+ v_item_ids uuid[] := '{}';
5356
+ v_fraction numeric;
5357
+ v_qty numeric;
5358
+ v_short_n integer := 0;
5359
+ v_short_v numeric := 0;
5360
+ -- A compet\xEAncia: o DIA da emiss\xE3o, n\xE3o o instante.
5361
+ v_competence date;
5362
+ BEGIN
5363
+ SELECT * INTO v_doc FROM public.plg_fiscalbr_inbox_documents
5364
+ WHERE tenant_id = v_tenant AND id = p_document_id;
5365
+ IF NOT FOUND THEN
5366
+ RAISE EXCEPTION 'fiscalbr: nota % n\xE3o encontrada neste tenant', p_document_id USING ERRCODE = 'P0002';
5367
+ END IF;
5368
+ PERFORM public.plg_financial_require_permission('financial.create', v_doc.unit_id);
5369
+
5370
+ -- Settled = stocked, or a payable with no stock line left to receive (027).
5371
+ 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
5372
+ WHERE x.tenant_id = v_tenant AND x.inbox_document_id = v_doc.id
5373
+ AND x.stock_movement_id IS NULL
5374
+ AND (x.entry_type IS NULL OR x.entry_type = '' OR x.entry_type IN ('insumo','revenda','patrimonio','uso_consumo')))) THEN
5375
+ RETURN jsonb_build_object('document_id', v_doc.id, 'already_accepted', true,
5376
+ 'invoice_id', v_doc.invoice_id, 'operation_id', v_doc.inventory_operation_id);
5377
+ END IF;
5378
+
5379
+ v_loc := coalesce(p_location_id, v_doc.default_location_id);
5380
+ v_competence := (v_doc.issue_date)::date;
5381
+
5382
+ IF EXISTS (SELECT 1 FROM public.plg_fiscalbr_inbox_items
5383
+ WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id
5384
+ AND (entry_type IS NULL OR entry_type = '')) THEN
5385
+ RAISE EXCEPTION 'fiscalbr: h\xE1 item sem tipo de registro \u2014 conciliar antes de aceitar'
5386
+ USING ERRCODE = '23514';
5387
+ END IF;
5388
+
5389
+ -- What did not arrive, on every line (stock-bearing or not): it is what the
5390
+ -- finance person will abate from the payable.
5391
+ SELECT count(*), coalesce(sum(round(coalesce(i.total_price, 0) * least(i.shortage_quantity, i.quantity_commercial)
5392
+ / nullif(i.quantity_commercial, 0), 2)), 0)
5393
+ INTO v_short_n, v_short_v
5394
+ FROM public.plg_fiscalbr_inbox_items i
5395
+ WHERE i.tenant_id = v_tenant AND i.inbox_document_id = v_doc.id AND i.shortage_quantity > 0;
5396
+
5397
+ FOR v_it IN
5398
+ SELECT * FROM public.plg_fiscalbr_inbox_items
5399
+ WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id
5400
+ AND entry_type IN ('insumo','revenda','patrimonio','uso_consumo')
5401
+ ORDER BY item_number
5402
+ LOOP
5403
+ v_bearing := v_bearing + 1;
5404
+ -- The received fraction: 1 = all of it, 0 = nothing came.
5405
+ v_fraction := CASE WHEN coalesce(v_it.quantity_commercial, 0) <= 0 THEN 1
5406
+ ELSE 1 - least(greatest(coalesce(v_it.shortage_quantity, 0), 0), v_it.quantity_commercial)
5407
+ / v_it.quantity_commercial END;
5408
+ -- Nothing came: nothing enters, and there is nothing to name.
5409
+ CONTINUE WHEN v_fraction <= 0.000001;
5410
+ IF v_it.stock_unit_id IS NULL THEN
5411
+ RAISE EXCEPTION 'fiscalbr: item % entra no estoque sem unidade \u2014 escolha a unidade de estoque', v_it.item_number
5412
+ USING ERRCODE = '23514';
5413
+ END IF;
5414
+ IF v_it.product_id IS NULL THEN
5415
+ RAISE EXCEPTION 'fiscalbr: item % \xE9 % e n\xE3o tem produto vinculado', v_it.item_number, v_it.entry_type
5416
+ USING ERRCODE = '23514';
5417
+ END IF;
5418
+ v_qty := round(coalesce(v_it.stock_quantity, v_it.quantity_commercial * v_it.conversion_factor) * v_fraction, 4);
5419
+ CONTINUE WHEN v_qty <= 0;
5420
+ v_no := v_no + 1;
5421
+ v_item_ids := v_item_ids || v_it.id;
5422
+ v_lines := v_lines || jsonb_build_object(
5423
+ 'product_id', v_it.product_id,
5424
+ 'quantity', v_qty,
5425
+ 'unit_cost', coalesce(v_it.unit_cost_new, v_it.unit_price_commercial / v_it.conversion_factor),
5426
+ 'measurement_unit_id', v_it.stock_unit_id,
5427
+ 'notes', v_it.description);
5428
+ END LOOP;
5429
+ v_stock_n := v_no;
5430
+
5431
+ IF v_stock_n > 0 THEN
5432
+ IF v_loc IS NULL THEN
5433
+ RAISE EXCEPTION 'fiscalbr: a nota tem % linha(s) de estoque e nenhum local de estoque escolhido', v_stock_n
5434
+ USING ERRCODE = '22023';
5435
+ END IF;
5436
+ v_recv := public.inventory_receive(
5437
+ v_loc::uuid,
5438
+ v_lines::jsonb,
5439
+ jsonb_build_object(
5440
+ 'supplier_id', v_doc.supplier_party_id,
5441
+ -- O documento do estoque tamb\xE9m quer o DIA.
5442
+ 'date', v_competence,
5443
+ 'type', 'nfe',
5444
+ 'ref', 'NF-e ' || coalesce(v_doc.nfe_number, '?'),
5445
+ 'notes', 'Entrada via DANFE NF-e ' || coalesce(v_doc.nfe_number, '?'),
5446
+ 'reason', 'Entrada via DANFE NF-e ' || coalesce(v_doc.nfe_number, '?')),
5447
+ ('nfe:' || v_doc.access_key)::text);
5448
+
5449
+ UPDATE public.plg_fiscalbr_inbox_items i
5450
+ SET stock_movement_id = m.movement_id, updated_at = now()
5451
+ FROM (
5452
+ SELECT v_item_ids[(mov->>'line_no')::int] AS item_id, (mov->>'id')::uuid AS movement_id
5453
+ FROM jsonb_array_elements(coalesce(v_recv->'movements', '[]'::jsonb)) AS t(mov)
5454
+ WHERE (mov->>'line_no') IS NOT NULL
5455
+ ) m
5456
+ WHERE i.tenant_id = v_tenant AND i.id = m.item_id;
5457
+ END IF;
5458
+
5459
+ IF v_doc.invoice_id IS NOT NULL THEN
5460
+ -- Half-done in the V1: the payable exists; only the stock is missing.
5461
+ v_invoice := v_doc.invoice_id;
5462
+ SELECT total INTO v_total FROM public.plg_financial_invoices WHERE id = v_invoice;
5463
+ v_insts := '[]'::jsonb;
5464
+ ELSE
5465
+ SELECT coalesce(sum(value), 0),
5466
+ coalesce(jsonb_agg(jsonb_build_object(
5467
+ 'number', coalesce(duplicate_index, 1),
5468
+ 'due_date', coalesce(due_date, v_competence, current_date),
5469
+ 'amount', round(value, 2),
5470
+ 'metadata', jsonb_strip_nulls(jsonb_build_object(
5471
+ 'barcode', barcode, 'pixKey', pix_key, 'paymentType', payment_type,
5472
+ 'danfeNumber', number))) ORDER BY duplicate_index), '[]'::jsonb)
5473
+ INTO v_total, v_insts
5474
+ FROM public.plg_fiscalbr_inbox_duplicates
5475
+ WHERE tenant_id = v_tenant AND inbox_document_id = v_doc.id;
5476
+
5477
+ IF jsonb_array_length(v_insts) = 0 THEN
5478
+ v_total := round(coalesce(v_doc.total_value, 0), 2);
5479
+ v_insts := jsonb_build_array(jsonb_build_object(
5480
+ 'number', 1, 'due_date', coalesce(v_competence, current_date), 'amount', v_total));
5481
+ ELSE
5482
+ v_total := round(v_total, 2);
5483
+ END IF;
5484
+
5485
+ v_key := 'danfe:' || v_doc.access_key;
5486
+
5487
+ -- The payable is born at the note's full value (V1 rule): the supplier
5488
+ -- billed it, and what did not arrive is abated by finance.
5489
+ v_inv := public.financial_create_invoice(
5490
+ 'payable'::text,
5491
+ v_total::numeric,
5492
+ v_doc.supplier_party_id::uuid,
5493
+ NULL::uuid,
5494
+ v_doc.unit_id::uuid,
5495
+ v_insts::jsonb,
5496
+ v_competence::date,
5497
+ ('NF-e ' || coalesce(v_doc.nfe_number, '?') || ' \xB7 ' || coalesce(v_doc.supplier_name, 'fornecedor'))::text,
5498
+ NULL::text,
5499
+ jsonb_build_object(
5500
+ 'source', 'danfe',
5501
+ 'danfe', jsonb_strip_nulls(jsonb_build_object(
5502
+ 'accessKey', v_doc.access_key, 'number', v_doc.nfe_number,
5503
+ 'series', v_doc.nfe_series, 'supplierName', v_doc.supplier_name,
5504
+ 'supplierCnpj', v_doc.supplier_cnpj,
5505
+ 'noteTotal', v_doc.total_value,
5506
+ 'inboxDocumentId', v_doc.id)))::jsonb,
5507
+ v_key::text);
5508
+ v_invoice := (v_inv->>'invoice_id')::uuid;
5509
+
5510
+ INSERT INTO public.items (tenant_id, invoice_id, product_id, chart_account_id, name, quantity, unit_price, total, sort_order, metadata)
5511
+ SELECT v_tenant, v_invoice, i.product_id, coalesce(i.chart_account_id, v_doc.default_chart_account_id),
5512
+ i.description, i.quantity_commercial, i.unit_price_commercial,
5513
+ round(coalesce(i.total_price, 0), 2), i.item_number,
5514
+ jsonb_strip_nulls(jsonb_build_object(
5515
+ 'itemKind', CASE WHEN i.product_id IS NOT NULL THEN 'product' ELSE 'other' END,
5516
+ 'referenceId', i.product_id, 'entryType', i.entry_type,
5517
+ 'chartAccountId', coalesce(i.chart_account_id, v_doc.default_chart_account_id),
5518
+ 'ncm', i.ncm, 'cfop', i.cfop,
5519
+ 'supplierProductCode', i.supplier_product_code,
5520
+ -- The note line this payable line came from: the receipt check
5521
+ -- reaches the payable through it.
5522
+ 'inboxItemId', i.id))
5523
+ FROM public.plg_fiscalbr_inbox_items i
5524
+ WHERE i.tenant_id = v_tenant AND i.inbox_document_id = v_doc.id
5525
+ ORDER BY i.item_number
5526
+ ON CONFLICT DO NOTHING;
5527
+ PERFORM public.plg_fiscalbr_note_charge_lines(v_tenant, v_doc.id, v_invoice, v_total);
5528
+ END IF;
5529
+
5530
+ UPDATE public.plg_fiscalbr_inbox_documents SET
5531
+ invoice_id = v_invoice,
5532
+ inventory_operation_id = coalesce((v_recv->>'operation_id')::uuid, inventory_operation_id),
5533
+ -- A note whose stock lines all came short was still received: nothing is
5534
+ -- left to enter, so it is settled too.
5535
+ stocked_at = CASE WHEN v_bearing > 0 THEN now() ELSE stocked_at END,
5536
+ status = 'accepted', updated_at = now()
5537
+ WHERE id = v_doc.id;
5538
+
5539
+ INSERT INTO public.plg_fiscalbr_supplier_product_map (
5540
+ tenant_id, supplier_cnpj, supplier_product_code, product_id, entry_type,
5541
+ chart_account_id, stock_unit_id, conversion_factor, cost_mode, hit_count, last_used_at)
5542
+ SELECT v_tenant, v_doc.supplier_cnpj, i.supplier_product_code, i.product_id,
5543
+ i.entry_type, coalesce(i.chart_account_id, v_doc.default_chart_account_id),
5544
+ i.stock_unit_id, i.conversion_factor, i.cost_mode, 1, now()
5545
+ FROM public.plg_fiscalbr_inbox_items i
5546
+ WHERE i.tenant_id = v_tenant AND i.inbox_document_id = v_doc.id
5547
+ AND i.product_id IS NOT NULL
5548
+ AND coalesce(v_doc.supplier_cnpj, '') <> ''
5549
+ AND coalesce(i.supplier_product_code, '') <> ''
5550
+ ON CONFLICT (tenant_id, supplier_cnpj, supplier_product_code) DO UPDATE SET
5551
+ product_id = EXCLUDED.product_id,
5552
+ entry_type = EXCLUDED.entry_type,
5553
+ chart_account_id = coalesce(EXCLUDED.chart_account_id, public.plg_fiscalbr_supplier_product_map.chart_account_id),
5554
+ stock_unit_id = coalesce(EXCLUDED.stock_unit_id, public.plg_fiscalbr_supplier_product_map.stock_unit_id),
5555
+ conversion_factor = EXCLUDED.conversion_factor,
5556
+ cost_mode = EXCLUDED.cost_mode,
5557
+ hit_count = public.plg_fiscalbr_supplier_product_map.hit_count + 1,
5558
+ last_used_at = now(),
5559
+ updated_at = now();
5560
+
5561
+ RETURN jsonb_build_object(
5562
+ 'document_id', v_doc.id, 'already_accepted', false,
5563
+ 'invoice_id', v_invoice, 'invoice_total', v_total,
5564
+ 'installments', jsonb_array_length(v_insts),
5565
+ 'operation_id', v_recv->>'operation_id',
5566
+ 'stock_lines', v_stock_n,
5567
+ 'shortage_lines', v_short_n,
5568
+ 'shortage_value', v_short_v,
5569
+ 'movements', coalesce(v_recv->'movements', '[]'::jsonb));
5570
+ END $function$;
5571
+
5572
+ REVOKE ALL ON FUNCTION public.fiscalbr_accept_inbox_document(uuid, uuid) FROM PUBLIC;
5573
+ GRANT EXECUTE ON FUNCTION public.fiscalbr_accept_inbox_document(uuid, uuid) TO authenticated;
5574
+
5575
+ -- \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
5576
+ -- One row per note line with a shortage. \`pending\` is what is still to abate:
5577
+ -- the payable line bills more than what arrived is worth. A cancelled line, or
5578
+ -- a note line with no payable line (a V1 copy), has nothing pending.
5579
+ CREATE OR REPLACE FUNCTION public.fiscalbr_note_receipt_occurrences(p_invoice_id uuid)
5580
+ RETURNS TABLE (
5581
+ inbox_item_id uuid, document_id uuid, nfe_number text, item_number integer, description text, unit text,
5582
+ note_quantity numeric, shortage_quantity numeric, shortage_reason text, shortage_note text,
5583
+ shortage_value numeric, received_value numeric,
5584
+ invoice_item_id uuid, invoice_item_total numeric, invoice_item_cancelled boolean, pending numeric)
5585
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO '' AS $function$
5586
+ DECLARE
5587
+ v_tenant uuid := public.plg_financial_require_tenant();
5588
+ v_unit uuid;
5589
+ BEGIN
5590
+ SELECT f.unit_id INTO v_unit FROM public.plg_financial_invoices f
5591
+ WHERE f.id = p_invoice_id AND f.tenant_id = v_tenant AND f.direction = 'payable';
5592
+ IF NOT FOUND THEN RETURN; END IF;
5593
+ PERFORM public.plg_financial_require_permission('financial.read', v_unit);
5594
+
5595
+ RETURN QUERY
5596
+ WITH short AS (
5597
+ SELECT i.id, d.id AS doc_id, d.nfe_number, i.item_number, i.description, i.unit_commercial,
5598
+ i.quantity_commercial AS q,
5599
+ least(i.shortage_quantity, i.quantity_commercial) AS s,
5600
+ i.shortage_reason, i.shortage_note,
5601
+ round(coalesce(i.total_price, 0) * least(i.shortage_quantity, i.quantity_commercial)
5602
+ / nullif(i.quantity_commercial, 0), 2) AS sv,
5603
+ round(coalesce(i.total_price, 0), 2) AS tp
5604
+ FROM public.plg_fiscalbr_inbox_documents d
5605
+ JOIN public.plg_fiscalbr_inbox_items i ON i.inbox_document_id = d.id AND i.tenant_id = d.tenant_id
5606
+ WHERE d.tenant_id = v_tenant AND d.invoice_id = p_invoice_id AND i.shortage_quantity > 0
5607
+ )
5608
+ SELECT s.id, s.doc_id, s.nfe_number, s.item_number, s.description, s.unit_commercial,
5609
+ s.q, s.s, s.shortage_reason, s.shortage_note,
5610
+ coalesce(s.sv, 0), s.tp - coalesce(s.sv, 0),
5611
+ it.id, it.total, it.cancelled_at IS NOT NULL,
5612
+ CASE WHEN it.id IS NULL OR it.cancelled_at IS NOT NULL THEN 0::numeric
5613
+ ELSE greatest(round(it.total - (s.tp - coalesce(s.sv, 0)), 2), 0) END
5614
+ FROM short s
5615
+ LEFT JOIN LATERAL (
5616
+ SELECT x.id, x.total, x.cancelled_at FROM public.items x
5617
+ WHERE x.tenant_id = v_tenant AND x.invoice_id = p_invoice_id
5618
+ AND (x.metadata->>'inboxItemId' = s.id::text
5619
+ -- Payables opened before 034 carry no inboxItemId: the note's
5620
+ -- product lines are written in item order with their CFOP.
5621
+ OR (NOT x.metadata ? 'inboxItemId' AND x.metadata ? 'cfop'
5622
+ AND NOT x.metadata ? 'noteCharge' AND x.sort_order = s.item_number))
5623
+ ORDER BY (x.metadata ? 'inboxItemId') DESC
5624
+ LIMIT 1
5625
+ ) it ON true
5626
+ ORDER BY s.item_number;
5627
+ END $function$;
5628
+
5629
+ REVOKE ALL ON FUNCTION public.fiscalbr_note_receipt_occurrences(uuid) FROM PUBLIC, anon;
5630
+ GRANT EXECUTE ON FUNCTION public.fiscalbr_note_receipt_occurrences(uuid) TO authenticated, service_role;
5631
+ `;
4874
5632
  var MIGRATIONS = [
4875
5633
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
4876
5634
  { id: "001_preserve_terminal_results_and_recover_leases", sql: MIGRATION_001_PRESERVE_TERMINAL_RESULTS_AND_RECOVER_LEASES },
@@ -4904,9 +5662,11 @@ var MIGRATIONS = [
4904
5662
  { id: "029_the_service_writes_the_intake_health", sql: MIGRATION_029_THE_SERVICE_WRITES_THE_INTAKE_HEALTH },
4905
5663
  { id: "030_the_service_onboards_the_emitter", sql: MIGRATION_030_THE_SERVICE_ONBOARDS_THE_EMITTER },
4906
5664
  { id: "031_the_service_issues_the_note", sql: MIGRATION_031_THE_SERVICE_ISSUES_THE_NOTE },
4907
- { id: "032_a_delivered_note_carries_where_it_goes", sql: MIGRATION_032_A_DELIVERED_NOTE_CARRIES_WHERE_IT_GOES }
5665
+ { id: "032_a_delivered_note_carries_where_it_goes", sql: MIGRATION_032_A_DELIVERED_NOTE_CARRIES_WHERE_IT_GOES },
5666
+ { id: "033_a_company_buyer_gets_its_nfe", sql: MIGRATION_033_A_COMPANY_BUYER_GETS_ITS_NFE },
5667
+ { id: "034_only_what_arrived_enters_stock", sql: MIGRATION_034_ONLY_WHAT_ARRIVED_ENTERS_STOCK }
4908
5668
  ];
4909
5669
 
4910
- 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 };
5670
+ 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 };
4911
5671
  //# sourceMappingURL=main.js.map
4912
5672
  //# sourceMappingURL=main.js.map