@flowselections/mailbox-orders 1.0.26 → 1.0.27
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/CartAssignmentWizard.d.ts +6 -0
- package/dist-lib/components/CartAssignmentWizard.d.ts.map +1 -0
- package/dist-lib/components/CartAssignmentWizard.js +199 -0
- package/dist-lib/components/MailboxInboxPage.d.ts +2 -0
- package/dist-lib/components/MailboxInboxPage.d.ts.map +1 -0
- package/dist-lib/components/MailboxInboxPage.js +120 -0
- package/dist-lib/components/MailboxProcessedPage.js +1 -1
- package/dist-lib/components/MailboxProposalsPage.js +5 -5
- package/dist-lib/components/settings/ImapAccountsCard.d.ts +2 -0
- package/dist-lib/components/settings/ImapAccountsCard.d.ts.map +1 -0
- package/dist-lib/components/settings/ImapAccountsCard.js +136 -0
- package/dist-lib/components/settings/ImapProfilesCard.d.ts +2 -0
- package/dist-lib/components/settings/ImapProfilesCard.d.ts.map +1 -0
- package/dist-lib/components/settings/ImapProfilesCard.js +101 -0
- package/dist-lib/components/settings/MailboxAiPromptCard.js +2 -2
- package/dist-lib/components/settings/MailboxOrderTemplateCard.js +1 -1
- package/dist-lib/components/settings/MailboxSettingsCard.d.ts +2 -0
- package/dist-lib/components/settings/MailboxSettingsCard.d.ts.map +1 -0
- package/dist-lib/components/settings/MailboxSettingsCard.js +85 -0
- package/dist-lib/integrations/supabase/client.server.js +1 -1
- package/dist-lib/integrations/supabase/types.d.ts +2746 -7
- package/dist-lib/integrations/supabase/types.d.ts.map +1 -1
- package/dist-lib/integrations/supabase/types.js +1 -0
- package/dist-lib/lib/ai-config.server.d.ts +1 -1
- package/dist-lib/lib/imap.functions.d.ts +32852 -0
- package/dist-lib/lib/imap.functions.d.ts.map +1 -0
- package/dist-lib/lib/imap.functions.js +235 -0
- package/dist-lib/lib/mailbox-ai-settings.functions.d.ts +2 -2
- package/dist-lib/lib/mailbox-ai-settings.functions.js +1 -1
- package/dist-lib/lib/mailbox-ai.server.d.ts +1 -1
- package/dist-lib/lib/mailbox-auto.server.d.ts +9 -0
- package/dist-lib/lib/mailbox-auto.server.d.ts.map +1 -0
- package/dist-lib/lib/mailbox-auto.server.js +198 -0
- package/dist-lib/lib/mailbox-ingest.server.d.ts +1 -1
- package/dist-lib/lib/mailbox-ingest.server.js +1 -1
- package/dist-lib/lib/mailbox-template.functions.d.ts +6 -6
- package/dist-lib/lib/mailbox-template.functions.js +1 -1
- package/dist-lib/lib/mailbox.functions.d.ts +25 -24
- package/dist-lib/lib/mailbox.functions.d.ts.map +1 -1
- package/dist-lib/lib/mailbox.functions.js +22 -22
- package/dist-lib/server-routes.d.ts +9 -0
- package/dist-lib/server-routes.d.ts.map +1 -0
- package/dist-lib/server-routes.js +34 -0
- package/package.json +38 -6
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// Server functions voor centraal IMAP-beheer (accounts + profielen).
|
|
2
|
+
// Admins beheren accounts & profielen; modules pollen via profile_key.
|
|
3
|
+
import { createServerFn } from "@tanstack/react-start";
|
|
4
|
+
import { requireSupabaseAuth } from "../integrations/supabase/auth-middleware";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
async function assertAdmin(supabase, userId) {
|
|
7
|
+
const { data } = await supabase.rpc("has_role", { _user_id: userId, _role: "admin" });
|
|
8
|
+
if (!data)
|
|
9
|
+
throw new Error("Alleen admins mogen IMAP-instellingen wijzigen");
|
|
10
|
+
}
|
|
11
|
+
// ─── Accounts ────────────────────────────────────────────────────────────────
|
|
12
|
+
export const listImapAccounts = createServerFn({ method: "GET" })
|
|
13
|
+
.middleware([requireSupabaseAuth])
|
|
14
|
+
.handler(async ({ context }) => {
|
|
15
|
+
const { data, error } = await context.supabase
|
|
16
|
+
.from("imap_accounts")
|
|
17
|
+
.select("id, name, email, host, port, username, use_tls, password_secret_name, is_active, last_tested_at, last_test_ok, last_test_error, created_at, updated_at")
|
|
18
|
+
.order("name");
|
|
19
|
+
if (error)
|
|
20
|
+
throw new Error(error.message);
|
|
21
|
+
return { items: Array.isArray(data) ? data : [] };
|
|
22
|
+
});
|
|
23
|
+
const AccountInput = z.object({
|
|
24
|
+
id: z.string().uuid().optional(),
|
|
25
|
+
name: z.string().min(1).max(255),
|
|
26
|
+
email: z.string().email().max(255).nullable().optional(),
|
|
27
|
+
host: z.string().min(1).max(255),
|
|
28
|
+
port: z.number().int().min(1).max(65535),
|
|
29
|
+
username: z.string().min(1).max(255),
|
|
30
|
+
use_tls: z.boolean(),
|
|
31
|
+
password: z.string().max(1024).optional(), // leeg = bestaand wachtwoord behouden
|
|
32
|
+
password_secret_name: z.string().min(1).max(255).regex(/^[A-Za-z_][A-Za-z0-9_]*$/).nullable().optional(),
|
|
33
|
+
is_active: z.boolean().optional(),
|
|
34
|
+
});
|
|
35
|
+
export const upsertImapAccount = createServerFn({ method: "POST" })
|
|
36
|
+
.middleware([requireSupabaseAuth])
|
|
37
|
+
.inputValidator((input) => AccountInput.parse(input))
|
|
38
|
+
.handler(async ({ data, context }) => {
|
|
39
|
+
await assertAdmin(context.supabase, context.userId);
|
|
40
|
+
const { supabaseAdmin } = await import("../integrations/supabase/client.server");
|
|
41
|
+
const payload = {
|
|
42
|
+
name: data.name,
|
|
43
|
+
email: data.email ?? null,
|
|
44
|
+
host: data.host,
|
|
45
|
+
port: data.port,
|
|
46
|
+
username: data.username,
|
|
47
|
+
use_tls: data.use_tls,
|
|
48
|
+
password_secret_name: data.password_secret_name ?? null,
|
|
49
|
+
is_active: data.is_active ?? true,
|
|
50
|
+
};
|
|
51
|
+
if (typeof data.password === "string" && data.password.length > 0) {
|
|
52
|
+
payload.password = data.password;
|
|
53
|
+
}
|
|
54
|
+
if (data.id) {
|
|
55
|
+
const { error } = await supabaseAdmin.from("imap_accounts").update(payload).eq("id", data.id);
|
|
56
|
+
if (error)
|
|
57
|
+
throw new Error(error.message);
|
|
58
|
+
return { ok: true, id: data.id };
|
|
59
|
+
}
|
|
60
|
+
const { data: row, error } = await supabaseAdmin.from("imap_accounts").insert(payload).select("id").single();
|
|
61
|
+
if (error)
|
|
62
|
+
throw new Error(error.message);
|
|
63
|
+
return { ok: true, id: row.id };
|
|
64
|
+
});
|
|
65
|
+
// Markeer 1 account als de actieve voor het mailbox_orders profiel
|
|
66
|
+
export const activateImapAccount = createServerFn({ method: "POST" })
|
|
67
|
+
.middleware([requireSupabaseAuth])
|
|
68
|
+
.inputValidator((input) => z.object({ account_id: z.string().uuid() }).parse(input))
|
|
69
|
+
.handler(async ({ data, context }) => {
|
|
70
|
+
await assertAdmin(context.supabase, context.userId);
|
|
71
|
+
const { supabaseAdmin } = await import("../integrations/supabase/client.server");
|
|
72
|
+
// Zorg dat het standaardprofiel bestaat
|
|
73
|
+
const { data: prof } = await supabaseAdmin
|
|
74
|
+
.from("imap_profiles")
|
|
75
|
+
.upsert({ profile_key: "mailbox_orders", name: "Mailbox Orders", folder: "INBOX", polling_enabled: true, account_id: data.account_id }, { onConflict: "profile_key" })
|
|
76
|
+
.select("id")
|
|
77
|
+
.single();
|
|
78
|
+
// Update voor zekerheid (upsert zou ook account_id moeten zetten, maar PostgREST upsert kan default-merge gedrag hebben)
|
|
79
|
+
if (prof?.id) {
|
|
80
|
+
await supabaseAdmin.from("imap_profiles").update({ account_id: data.account_id, polling_enabled: true }).eq("id", prof.id);
|
|
81
|
+
}
|
|
82
|
+
return { ok: true };
|
|
83
|
+
});
|
|
84
|
+
export const deleteImapAccount = createServerFn({ method: "POST" })
|
|
85
|
+
.middleware([requireSupabaseAuth])
|
|
86
|
+
.inputValidator((input) => z.object({ id: z.string().uuid() }).parse(input))
|
|
87
|
+
.handler(async ({ data, context }) => {
|
|
88
|
+
await assertAdmin(context.supabase, context.userId);
|
|
89
|
+
const { supabaseAdmin } = await import("../integrations/supabase/client.server");
|
|
90
|
+
const { error } = await supabaseAdmin.from("imap_accounts").delete().eq("id", data.id);
|
|
91
|
+
if (error)
|
|
92
|
+
throw new Error(error.message);
|
|
93
|
+
return { ok: true };
|
|
94
|
+
});
|
|
95
|
+
export const testImapAccount = createServerFn({ method: "POST" })
|
|
96
|
+
.middleware([requireSupabaseAuth])
|
|
97
|
+
.inputValidator((input) => z.object({
|
|
98
|
+
id: z.string().uuid().optional(),
|
|
99
|
+
host: z.string().max(255).optional(),
|
|
100
|
+
port: z.number().int().min(1).max(65535).optional(),
|
|
101
|
+
username: z.string().max(255).optional(),
|
|
102
|
+
use_tls: z.boolean().optional(),
|
|
103
|
+
password: z.string().max(1024).optional(),
|
|
104
|
+
password_secret_name: z.string().max(255).optional(),
|
|
105
|
+
}).parse(input ?? {}))
|
|
106
|
+
.handler(async ({ data, context }) => {
|
|
107
|
+
await assertAdmin(context.supabase, context.userId);
|
|
108
|
+
const body = { action: "test" };
|
|
109
|
+
if (data.id)
|
|
110
|
+
body.account_id = data.id;
|
|
111
|
+
else {
|
|
112
|
+
body.host = data.host;
|
|
113
|
+
body.port = data.port;
|
|
114
|
+
body.username = data.username;
|
|
115
|
+
body.use_tls = data.use_tls;
|
|
116
|
+
body.password = data.password;
|
|
117
|
+
body.password_secret_name = data.password_secret_name;
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
const { data: res, error } = await context.supabase.functions.invoke("mailbox-imap", { body });
|
|
121
|
+
if (error)
|
|
122
|
+
return { ok: false, error: error.message };
|
|
123
|
+
return res;
|
|
124
|
+
}
|
|
125
|
+
catch (e) {
|
|
126
|
+
return { ok: false, error: e?.message ?? "Onbekende fout" };
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
// ─── Profielen ───────────────────────────────────────────────────────────────
|
|
130
|
+
export const listImapProfiles = createServerFn({ method: "GET" })
|
|
131
|
+
.middleware([requireSupabaseAuth])
|
|
132
|
+
.handler(async ({ context }) => {
|
|
133
|
+
const { data, error } = await context.supabase
|
|
134
|
+
.from("imap_profiles")
|
|
135
|
+
.select("id, profile_key, name, account_id, folder, polling_enabled, last_polled_at, last_uid_seen, last_error, created_at, updated_at, imap_accounts(id, name, email, host)")
|
|
136
|
+
.order("name");
|
|
137
|
+
if (error)
|
|
138
|
+
throw new Error(error.message);
|
|
139
|
+
return { items: Array.isArray(data) ? data : [] };
|
|
140
|
+
});
|
|
141
|
+
const ProfileInput = z.object({
|
|
142
|
+
id: z.string().uuid().optional(),
|
|
143
|
+
profile_key: z.string().min(1).max(64).regex(/^[a-z0-9_]+$/),
|
|
144
|
+
name: z.string().min(1).max(255),
|
|
145
|
+
account_id: z.string().uuid().nullable(),
|
|
146
|
+
folder: z.string().min(1).max(255),
|
|
147
|
+
polling_enabled: z.boolean(),
|
|
148
|
+
});
|
|
149
|
+
export const upsertImapProfile = createServerFn({ method: "POST" })
|
|
150
|
+
.middleware([requireSupabaseAuth])
|
|
151
|
+
.inputValidator((input) => ProfileInput.parse(input))
|
|
152
|
+
.handler(async ({ data, context }) => {
|
|
153
|
+
await assertAdmin(context.supabase, context.userId);
|
|
154
|
+
const { supabaseAdmin } = await import("../integrations/supabase/client.server");
|
|
155
|
+
const payload = {
|
|
156
|
+
profile_key: data.profile_key,
|
|
157
|
+
name: data.name,
|
|
158
|
+
account_id: data.account_id,
|
|
159
|
+
folder: data.folder,
|
|
160
|
+
polling_enabled: data.polling_enabled,
|
|
161
|
+
};
|
|
162
|
+
if (data.id) {
|
|
163
|
+
const { error } = await supabaseAdmin.from("imap_profiles").update(payload).eq("id", data.id);
|
|
164
|
+
if (error)
|
|
165
|
+
throw new Error(error.message);
|
|
166
|
+
return { ok: true, id: data.id };
|
|
167
|
+
}
|
|
168
|
+
const { data: row, error } = await supabaseAdmin
|
|
169
|
+
.from("imap_profiles")
|
|
170
|
+
.upsert(payload, { onConflict: "profile_key" })
|
|
171
|
+
.select("id").single();
|
|
172
|
+
if (error)
|
|
173
|
+
throw new Error(error.message);
|
|
174
|
+
return { ok: true, id: row.id };
|
|
175
|
+
});
|
|
176
|
+
export const deleteImapProfile = createServerFn({ method: "POST" })
|
|
177
|
+
.middleware([requireSupabaseAuth])
|
|
178
|
+
.inputValidator((input) => z.object({ id: z.string().uuid() }).parse(input))
|
|
179
|
+
.handler(async ({ data, context }) => {
|
|
180
|
+
await assertAdmin(context.supabase, context.userId);
|
|
181
|
+
const { supabaseAdmin } = await import("../integrations/supabase/client.server");
|
|
182
|
+
const { error } = await supabaseAdmin.from("imap_profiles").delete().eq("id", data.id);
|
|
183
|
+
if (error)
|
|
184
|
+
throw new Error(error.message);
|
|
185
|
+
return { ok: true };
|
|
186
|
+
});
|
|
187
|
+
export const setProfileAccount = createServerFn({ method: "POST" })
|
|
188
|
+
.middleware([requireSupabaseAuth])
|
|
189
|
+
.inputValidator((input) => z.object({ profile_id: z.string().uuid(), account_id: z.string().uuid().nullable() }).parse(input))
|
|
190
|
+
.handler(async ({ data, context }) => {
|
|
191
|
+
await assertAdmin(context.supabase, context.userId);
|
|
192
|
+
const { supabaseAdmin } = await import("../integrations/supabase/client.server");
|
|
193
|
+
const { error } = await supabaseAdmin.from("imap_profiles").update({ account_id: data.account_id }).eq("id", data.profile_id);
|
|
194
|
+
if (error)
|
|
195
|
+
throw new Error(error.message);
|
|
196
|
+
return { ok: true };
|
|
197
|
+
});
|
|
198
|
+
export const pollImapProfile = createServerFn({ method: "POST" })
|
|
199
|
+
.middleware([requireSupabaseAuth])
|
|
200
|
+
.inputValidator((input) => z.object({ profile_id: z.string().uuid() }).parse(input))
|
|
201
|
+
.handler(async ({ data, context }) => {
|
|
202
|
+
try {
|
|
203
|
+
const { data: res, error } = await context.supabase.functions.invoke("mailbox-imap", {
|
|
204
|
+
body: { action: "poll", profile_id: data.profile_id },
|
|
205
|
+
});
|
|
206
|
+
if (error)
|
|
207
|
+
return { ok: false, error: error.message, inserted: 0 };
|
|
208
|
+
const r = res;
|
|
209
|
+
// Auto-verwerk binnenkomende mails (alleen mailbox_orders profiel heeft AI-flow)
|
|
210
|
+
if (r.ok && (r.inserted ?? 0) > 0) {
|
|
211
|
+
const { autoProcessNewMessagesInternal } = await import("./mailbox-auto.server");
|
|
212
|
+
await autoProcessNewMessagesInternal();
|
|
213
|
+
}
|
|
214
|
+
return r;
|
|
215
|
+
}
|
|
216
|
+
catch (e) {
|
|
217
|
+
return { ok: false, error: e?.message ?? "Onbekende fout", inserted: 0 };
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
export const listImapSyncLog = createServerFn({ method: "GET" })
|
|
221
|
+
.middleware([requireSupabaseAuth])
|
|
222
|
+
.inputValidator((input) => z.object({ profile_id: z.string().uuid().optional() }).parse(input ?? {}))
|
|
223
|
+
.handler(async ({ data, context }) => {
|
|
224
|
+
let q = context.supabase
|
|
225
|
+
.from("imap_sync_log")
|
|
226
|
+
.select("id, profile_id, account_id, started_at, finished_at, inserted, ok, error")
|
|
227
|
+
.order("started_at", { ascending: false })
|
|
228
|
+
.limit(50);
|
|
229
|
+
if (data.profile_id)
|
|
230
|
+
q = q.eq("profile_id", data.profile_id);
|
|
231
|
+
const { data: rows, error } = await q;
|
|
232
|
+
if (error)
|
|
233
|
+
throw new Error(error.message);
|
|
234
|
+
return { items: Array.isArray(rows) ? rows : [] };
|
|
235
|
+
});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export declare const getMailboxAiSettings: import("@tanstack/start-client-core").OptionalFetcher<readonly [import("@tanstack/start-client-core").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
|
|
2
|
-
supabase: import("../integrations/supabase/auth-middleware
|
|
2
|
+
supabase: import("../integrations/supabase/auth-middleware").AuthedSupabaseClient;
|
|
3
3
|
userId: string;
|
|
4
4
|
claims: import("@supabase/auth-js").User;
|
|
5
5
|
}, undefined, undefined, undefined>], undefined, Promise<{
|
|
@@ -10,7 +10,7 @@ export declare const getMailboxAiSettings: import("@tanstack/start-client-core")
|
|
|
10
10
|
default_prompt: string;
|
|
11
11
|
}>>;
|
|
12
12
|
export declare const saveMailboxAiSettings: import("@tanstack/start-client-core").OptionalFetcher<readonly [import("@tanstack/start-client-core").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
|
|
13
|
-
supabase: import("../integrations/supabase/auth-middleware
|
|
13
|
+
supabase: import("../integrations/supabase/auth-middleware").AuthedSupabaseClient;
|
|
14
14
|
userId: string;
|
|
15
15
|
claims: import("@supabase/auth-js").User;
|
|
16
16
|
}, undefined, undefined, undefined>], (input: unknown) => {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Beheer van de centrale systeemprompt en verplichte velden voor de mailbox-AI.
|
|
2
2
|
import { createServerFn } from "@tanstack/react-start";
|
|
3
|
-
import { requireSupabaseAuth } from "../integrations/supabase/auth-middleware
|
|
3
|
+
import { requireSupabaseAuth } from "../integrations/supabase/auth-middleware";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { DEFAULT_MAILBOX_SYSTEM_PROMPT, DEFAULT_REQUIRED_FIELDS } from "./mailbox-ai-prompt";
|
|
6
6
|
export const getMailboxAiSettings = createServerFn({ method: "GET" })
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
2
|
-
import type { Database } from "../integrations/supabase/types
|
|
2
|
+
import type { Database } from "../integrations/supabase/types";
|
|
3
3
|
import { DEFAULT_MAILBOX_SYSTEM_PROMPT } from "./mailbox-ai-prompt";
|
|
4
4
|
export { DEFAULT_MAILBOX_SYSTEM_PROMPT };
|
|
5
5
|
type AdminClient = SupabaseClient<Database>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mailbox-auto.server.d.ts","sourceRoot":"","sources":["../../src/lib/mailbox-auto.server.ts"],"names":[],"mappings":"AAIA,UAAU,aAAa;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB;AA0LD,wBAAsB,8BAA8B,IAAI,OAAO,CAAC,aAAa,CAAC,CA2C7E"}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
async function parseOneMessage(messageId) {
|
|
2
|
+
const { supabaseAdmin } = await import("../integrations/supabase/client.server");
|
|
3
|
+
const { data: msg, error: msgErr } = await supabaseAdmin
|
|
4
|
+
.from("mailbox_messages").select("*").eq("id", messageId).single();
|
|
5
|
+
if (msgErr || !msg)
|
|
6
|
+
return { ok: false, error: "Bericht niet gevonden" };
|
|
7
|
+
await supabaseAdmin.from("mailbox_messages")
|
|
8
|
+
.update({ status: "parsing", error_message: null }).eq("id", msg.id);
|
|
9
|
+
try {
|
|
10
|
+
const { data: fields } = await supabaseAdmin
|
|
11
|
+
.from("mailbox_order_template_fields")
|
|
12
|
+
.select("*")
|
|
13
|
+
.order("sort_order", { ascending: true });
|
|
14
|
+
const templateFields = (fields ?? []).filter((f) => f.ai_enabled);
|
|
15
|
+
const [{ data: products }, { data: customers }, { data: suppliers }] = await Promise.all([
|
|
16
|
+
supabaseAdmin.from("products").select("id, product, product_type").order("product").range(0, 1999),
|
|
17
|
+
supabaseAdmin.from("customers").select("id, company_name, email").eq("is_active", true).order("company_name").range(0, 4999),
|
|
18
|
+
supabaseAdmin.from("suppliers").select("id, name").order("name").range(0, 999),
|
|
19
|
+
]);
|
|
20
|
+
const catalog = (products ?? []).map((p) => ({ id: p.id, name: p.product }));
|
|
21
|
+
const plantTypeSet = new Set();
|
|
22
|
+
(products ?? []).forEach((p) => { if (p.product_type)
|
|
23
|
+
plantTypeSet.add(p.product_type); });
|
|
24
|
+
const plantTypes = Array.from(plantTypeSet).sort().map((v) => ({ id: v, name: v }));
|
|
25
|
+
const spec = templateFields.map((f) => {
|
|
26
|
+
let allowed;
|
|
27
|
+
if (f.source === "database") {
|
|
28
|
+
switch (f.field_type) {
|
|
29
|
+
case "customer":
|
|
30
|
+
allowed = (customers ?? []).map((c) => ({ id: c.id, name: c.company_name }));
|
|
31
|
+
break;
|
|
32
|
+
case "product":
|
|
33
|
+
allowed = catalog;
|
|
34
|
+
break;
|
|
35
|
+
case "plant_type":
|
|
36
|
+
allowed = plantTypes;
|
|
37
|
+
break;
|
|
38
|
+
case "supplier":
|
|
39
|
+
allowed = (suppliers ?? []).map((s) => ({ id: s.id, name: s.name }));
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
key: f.key,
|
|
45
|
+
label: f.label,
|
|
46
|
+
field_type: f.field_type,
|
|
47
|
+
ai_hint: f.ai_hint,
|
|
48
|
+
allowed,
|
|
49
|
+
};
|
|
50
|
+
});
|
|
51
|
+
const { parseOrderEmail } = await import("./mailbox-ai.server");
|
|
52
|
+
const parsed = await parseOrderEmail(msg.body_text ?? msg.body_html ?? "", msg.subject ?? "", spec, catalog);
|
|
53
|
+
const customerId = parsed.fields["customer"]?.value;
|
|
54
|
+
const deliveryDate = parsed.fields["delivery_date"]?.value;
|
|
55
|
+
const notesValue = parsed.fields["notes"]?.value;
|
|
56
|
+
const matchedCustomerId = typeof customerId === "string" && customerId.length === 36 ? customerId : null;
|
|
57
|
+
let finalCustomerId = matchedCustomerId;
|
|
58
|
+
if (!finalCustomerId && msg.from_email) {
|
|
59
|
+
const { data: customer } = await supabaseAdmin
|
|
60
|
+
.from("customers").select("id").eq("email", msg.from_email).maybeSingle();
|
|
61
|
+
finalCustomerId = customer?.id ?? null;
|
|
62
|
+
}
|
|
63
|
+
const { data: proposal, error: propErr } = await supabaseAdmin
|
|
64
|
+
.from("mailbox_order_proposals").insert({
|
|
65
|
+
message_id: msg.id,
|
|
66
|
+
matched_customer_id: finalCustomerId,
|
|
67
|
+
confidence: parsed.overall_confidence,
|
|
68
|
+
delivery_date: typeof deliveryDate === "string" ? deliveryDate : null,
|
|
69
|
+
notes: typeof notesValue === "string" ? notesValue : null,
|
|
70
|
+
parsed_payload: parsed,
|
|
71
|
+
status: "pending",
|
|
72
|
+
}).select("id").single();
|
|
73
|
+
if (propErr)
|
|
74
|
+
throw new Error(propErr.message);
|
|
75
|
+
const fieldRows = Object.entries(parsed.fields).map(([key, v]) => ({
|
|
76
|
+
proposal_id: proposal.id,
|
|
77
|
+
field_key: key,
|
|
78
|
+
value: v.value === undefined ? null : v.value,
|
|
79
|
+
ai_confidence: v.confidence,
|
|
80
|
+
ai_filled: v.value !== null && v.value !== undefined,
|
|
81
|
+
needs_review: v.needs_review,
|
|
82
|
+
}));
|
|
83
|
+
if (fieldRows.length > 0) {
|
|
84
|
+
await supabaseAdmin.from("mailbox_proposal_field_values").insert(fieldRows);
|
|
85
|
+
}
|
|
86
|
+
if (parsed.lines.length > 0) {
|
|
87
|
+
const linesToInsert = parsed.lines.map((l, idx) => ({
|
|
88
|
+
proposal_id: proposal.id,
|
|
89
|
+
product_id: l.product_id,
|
|
90
|
+
raw_product_text: l.raw_product_text,
|
|
91
|
+
quantity: l.quantity,
|
|
92
|
+
unit: l.unit,
|
|
93
|
+
match_confidence: l.match_confidence,
|
|
94
|
+
sort_order: idx,
|
|
95
|
+
}));
|
|
96
|
+
await supabaseAdmin.from("mailbox_proposal_lines").insert(linesToInsert);
|
|
97
|
+
}
|
|
98
|
+
await supabaseAdmin.from("mailbox_messages")
|
|
99
|
+
.update({ status: "parsed" }).eq("id", msg.id);
|
|
100
|
+
return {
|
|
101
|
+
ok: true,
|
|
102
|
+
proposalId: proposal.id,
|
|
103
|
+
parsed,
|
|
104
|
+
customerId: finalCustomerId,
|
|
105
|
+
deliveryDate: typeof deliveryDate === "string" ? deliveryDate : null,
|
|
106
|
+
notes: typeof notesValue === "string" ? notesValue : null,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
catch (e) {
|
|
110
|
+
await supabaseAdmin.from("mailbox_messages")
|
|
111
|
+
.update({ status: "failed", error_message: e?.message ?? "Parsefout" }).eq("id", msg.id);
|
|
112
|
+
return { ok: false, error: e?.message ?? "Parsefout" };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async function autoApproveProposal(args) {
|
|
116
|
+
const { supabaseAdmin } = await import("../integrations/supabase/client.server");
|
|
117
|
+
const customFields = {};
|
|
118
|
+
for (const [k, v] of Object.entries(args.parsed.fields)) {
|
|
119
|
+
customFields[k] = v.value ?? null;
|
|
120
|
+
}
|
|
121
|
+
const orderNumber = `MB-${Date.now()}`;
|
|
122
|
+
const { data: order, error: orderErr } = await supabaseAdmin
|
|
123
|
+
.from("orders").insert({
|
|
124
|
+
order_number: orderNumber,
|
|
125
|
+
customer_name: args.customerName,
|
|
126
|
+
customer_id: args.customerId,
|
|
127
|
+
order_date: new Date().toISOString().slice(0, 10),
|
|
128
|
+
delivery_date: args.deliveryDate,
|
|
129
|
+
status: "nieuw",
|
|
130
|
+
total: "0",
|
|
131
|
+
notes: args.notes,
|
|
132
|
+
custom_fields: { ...customFields, source: "mailbox", auto_created: true },
|
|
133
|
+
}).select("id").single();
|
|
134
|
+
if (orderErr || !order)
|
|
135
|
+
return false;
|
|
136
|
+
const items = args.parsed.lines.map((l) => ({
|
|
137
|
+
order_id: order.id,
|
|
138
|
+
product_id: l.product_id,
|
|
139
|
+
product_name: l.raw_product_text || "Onbekend product",
|
|
140
|
+
quantity: Math.max(1, Math.round(l.quantity ?? 1)),
|
|
141
|
+
unit: l.unit ?? "stuks",
|
|
142
|
+
}));
|
|
143
|
+
if (items.length > 0) {
|
|
144
|
+
const { error: itemsErr } = await supabaseAdmin.from("order_items").insert(items);
|
|
145
|
+
if (itemsErr)
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
await supabaseAdmin.from("mailbox_order_proposals").update({
|
|
149
|
+
status: "approved",
|
|
150
|
+
reviewed_at: new Date().toISOString(),
|
|
151
|
+
created_order_id: order.id,
|
|
152
|
+
}).eq("id", args.proposalId);
|
|
153
|
+
await supabaseAdmin.from("mailbox_messages")
|
|
154
|
+
.update({ status: "converted" }).eq("id", args.messageId);
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
export async function autoProcessNewMessagesInternal() {
|
|
158
|
+
const { supabaseAdmin } = await import("../integrations/supabase/client.server");
|
|
159
|
+
const { data: newMsgs } = await supabaseAdmin
|
|
160
|
+
.from("mailbox_messages")
|
|
161
|
+
.select("id")
|
|
162
|
+
.eq("status", "new")
|
|
163
|
+
.order("received_at", { ascending: true })
|
|
164
|
+
.limit(20);
|
|
165
|
+
const result = { processed: 0, approved: 0, pending: 0, failed: 0 };
|
|
166
|
+
for (const m of newMsgs ?? []) {
|
|
167
|
+
result.processed++;
|
|
168
|
+
const r = await parseOneMessage(m.id);
|
|
169
|
+
if (!r.ok || !r.proposalId || !r.parsed) {
|
|
170
|
+
result.failed++;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const hasCustomer = !!r.customerId;
|
|
174
|
+
const hasDelivery = !!r.deliveryDate;
|
|
175
|
+
const hasLines = r.parsed.lines.length > 0;
|
|
176
|
+
if (!hasCustomer || !hasDelivery || !hasLines) {
|
|
177
|
+
result.pending++;
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
// Haal klantnaam op
|
|
181
|
+
const { data: cust } = await supabaseAdmin
|
|
182
|
+
.from("customers").select("company_name").eq("id", r.customerId).maybeSingle();
|
|
183
|
+
const ok = await autoApproveProposal({
|
|
184
|
+
proposalId: r.proposalId,
|
|
185
|
+
messageId: m.id,
|
|
186
|
+
customerId: r.customerId,
|
|
187
|
+
customerName: cust?.company_name ?? "Onbekende klant",
|
|
188
|
+
deliveryDate: r.deliveryDate,
|
|
189
|
+
notes: r.notes ?? null,
|
|
190
|
+
parsed: r.parsed,
|
|
191
|
+
});
|
|
192
|
+
if (ok)
|
|
193
|
+
result.approved++;
|
|
194
|
+
else
|
|
195
|
+
result.pending++;
|
|
196
|
+
}
|
|
197
|
+
return result;
|
|
198
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
2
|
-
import type { Database } from "../integrations/supabase/types
|
|
2
|
+
import type { Database } from "../integrations/supabase/types";
|
|
3
3
|
type AdminClient = SupabaseClient<Database>;
|
|
4
4
|
/** Centrale AI-instellingen van deze module (aanpasbaar via Instellingen). */
|
|
5
5
|
export declare function loadMailboxAiSettings(admin: AdminClient): Promise<{
|
|
@@ -799,7 +799,7 @@ async function ingestSingleEvent(admin, connectionId, ev) {
|
|
|
799
799
|
}
|
|
800
800
|
// De volledige pipeline. Alle triggers roepen dit aan.
|
|
801
801
|
export async function runIngest(trigger) {
|
|
802
|
-
const { supabaseAdmin } = await import("../integrations/supabase/client.server
|
|
802
|
+
const { supabaseAdmin } = await import("../integrations/supabase/client.server");
|
|
803
803
|
// 1. Actieve orders/receive connectie ophalen (service_role → geen bearer nodig).
|
|
804
804
|
const { data: active, error: activeErr } = await supabaseAdmin.rpc("email_auth_for_purpose", {
|
|
805
805
|
_purpose: "orders",
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export declare const listTemplateFields: import("@tanstack/start-client-core").OptionalFetcher<readonly [import("@tanstack/start-client-core").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
|
|
2
|
-
supabase: import("../integrations/supabase/auth-middleware
|
|
2
|
+
supabase: import("../integrations/supabase/auth-middleware").AuthedSupabaseClient;
|
|
3
3
|
userId: string;
|
|
4
4
|
claims: import("@supabase/auth-js").User;
|
|
5
5
|
}, undefined, undefined, undefined>], undefined, Promise<{
|
|
@@ -22,7 +22,7 @@ export declare const listTemplateFields: import("@tanstack/start-client-core").O
|
|
|
22
22
|
}[];
|
|
23
23
|
}>>;
|
|
24
24
|
export declare const upsertTemplateField: import("@tanstack/start-client-core").OptionalFetcher<readonly [import("@tanstack/start-client-core").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
|
|
25
|
-
supabase: import("../integrations/supabase/auth-middleware
|
|
25
|
+
supabase: import("../integrations/supabase/auth-middleware").AuthedSupabaseClient;
|
|
26
26
|
userId: string;
|
|
27
27
|
claims: import("@supabase/auth-js").User;
|
|
28
28
|
}, undefined, undefined, undefined>], (input: unknown) => {
|
|
@@ -47,7 +47,7 @@ export declare const upsertTemplateField: import("@tanstack/start-client-core").
|
|
|
47
47
|
id: string;
|
|
48
48
|
}>>;
|
|
49
49
|
export declare const deleteTemplateField: import("@tanstack/start-client-core").OptionalFetcher<readonly [import("@tanstack/start-client-core").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
|
|
50
|
-
supabase: import("../integrations/supabase/auth-middleware
|
|
50
|
+
supabase: import("../integrations/supabase/auth-middleware").AuthedSupabaseClient;
|
|
51
51
|
userId: string;
|
|
52
52
|
claims: import("@supabase/auth-js").User;
|
|
53
53
|
}, undefined, undefined, undefined>], (input: unknown) => {
|
|
@@ -56,7 +56,7 @@ export declare const deleteTemplateField: import("@tanstack/start-client-core").
|
|
|
56
56
|
ok: true;
|
|
57
57
|
}>>;
|
|
58
58
|
export declare const reorderTemplateFields: import("@tanstack/start-client-core").OptionalFetcher<readonly [import("@tanstack/start-client-core").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
|
|
59
|
-
supabase: import("../integrations/supabase/auth-middleware
|
|
59
|
+
supabase: import("../integrations/supabase/auth-middleware").AuthedSupabaseClient;
|
|
60
60
|
userId: string;
|
|
61
61
|
claims: import("@supabase/auth-js").User;
|
|
62
62
|
}, undefined, undefined, undefined>], (input: unknown) => {
|
|
@@ -65,7 +65,7 @@ export declare const reorderTemplateFields: import("@tanstack/start-client-core"
|
|
|
65
65
|
ok: true;
|
|
66
66
|
}>>;
|
|
67
67
|
export declare const listPlantTypesForPicker: import("@tanstack/start-client-core").OptionalFetcher<readonly [import("@tanstack/start-client-core").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
|
|
68
|
-
supabase: import("../integrations/supabase/auth-middleware
|
|
68
|
+
supabase: import("../integrations/supabase/auth-middleware").AuthedSupabaseClient;
|
|
69
69
|
userId: string;
|
|
70
70
|
claims: import("@supabase/auth-js").User;
|
|
71
71
|
}, undefined, undefined, undefined>], undefined, Promise<{
|
|
@@ -75,7 +75,7 @@ export declare const listPlantTypesForPicker: import("@tanstack/start-client-cor
|
|
|
75
75
|
}[];
|
|
76
76
|
}>>;
|
|
77
77
|
export declare const listSuppliersForPicker: import("@tanstack/start-client-core").OptionalFetcher<readonly [import("@tanstack/start-client-core").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
|
|
78
|
-
supabase: import("../integrations/supabase/auth-middleware
|
|
78
|
+
supabase: import("../integrations/supabase/auth-middleware").AuthedSupabaseClient;
|
|
79
79
|
userId: string;
|
|
80
80
|
claims: import("@supabase/auth-js").User;
|
|
81
81
|
}, undefined, undefined, undefined>], undefined, Promise<{
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// CRUD voor de configureerbare ordertemplate.
|
|
2
2
|
import { createServerFn } from "@tanstack/react-start";
|
|
3
|
-
import { requireSupabaseAuth } from "../integrations/supabase/auth-middleware
|
|
3
|
+
import { requireSupabaseAuth } from "../integrations/supabase/auth-middleware";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
const FieldType = z.enum([
|
|
6
6
|
"text", "number", "date", "select", "multiselect",
|