@flowselections/floriday-verkoop-module 1.0.107 → 1.0.111
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-lib/components/verkoop/CreateOrderPage.d.ts.map +1 -1
- package/dist-lib/components/verkoop/CreateOrderPage.js +6 -0
- package/dist-lib/integrations/supabase/types.d.ts +71 -0
- package/dist-lib/integrations/supabase/types.d.ts.map +1 -1
- package/dist-lib/lib/create-order.functions.d.ts +6 -0
- package/dist-lib/lib/create-order.functions.d.ts.map +1 -1
- package/dist-lib/lib/create-order.functions.js +40 -12
- package/dist-lib/lib/customer-stickers.check.js +4 -1
- package/dist-lib/lib/customer-stickers.d.ts +10 -0
- package/dist-lib/lib/customer-stickers.d.ts.map +1 -1
- package/dist-lib/lib/customer-stickers.js +6 -1
- package/dist-lib/lib/module-version.d.ts +1 -1
- package/dist-lib/lib/module-version.js +1 -1
- package/package.json +1 -1
- package/schema/verkoop.sql +155 -0
|
@@ -126,6 +126,7 @@ export declare const createManualOrder: import("@tanstack/start-client-core").Op
|
|
|
126
126
|
userId: string;
|
|
127
127
|
claims: import("@supabase/auth-js").User;
|
|
128
128
|
}, undefined, undefined, undefined>], (input: unknown) => {
|
|
129
|
+
idempotencyKey: string;
|
|
129
130
|
customerId: string;
|
|
130
131
|
customerName: string;
|
|
131
132
|
deliveryLocationId: string;
|
|
@@ -160,6 +161,11 @@ export declare const createManualOrder: import("@tanstack/start-client-core").Op
|
|
|
160
161
|
}, Promise<{
|
|
161
162
|
ok: true;
|
|
162
163
|
orderId: string;
|
|
164
|
+
alreadyExisted: true;
|
|
165
|
+
} | {
|
|
166
|
+
ok: true;
|
|
167
|
+
orderId: string;
|
|
168
|
+
alreadyExisted?: undefined;
|
|
163
169
|
}>>;
|
|
164
170
|
export declare const cancelLocalOrder: import("@tanstack/start-client-core").OptionalFetcher<readonly [import("@tanstack/start-client-core").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
|
|
165
171
|
supabase: import("../integrations/supabase/auth-middleware.js").AuthedSupabaseClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-order.functions.d.ts","sourceRoot":"","sources":["../../src/lib/create-order.functions.ts"],"names":[],"mappings":"AAcA,eAAO,MAAM,2BAA2B;;;;;;GA+CpC,CAAC;AAIL,eAAO,MAAM,2BAA2B;;;;0CAElB,OAAO;;;;GAoDzB,CAAC;AAWL,eAAO,MAAM,0BAA0B;;;;;;YA+D7B,MAAM;iBACD,MAAM;sBACD,MAAM,GAAG,IAAI;cACrB,MAAM;oBACA,MAAM,GAAG,IAAI;0BACP,MAAM,GAAG,IAAI;0BACb,MAAM,GAAG,IAAI;yBACd,MAAM,GAAG,IAAI;wBACd,MAAM;wBACN,MAAM;yBACL,MAAM;kBACb,OAAO;gBACT,UAAU,GAAG,OAAO,GAAG,OAAO,GAAG,SAAS;;GAkSpD,CAAC;AAGL,eAAO,MAAM,kCAAkC;;;;0CAEzB,OAAO;;;;;;;;;;;;;;;;;;;;;;GAkDzB,CAAC;AAKL,eAAO,MAAM,qBAAqB;;;;;;YAoBI,MAAM;;;GAIxC,CAAC;AAGL,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;;;;;;GAWnC,CAAC;AASL,eAAO,MAAM,8BAA8B;;;;8CAEjB,OAAO;;;;GAU7B,CAAC;AASL,eAAO,MAAM,mBAAmB;;;;;;;;0BAgBuB,MAAM;0BAAoB,MAAM;yBAAmB,MAAM;;;GA8C5G,CAAC;AAGL,eAAO,MAAM,kBAAkB;;;;;;GAU3B,CAAC;
|
|
1
|
+
{"version":3,"file":"create-order.functions.d.ts","sourceRoot":"","sources":["../../src/lib/create-order.functions.ts"],"names":[],"mappings":"AAcA,eAAO,MAAM,2BAA2B;;;;;;GA+CpC,CAAC;AAIL,eAAO,MAAM,2BAA2B;;;;0CAElB,OAAO;;;;GAoDzB,CAAC;AAWL,eAAO,MAAM,0BAA0B;;;;;;YA+D7B,MAAM;iBACD,MAAM;sBACD,MAAM,GAAG,IAAI;cACrB,MAAM;oBACA,MAAM,GAAG,IAAI;0BACP,MAAM,GAAG,IAAI;0BACb,MAAM,GAAG,IAAI;yBACd,MAAM,GAAG,IAAI;wBACd,MAAM;wBACN,MAAM;yBACL,MAAM;kBACb,OAAO;gBACT,UAAU,GAAG,OAAO,GAAG,OAAO,GAAG,SAAS;;GAkSpD,CAAC;AAGL,eAAO,MAAM,kCAAkC;;;;0CAEzB,OAAO;;;;;;;;;;;;;;;;;;;;;;GAkDzB,CAAC;AAKL,eAAO,MAAM,qBAAqB;;;;;;YAoBI,MAAM;;;GAIxC,CAAC;AAGL,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;;;;;;GAWnC,CAAC;AASL,eAAO,MAAM,8BAA8B;;;;8CAEjB,OAAO;;;;GAU7B,CAAC;AASL,eAAO,MAAM,mBAAmB;;;;;;;;0BAgBuB,MAAM;0BAAoB,MAAM;yBAAmB,MAAM;;;GA8C5G,CAAC;AAGL,eAAO,MAAM,kBAAkB;;;;;;GAU3B,CAAC;AA8EL,eAAO,MAAM,iBAAiB;;;;8CAEJ,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAmQY,MAAM;;GAE/C,CAAC;AAKL,eAAO,MAAM,gBAAgB;;;;8CAEH,OAAO;;;;;;;GAY7B,CAAC;AAQL,eAAO,MAAM,gBAAgB;;;;8CAEH,OAAO;;;;;;GAoG7B,CAAC;AAEL;;;GAGG;AACH,eAAO,MAAM,qBAAqB;;;;8CAER,OAAO;;;;GAyB7B,CAAC;AAgDL,eAAO,MAAM,oBAAoB;;;;8CAEP,OAAO;;;aA2JG,MAAM;iBACQ,MAAM,GAAG,IAAI;kBACX,MAAM;;YAEnB,MAAM,GAAG,IAAI;;;;YAmB7B,MAAM;mBACS,MAAM,GAAG,IAAI;qBACT,MAAM;;cAErB,MAAM,GAAG,IAAI;;;;;;;GASpC,CAAC;AAIL,eAAO,MAAM,gBAAgB;;;;8CAEH,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;GAgR7B,CAAC;AAKL,eAAO,MAAM,kBAAkB;;;;8CAEL,OAAO;;;;;;;;WAUM,MAAM;YAAU,MAAM,GAAG,IAAI;WAahE,CAAC;AAOL,eAAO,MAAM,2BAA2B;;;;8CAEd,OAAO;;;;gBAIgC,MAAM,EAAE;GAoCrE,CAAC"}
|
|
@@ -672,7 +672,14 @@ function snapshotForLine(l) {
|
|
|
672
672
|
packing_source: snap.packing_source,
|
|
673
673
|
};
|
|
674
674
|
}
|
|
675
|
+
function friendlyCreateError(msg) {
|
|
676
|
+
if (/De bestelling is niet aangemaakt/.test(msg))
|
|
677
|
+
return msg;
|
|
678
|
+
return `De bestelling is niet aangemaakt (${msg}). Er is niets bewaard; probeer het opnieuw.`;
|
|
679
|
+
}
|
|
675
680
|
const CreateManualOrderInput = z.object({
|
|
681
|
+
// Kenmerk per formulier: opnieuw versturen geeft dezelfde bestelling terug.
|
|
682
|
+
idempotencyKey: z.string().min(8).max(100),
|
|
676
683
|
customerId: z.string().uuid(),
|
|
677
684
|
customerName: z.string().min(1).max(255),
|
|
678
685
|
deliveryLocationId: z.string().uuid(),
|
|
@@ -872,7 +879,7 @@ export const createManualOrder = createServerFn({ method: "POST" })
|
|
|
872
879
|
}
|
|
873
880
|
}
|
|
874
881
|
const total = data.lines.reduce((s, l) => s + (Number(l.unit_price ?? 0) * Number(l.quantity)), 0);
|
|
875
|
-
const
|
|
882
|
+
const orderPayload = {
|
|
876
883
|
customer_name: data.customerName,
|
|
877
884
|
customer_id: data.customerId,
|
|
878
885
|
order_date: new Date().toISOString().slice(0, 10),
|
|
@@ -895,9 +902,7 @@ export const createManualOrder = createServerFn({ method: "POST" })
|
|
|
895
902
|
is_reservation: !!data.isReservation,
|
|
896
903
|
load_carrier_type: loadCarrierType,
|
|
897
904
|
},
|
|
898
|
-
}
|
|
899
|
-
if (orderErr)
|
|
900
|
-
throw new Error(orderErr.message);
|
|
905
|
+
};
|
|
901
906
|
const items = data.lines.map((l) => {
|
|
902
907
|
const isGroup = groupById.has(l.product_id);
|
|
903
908
|
const groupRow = isGroup ? groupById.get(l.product_id) : null;
|
|
@@ -906,23 +911,33 @@ export const createManualOrder = createServerFn({ method: "POST" })
|
|
|
906
911
|
? (/^\s*\[Groep\]/i.test(l.product_name) ? l.product_name : `[Groep] ${groupName}`)
|
|
907
912
|
: l.product_name;
|
|
908
913
|
return {
|
|
909
|
-
order_id: order.id,
|
|
910
914
|
// Groepen krijgen product_id = null; expand-group-order-items
|
|
911
915
|
// resolvt hen op naam ("[Groep] <naam>").
|
|
912
916
|
product_id: isGroup ? null : l.product_id,
|
|
913
917
|
product_name: productNameForStorage(displayName),
|
|
914
918
|
quantity: Math.max(1, Math.round(l.quantity)),
|
|
915
919
|
unit: l.unit ?? "stuks",
|
|
916
|
-
// Gekozen belading vastleggen op de regel zelf
|
|
917
|
-
// de handmatige keuze gebruikt i.p.v. de standaard van het product.
|
|
920
|
+
// Gekozen belading vastleggen op de regel zelf (snapshot).
|
|
918
921
|
...snapshotForLine(l),
|
|
919
|
-
unit_price: l.unit_price ??
|
|
922
|
+
unit_price: l.unit_price ?? null,
|
|
920
923
|
needs_sticker: l.needs_sticker === true,
|
|
921
924
|
};
|
|
922
925
|
});
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
+
// Kop en alle regels in één databasetransactie; idempotent op het
|
|
927
|
+
// formulierkenmerk. Mislukt één regel, dan wordt niets bewaard.
|
|
928
|
+
const { data: rpcRes, error: rpcErr } = await supabaseAdmin.rpc("verkoop_insert_manual_order", {
|
|
929
|
+
p_order: orderPayload,
|
|
930
|
+
p_items: items,
|
|
931
|
+
p_idempotency_key: data.idempotencyKey,
|
|
932
|
+
});
|
|
933
|
+
if (rpcErr)
|
|
934
|
+
throw new Error(friendlyCreateError(rpcErr.message));
|
|
935
|
+
if (!rpcRes?.ok)
|
|
936
|
+
throw new Error(rpcRes?.reason ?? "De bestelling is niet aangemaakt. Er is niets bewaard.");
|
|
937
|
+
const order = { id: rpcRes.order_id, order_number: rpcRes.order_number };
|
|
938
|
+
if (rpcRes.already_existed) {
|
|
939
|
+
return { ok: true, orderId: order.id, alreadyExisted: true };
|
|
940
|
+
}
|
|
926
941
|
// Karindeling wordt door de Logistiek Engine gedaan (eigen minuut-cron);
|
|
927
942
|
// deze module stoot dat niet zelf meer aan.
|
|
928
943
|
// Logistics Engine informeren (schaduwmodus): Engine plant de keten.
|
|
@@ -1621,7 +1636,20 @@ export const listCustomerStickerProducts = createServerFn({ method: "POST" })
|
|
|
1621
1636
|
.select("id, trade_item_key")
|
|
1622
1637
|
.in("id", data.productIds);
|
|
1623
1638
|
const productKeyRows = (prods ?? []).map((p) => ({ id: p.id, tradeItemKey: p.trade_item_key ?? null }));
|
|
1624
|
-
|
|
1639
|
+
// Productgroep: sticker volgt het hoofdproduct van de groep (head_product_id), op id.
|
|
1640
|
+
const { data: groups } = await sb
|
|
1641
|
+
.from("product_groups")
|
|
1642
|
+
.select("id, head_product_id")
|
|
1643
|
+
.in("id", data.productIds);
|
|
1644
|
+
const { groupStickerRows } = await import("./customer-stickers.js");
|
|
1645
|
+
const groupRows = groupStickerRows((groups ?? []));
|
|
1646
|
+
if (groupRows.length) {
|
|
1647
|
+
const { data: heads } = await sb.from("products").select("id, trade_item_key").in("id", groupRows.map((g) => g.headId));
|
|
1648
|
+
const headKey = new Map((heads ?? []).map((h) => [h.id, (h.trade_item_key ?? null)]));
|
|
1649
|
+
for (const g of groupRows)
|
|
1650
|
+
productKeyRows.push({ id: g.groupId, tradeItemKey: null, headId: g.headId, headKey: headKey.get(g.headId) ?? null });
|
|
1651
|
+
}
|
|
1652
|
+
const keys = Array.from(new Set(productKeyRows.flatMap((p) => [p.id, p.tradeItemKey, p.headId, p.headKey].filter(Boolean))));
|
|
1625
1653
|
if (keys.length === 0)
|
|
1626
1654
|
return { productIds: [] };
|
|
1627
1655
|
const { data: rows, error } = await sb
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Draaien met: bun src/lib/customer-stickers.check.ts
|
|
2
|
-
import { stickerCustomerKeys, stickerProductIds } from "./customer-stickers.js";
|
|
2
|
+
import { groupStickerRows, stickerCustomerKeys, stickerProductIds } from "./customer-stickers.js";
|
|
3
3
|
let failed = 0;
|
|
4
4
|
const eq = (name, a, b) => {
|
|
5
5
|
const ok = JSON.stringify(a) === JSON.stringify(b);
|
|
@@ -12,6 +12,9 @@ eq("klantsleutels zonder codes", stickerCustomerKeys({ id: "c1", twinfield_code:
|
|
|
12
12
|
eq("product met vaste sticker op id staat aan", stickerProductIds([{ id: "p1", tradeItemKey: null }, { id: "p2", tradeItemKey: null }], [{ trade_item_key: "p1" }]), ["p1"]);
|
|
13
13
|
eq("product met vaste sticker op artikelsleutel staat aan", stickerProductIds([{ id: "p1", tradeItemKey: "t1" }], [{ trade_item_key: "t1" }]), ["p1"]);
|
|
14
14
|
eq("geen vaste sticker: uit", stickerProductIds([{ id: "p1", tradeItemKey: "t1" }], []), []);
|
|
15
|
+
eq("productgroep: vaste sticker op hoofdproduct zet groepregel aan", stickerProductIds([{ id: "g1", tradeItemKey: null, headId: "h1", headKey: null }], [{ trade_item_key: "h1" }]), ["g1"]);
|
|
16
|
+
eq("productgroep zonder sticker op hoofdproduct: uit", stickerProductIds([{ id: "g1", tradeItemKey: null, headId: "h1", headKey: null }], [{ trade_item_key: "h2" }]), []);
|
|
17
|
+
eq("groep zonder hoofdproduct telt niet mee", groupStickerRows([{ id: "g1", head_product_id: null }, { id: "g2", head_product_id: "h2" }]), [{ groupId: "g2", headId: "h2" }]);
|
|
15
18
|
if (failed) {
|
|
16
19
|
console.error(`${failed} controle(s) mislukt`);
|
|
17
20
|
process.exit(1);
|
|
@@ -8,7 +8,17 @@ export declare function stickerCustomerKeys(c: {
|
|
|
8
8
|
export declare function stickerProductIds(products: {
|
|
9
9
|
id: string;
|
|
10
10
|
tradeItemKey: string | null;
|
|
11
|
+
headId?: string | null;
|
|
12
|
+
headKey?: string | null;
|
|
11
13
|
}[], rows: {
|
|
12
14
|
trade_item_key: string | null;
|
|
13
15
|
}[]): string[];
|
|
16
|
+
/** Groepen met een hoofdproduct: de vaste sticker van het hoofdproduct geldt voor de groepregel. */
|
|
17
|
+
export declare function groupStickerRows(groups: {
|
|
18
|
+
id: string;
|
|
19
|
+
head_product_id: string | null;
|
|
20
|
+
}[]): {
|
|
21
|
+
groupId: string;
|
|
22
|
+
headId: string;
|
|
23
|
+
}[];
|
|
14
24
|
//# sourceMappingURL=customer-stickers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customer-stickers.d.ts","sourceRoot":"","sources":["../../src/lib/customer-stickers.ts"],"names":[],"mappings":"AAIA,2EAA2E;AAC3E,wBAAgB,mBAAmB,CAAC,CAAC,EAAE;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,wBAAwB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1C,GAAG,MAAM,EAAE,CAOX;AAED,sFAAsF;AACtF,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,EAAE,
|
|
1
|
+
{"version":3,"file":"customer-stickers.d.ts","sourceRoot":"","sources":["../../src/lib/customer-stickers.ts"],"names":[],"mappings":"AAIA,2EAA2E;AAC3E,wBAAgB,mBAAmB,CAAC,CAAC,EAAE;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,wBAAwB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1C,GAAG,MAAM,EAAE,CAOX;AAED,sFAAsF;AACtF,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,EAAE,EACxG,IAAI,EAAE;IAAE,cAAc,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,EAAE,GACxC,MAAM,EAAE,CAIV;AAED,oGAAoG;AACpG,wBAAgB,gBAAgB,CAAC,MAAM,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,eAAe,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,EAAE,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,EAAE,CAEhI"}
|
|
@@ -15,5 +15,10 @@ export function stickerCustomerKeys(c) {
|
|
|
15
15
|
/** Product-id's waarvoor een vaste klantsticker bestaat (op id of artikelsleutel). */
|
|
16
16
|
export function stickerProductIds(products, rows) {
|
|
17
17
|
const have = new Set(rows.map((r) => String(r.trade_item_key ?? "")).filter(Boolean));
|
|
18
|
-
|
|
18
|
+
const hit = (k) => !!k && have.has(k);
|
|
19
|
+
return products.filter((p) => hit(p.id) || hit(p.tradeItemKey) || hit(p.headId) || hit(p.headKey)).map((p) => p.id);
|
|
20
|
+
}
|
|
21
|
+
/** Groepen met een hoofdproduct: de vaste sticker van het hoofdproduct geldt voor de groepregel. */
|
|
22
|
+
export function groupStickerRows(groups) {
|
|
23
|
+
return groups.filter((g) => !!g.head_product_id).map((g) => ({ groupId: g.id, headId: g.head_product_id }));
|
|
19
24
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const MODULE_VERSION = "1.0.
|
|
1
|
+
export declare const MODULE_VERSION = "1.0.110";
|
|
2
2
|
//# sourceMappingURL=module-version.d.ts.map
|
package/package.json
CHANGED
package/schema/verkoop.sql
CHANGED
|
@@ -2009,3 +2009,158 @@ END IF; EXCEPTION WHEN undefined_function OR undefined_table OR undefined_column
|
|
|
2009
2009
|
REVOKE ALL ON FUNCTION verkoop_create_order(text,text,uuid,date,uuid,uuid,jsonb,text,text,boolean,text,boolean,text) FROM PUBLIC, anon;
|
|
2010
2010
|
GRANT EXECUTE ON FUNCTION verkoop_create_order(text,text,uuid,date,uuid,uuid,jsonb,text,text,boolean,text,boolean,text) TO authenticated;
|
|
2011
2011
|
GRANT EXECUTE ON FUNCTION verkoop_create_order(text,text,uuid,date,uuid,uuid,jsonb,text,text,boolean,text,boolean,text) TO service_role;
|
|
2012
|
+
|
|
2013
|
+
-- 1.0.108: eenmalige verpakkingscorrectie Floriday-orderregels (lijst alleen lezen + correctie op opgegeven orders)
|
|
2014
|
+
CREATE OR REPLACE FUNCTION public.verkoop_packing_drift_report()
|
|
2015
|
+
RETURNS TABLE(order_id uuid, order_number text, order_status text, order_item_id uuid, sales_order_id text, afgesloten boolean, vastgezet boolean, cache_match text, cur_plants_per_crate integer, cur_crates_per_layer integer, cur_layers_per_cart integer, cur_vbn_package_code text, cur_load_carrier_type text, cur_packing_source text, fd_plants_per_crate integer, fd_crates_per_layer integer, fd_layers_per_cart integer, fd_vbn_package_code text, fd_load_carrier_type text)
|
|
2016
|
+
LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO 'public'
|
|
2017
|
+
AS $function$
|
|
2018
|
+
BEGIN
|
|
2019
|
+
IF auth.uid() IS NOT NULL AND NOT (public.has_role(auth.uid(),'admin') OR public.has_role(auth.uid(),'superadmin')) THEN
|
|
2020
|
+
RAISE EXCEPTION 'Alleen beheerders mogen deze lijst opvragen';
|
|
2021
|
+
END IF;
|
|
2022
|
+
RETURN QUERY
|
|
2023
|
+
WITH m AS (
|
|
2024
|
+
SELECT oi.id, oi.order_id, oi.source_line_key, oi.plants_per_crate, oi.crates_per_layer, oi.layers_per_cart,
|
|
2025
|
+
oi.vbn_package_code, oi.load_carrier_type, oi.packing_source, oi.packing_locked_at,
|
|
2026
|
+
o.order_number::text AS onum, o.status::text AS ostatus,
|
|
2027
|
+
(SELECT count(*) FROM floriday_salesorders_cache c WHERE c.floriday_id = oi.source_line_key AND coalesce(c.is_deleted,false)=false) AS n,
|
|
2028
|
+
(SELECT c.data->'packingConfiguration' FROM floriday_salesorders_cache c WHERE c.floriday_id = oi.source_line_key AND coalesce(c.is_deleted,false)=false LIMIT 1) AS pc
|
|
2029
|
+
FROM order_items oi JOIN orders o ON o.id = oi.order_id
|
|
2030
|
+
WHERE oi.source_line_key IS NOT NULL AND oi.quarantined_at IS NULL AND o.deleted_at IS NULL
|
|
2031
|
+
), f AS (
|
|
2032
|
+
SELECT m.*,
|
|
2033
|
+
nullif((pc->>'piecesPerPackage')::numeric,0)::int AS f1,
|
|
2034
|
+
nullif((pc->>'packagesPerLayer')::numeric,0)::int AS f2,
|
|
2035
|
+
nullif((pc->>'layersPerLoadCarrier')::numeric,0)::int AS f3,
|
|
2036
|
+
nullif(pc#>>'{package,vbnPackageCode}','') AS f4,
|
|
2037
|
+
nullif(pc->>'loadCarrier','') AS f5
|
|
2038
|
+
FROM m
|
|
2039
|
+
)
|
|
2040
|
+
SELECT f.order_id, f.onum, f.ostatus, f.id, f.source_line_key,
|
|
2041
|
+
lower(coalesce(f.ostatus,'')) ~ '(verzonden|afgerond|geannuleerd|geleverd|cancel|shipped|delivered|vervallen|afgewezen|gereed voor facturatie)',
|
|
2042
|
+
f.packing_locked_at IS NOT NULL,
|
|
2043
|
+
CASE WHEN f.n = 1 AND f.pc IS NOT NULL THEN 'ok' WHEN f.n = 0 THEN 'geen Floriday-gegevens' WHEN f.n > 1 THEN 'meerdere Floriday-rijen' ELSE 'geen verpakking in Floriday' END,
|
|
2044
|
+
f.plants_per_crate, f.crates_per_layer, f.layers_per_cart, f.vbn_package_code, f.load_carrier_type, f.packing_source,
|
|
2045
|
+
f.f1, f.f2, f.f3, f.f4, f.f5
|
|
2046
|
+
FROM f
|
|
2047
|
+
WHERE f.n = 1 AND f.pc IS NOT NULL AND (
|
|
2048
|
+
f.plants_per_crate IS DISTINCT FROM f.f1 OR f.crates_per_layer IS DISTINCT FROM f.f2 OR f.layers_per_cart IS DISTINCT FROM f.f3)
|
|
2049
|
+
ORDER BY f.onum, f.id;
|
|
2050
|
+
END $function$;
|
|
2051
|
+
|
|
2052
|
+
CREATE OR REPLACE FUNCTION public.verkoop_packing_drift_apply(p_order_ids uuid[])
|
|
2053
|
+
RETURNS TABLE(order_id uuid, order_number text, lines_updated integer, replan_event text)
|
|
2054
|
+
LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public'
|
|
2055
|
+
AS $function$
|
|
2056
|
+
DECLARE r record; v_n int; v_ev jsonb; v_at text := to_char(now() AT TIME ZONE 'UTC','YYYYMMDDHH24MISS');
|
|
2057
|
+
BEGIN
|
|
2058
|
+
IF auth.uid() IS NOT NULL AND NOT (public.has_role(auth.uid(),'admin') OR public.has_role(auth.uid(),'superadmin')) THEN
|
|
2059
|
+
RAISE EXCEPTION 'Alleen beheerders mogen deze correctie uitvoeren';
|
|
2060
|
+
END IF;
|
|
2061
|
+
IF p_order_ids IS NULL OR cardinality(p_order_ids) = 0 THEN RAISE EXCEPTION 'Geen orders opgegeven'; END IF;
|
|
2062
|
+
FOR r IN SELECT d.order_id, min(d.order_number) AS onum FROM public.verkoop_packing_drift_report() d
|
|
2063
|
+
WHERE d.order_id = ANY(p_order_ids) AND NOT d.afgesloten AND NOT d.vastgezet GROUP BY d.order_id LOOP
|
|
2064
|
+
UPDATE order_items oi SET plants_per_crate = d.fd_plants_per_crate, crates_per_layer = d.fd_crates_per_layer,
|
|
2065
|
+
layers_per_cart = d.fd_layers_per_cart, vbn_package_code = d.fd_vbn_package_code,
|
|
2066
|
+
load_carrier_type = d.fd_load_carrier_type, packing_source = 'floriday_order'
|
|
2067
|
+
FROM public.verkoop_packing_drift_report() d
|
|
2068
|
+
WHERE d.order_item_id = oi.id AND d.order_id = r.order_id AND NOT d.afgesloten AND NOT d.vastgezet AND oi.packing_locked_at IS NULL;
|
|
2069
|
+
GET DIAGNOSTICS v_n = ROW_COUNT;
|
|
2070
|
+
v_ev := to_jsonb(public.logistics_emit_event('verkoop','order.changed', r.order_id::text,
|
|
2071
|
+
jsonb_build_object('orderId', r.order_id, 'reason', 'Verpakking hersteld uit Floriday'),
|
|
2072
|
+
NULL, false, 'verpakking-hersteld:' || r.order_id || ':' || v_at, NULL));
|
|
2073
|
+
order_id := r.order_id; order_number := r.onum; lines_updated := v_n; replan_event := v_ev #>> '{}';
|
|
2074
|
+
RETURN NEXT;
|
|
2075
|
+
END LOOP;
|
|
2076
|
+
END $function$;
|
|
2077
|
+
|
|
2078
|
+
REVOKE EXECUTE ON FUNCTION public.verkoop_packing_drift_report() FROM PUBLIC, anon;
|
|
2079
|
+
REVOKE EXECUTE ON FUNCTION public.verkoop_packing_drift_apply(uuid[]) FROM PUBLIC, anon;
|
|
2080
|
+
GRANT EXECUTE ON FUNCTION public.verkoop_packing_drift_report() TO authenticated, service_role;
|
|
2081
|
+
GRANT EXECUTE ON FUNCTION public.verkoop_packing_drift_apply(uuid[]) TO authenticated, service_role;
|
|
2082
|
+
|
|
2083
|
+
-- 1.0.110: handmatige bestelling atomair (kop + regels in één transactie), idempotent op formulierkenmerk
|
|
2084
|
+
DO $t$ BEGIN
|
|
2085
|
+
CREATE UNIQUE INDEX IF NOT EXISTS orders_manual_idempotency_uniq ON public.orders ((custom_fields->>'idempotency_key')) WHERE ((custom_fields->>'idempotency_key') IS NOT NULL);
|
|
2086
|
+
EXCEPTION WHEN undefined_table OR undefined_column THEN RAISE NOTICE 'verkoop-schema: index overgeslagen (%)', SQLERRM; END $t$;
|
|
2087
|
+
CREATE OR REPLACE FUNCTION public.verkoop_insert_manual_order(p_order jsonb, p_items jsonb, p_idempotency_key text)
|
|
2088
|
+
RETURNS jsonb
|
|
2089
|
+
LANGUAGE plpgsql
|
|
2090
|
+
SECURITY DEFINER
|
|
2091
|
+
SET search_path TO 'public'
|
|
2092
|
+
AS $function$
|
|
2093
|
+
DECLARE
|
|
2094
|
+
v_uid uuid := auth.uid();
|
|
2095
|
+
v_existing record;
|
|
2096
|
+
v_order_id uuid;
|
|
2097
|
+
v_order_number text;
|
|
2098
|
+
v_item jsonb;
|
|
2099
|
+
v_idx int := 0;
|
|
2100
|
+
v_cf jsonb;
|
|
2101
|
+
BEGIN
|
|
2102
|
+
IF v_uid IS NOT NULL AND NOT (public.has_role(v_uid,'admin') OR public.has_role(v_uid,'sales')
|
|
2103
|
+
OR public.has_role(v_uid,'manager') OR public.has_role(v_uid,'superadmin')) THEN
|
|
2104
|
+
RETURN jsonb_build_object('ok', false, 'reason', 'Je hebt geen rechten om bestellingen aan te maken.');
|
|
2105
|
+
END IF;
|
|
2106
|
+
IF p_idempotency_key IS NULL OR btrim(p_idempotency_key) = '' THEN
|
|
2107
|
+
RETURN jsonb_build_object('ok', false, 'reason', 'De bestelling is niet aangemaakt: het formulier mist een kenmerk. Ververs de pagina en probeer opnieuw.');
|
|
2108
|
+
END IF;
|
|
2109
|
+
IF p_items IS NULL OR jsonb_typeof(p_items) <> 'array' OR jsonb_array_length(p_items) = 0 THEN
|
|
2110
|
+
RETURN jsonb_build_object('ok', false, 'reason', 'De bestelling is niet aangemaakt: voeg minimaal één regel toe.');
|
|
2111
|
+
END IF;
|
|
2112
|
+
|
|
2113
|
+
SELECT id, order_number INTO v_existing FROM public.orders
|
|
2114
|
+
WHERE custom_fields->>'idempotency_key' = p_idempotency_key LIMIT 1;
|
|
2115
|
+
IF FOUND THEN
|
|
2116
|
+
RETURN jsonb_build_object('ok', true, 'order_id', v_existing.id, 'order_number', v_existing.order_number, 'already_existed', true);
|
|
2117
|
+
END IF;
|
|
2118
|
+
|
|
2119
|
+
v_cf := COALESCE(p_order->'custom_fields', '{}'::jsonb) || jsonb_build_object('idempotency_key', p_idempotency_key);
|
|
2120
|
+
|
|
2121
|
+
INSERT INTO public.orders (customer_name, customer_id, order_date, delivery_date, is_reservation, status, total, notes, custom_fields)
|
|
2122
|
+
VALUES (
|
|
2123
|
+
p_order->>'customer_name',
|
|
2124
|
+
NULLIF(p_order->>'customer_id','')::uuid,
|
|
2125
|
+
COALESCE(NULLIF(p_order->>'order_date','')::date, current_date),
|
|
2126
|
+
NULLIF(p_order->>'delivery_date','')::date,
|
|
2127
|
+
COALESCE((p_order->>'is_reservation')::boolean, false),
|
|
2128
|
+
p_order->>'status',
|
|
2129
|
+
p_order->>'total',
|
|
2130
|
+
NULLIF(p_order->>'notes',''),
|
|
2131
|
+
v_cf)
|
|
2132
|
+
RETURNING id, order_number INTO v_order_id, v_order_number;
|
|
2133
|
+
|
|
2134
|
+
FOR v_item IN SELECT * FROM jsonb_array_elements(p_items) LOOP
|
|
2135
|
+
v_idx := v_idx + 1;
|
|
2136
|
+
BEGIN
|
|
2137
|
+
INSERT INTO public.order_items (order_id, product_id, product_name, quantity, unit, unit_price, needs_sticker,
|
|
2138
|
+
plants_per_crate, crates_per_layer, layers_per_cart, quantity_crates, vbn_package_code, load_carrier_type, packing_source)
|
|
2139
|
+
VALUES (
|
|
2140
|
+
v_order_id,
|
|
2141
|
+
NULLIF(v_item->>'product_id','')::uuid,
|
|
2142
|
+
v_item->>'product_name',
|
|
2143
|
+
(v_item->>'quantity')::numeric,
|
|
2144
|
+
COALESCE(NULLIF(v_item->>'unit',''), 'stuks'),
|
|
2145
|
+
NULLIF(v_item->>'unit_price','')::numeric,
|
|
2146
|
+
COALESCE((v_item->>'needs_sticker')::boolean, false),
|
|
2147
|
+
NULLIF(v_item->>'plants_per_crate','')::numeric,
|
|
2148
|
+
NULLIF(v_item->>'crates_per_layer','')::numeric,
|
|
2149
|
+
NULLIF(v_item->>'layers_per_cart','')::numeric,
|
|
2150
|
+
NULLIF(v_item->>'quantity_crates','')::numeric,
|
|
2151
|
+
NULLIF(v_item->>'vbn_package_code',''),
|
|
2152
|
+
NULLIF(v_item->>'load_carrier_type',''),
|
|
2153
|
+
NULLIF(v_item->>'packing_source',''));
|
|
2154
|
+
EXCEPTION WHEN others THEN
|
|
2155
|
+
-- Fout doorgeven: de hele transactie (kop en eerdere regels) wordt teruggedraaid.
|
|
2156
|
+
RAISE EXCEPTION 'De bestelling is niet aangemaakt: regel % kon niet worden opgeslagen (%). Er is niets bewaard.', v_idx, SQLERRM
|
|
2157
|
+
USING ERRCODE = 'P0001';
|
|
2158
|
+
END;
|
|
2159
|
+
END LOOP;
|
|
2160
|
+
|
|
2161
|
+
RETURN jsonb_build_object('ok', true, 'order_id', v_order_id, 'order_number', v_order_number, 'already_existed', false);
|
|
2162
|
+
END;
|
|
2163
|
+
$function$;
|
|
2164
|
+
;
|
|
2165
|
+
REVOKE ALL ON FUNCTION public.verkoop_insert_manual_order(jsonb, jsonb, text) FROM PUBLIC, anon, authenticated;
|
|
2166
|
+
GRANT EXECUTE ON FUNCTION public.verkoop_insert_manual_order(jsonb, jsonb, text) TO service_role;
|