vantuz 3.4.2 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/.env.example +21 -0
  2. package/.openclaw/completions/openclaw.bash +227 -0
  3. package/.openclaw/completions/openclaw.fish +1552 -0
  4. package/.openclaw/completions/openclaw.ps1 +1966 -0
  5. package/.openclaw/completions/openclaw.zsh +3571 -0
  6. package/.openclaw/gateway.cmd +10 -0
  7. package/.openclaw/identity/device.json +7 -0
  8. package/.openclaw/openclaw.json +40 -0
  9. package/.windsurf/workflows/vantuz-dev.md +31 -0
  10. package/DOCS_TR.md +80 -0
  11. package/LICENSE +45 -45
  12. package/README.md +52 -21
  13. package/cli.js +685 -585
  14. package/config.js +733 -733
  15. package/core/agent-loop.js +190 -190
  16. package/core/ai-provider.js +298 -261
  17. package/core/automation.js +523 -523
  18. package/core/brand-analyst.js +101 -0
  19. package/core/channels.js +167 -167
  20. package/core/dashboard.js +230 -230
  21. package/core/database.js +135 -37
  22. package/core/eia-monitor.js +3 -1
  23. package/core/engine.js +648 -636
  24. package/core/gateway.js +447 -447
  25. package/core/learning.js +214 -214
  26. package/core/license.js +113 -0
  27. package/core/marketplace-adapter.js +168 -168
  28. package/core/memory.js +190 -190
  29. package/core/migrations/001-initial-schema.sql +1 -1
  30. package/core/queue.js +120 -120
  31. package/core/self-healer.js +314 -314
  32. package/core/unified-product.js +214 -214
  33. package/core/vision-service.js +113 -113
  34. package/index.js +217 -174
  35. package/modules/crm/sentiment-crm.js +231 -231
  36. package/modules/healer/listing-healer.js +201 -201
  37. package/modules/oracle/predictor.js +214 -214
  38. package/modules/researcher/agent.js +169 -169
  39. package/modules/team/agents/base.js +92 -92
  40. package/modules/team/agents/dev.js +33 -33
  41. package/modules/team/agents/josh.js +40 -40
  42. package/modules/team/agents/marketing.js +33 -33
  43. package/modules/team/agents/milo.js +36 -36
  44. package/modules/team/index.js +78 -78
  45. package/modules/team/shared-memory.js +87 -87
  46. package/modules/war-room/competitor-tracker.js +250 -250
  47. package/modules/war-room/pricing-engine.js +308 -308
  48. package/n11docs.md +1680 -0
  49. package/nodes/warehouse.js +238 -238
  50. package/onboard.js +1 -1
  51. package/openclawdocs.md +3 -0
  52. package/package.json +7 -5
  53. package/platforms/pttavm.js +14 -14
  54. package/plugins/vantuz/index.js +528 -528
  55. package/plugins/vantuz/memory/hippocampus.js +465 -465
  56. package/plugins/vantuz/package.json +20 -20
  57. package/plugins/vantuz/platforms/_template.js +118 -118
  58. package/plugins/vantuz/platforms/amazon.js +236 -236
  59. package/plugins/vantuz/platforms/ciceksepeti.js +166 -166
  60. package/plugins/vantuz/platforms/hepsiburada.js +180 -180
  61. package/plugins/vantuz/platforms/index.js +165 -165
  62. package/plugins/vantuz/platforms/n11.js +229 -229
  63. package/plugins/vantuz/platforms/pazarama.js +154 -154
  64. package/plugins/vantuz/platforms/pttavm.js +127 -127
  65. package/plugins/vantuz/platforms/trendyol.js +326 -326
  66. package/plugins/vantuz/services/alerts.js +253 -253
  67. package/plugins/vantuz/services/license.js +34 -34
  68. package/plugins/vantuz/services/scheduler.js +232 -232
  69. package/plugins/vantuz/tools/analytics.js +152 -152
  70. package/plugins/vantuz/tools/crossborder.js +187 -187
  71. package/plugins/vantuz/tools/nl-parser.js +211 -211
  72. package/plugins/vantuz/tools/product.js +110 -110
  73. package/plugins/vantuz/tools/quick-report.js +175 -175
  74. package/plugins/vantuz/tools/repricer.js +314 -314
  75. package/plugins/vantuz/tools/sentiment.js +115 -115
  76. package/plugins/vantuz/tools/vision.js +257 -257
  77. package/public.pem +9 -0
  78. package/server/app.js +260 -260
  79. package/server/public/index.html +514 -514
  80. package/start.bat +33 -33
  81. package/vantuz.sqlite +0 -0
  82. package/workspace/AGENTS.md +73 -0
  83. package/workspace/BRAND.md +29 -0
  84. package/workspace/SOUL.md +72 -0
  85. package/workspace/team/DECISIONS.md +3 -0
  86. package/workspace/team/GOALS.md +3 -0
  87. package/workspace/team/PROJECT_STATUS.md +3 -0
  88. package/workspace/team/agents/dev/SOUL.md +12 -0
  89. package/workspace/team/agents/josh/SOUL.md +12 -0
  90. package/workspace/team/agents/marketing/SOUL.md +12 -0
  91. package/workspace/team/agents/milo/SOUL.md +12 -0
  92. package/vantuz-3.3.4.tgz +0 -0
@@ -1,523 +1,523 @@
1
- // core/automation.js
2
- import fs from 'fs';
3
- import path from 'path';
4
- import os from 'os';
5
- import crypto from 'crypto';
6
- import { log, chat as aiChat } from './ai-provider.js';
7
- import { getScheduler } from './scheduler.js';
8
-
9
- const VANTUZ_HOME = path.join(os.homedir(), '.vantuz');
10
- const CONFIG_JSON = path.join(VANTUZ_HOME, 'config.json');
11
-
12
- const RISKY_KEYWORDS = [
13
- 'güncelle', 'update', 'yayınla', 'publish', 'yayından kaldır', 'unpublish',
14
- 'değiştir', 'change', 'sil', 'kaldır', 'delete', 'remove',
15
- 'fiyatı yap', 'stoğu yap'
16
- ];
17
-
18
- const APPROVE_KEYWORDS = ['onay', 'onayla', 'kabul', 'evet', 'tamam'];
19
- const REJECT_KEYWORDS = ['hayır', 'iptal', 'vazgeç', 'reddet'];
20
-
21
- function loadConfig() {
22
- try {
23
- if (fs.existsSync(CONFIG_JSON)) {
24
- return JSON.parse(fs.readFileSync(CONFIG_JSON, 'utf-8'));
25
- }
26
- } catch (e) {
27
- log('WARN', 'Config okunamadı', { error: e.message });
28
- }
29
- return {};
30
- }
31
-
32
- function saveConfig(config) {
33
- try {
34
- fs.writeFileSync(CONFIG_JSON, JSON.stringify(config, null, 2));
35
- return true;
36
- } catch (e) {
37
- log('WARN', 'Config yazılamadı', { error: e.message });
38
- return false;
39
- }
40
- }
41
-
42
- function normalizePhone(input) {
43
- if (!input) return '';
44
- const cleaned = String(input).replace(/[\s-]/g, '');
45
- return cleaned.startsWith('+') ? cleaned : `+${cleaned}`;
46
- }
47
-
48
- function messageHasAny(message, keywords) {
49
- const lower = message.toLowerCase();
50
- return keywords.some(k => lower.includes(k));
51
- }
52
-
53
- function normalizeTr(input) {
54
- return String(input || '')
55
- .toLowerCase()
56
- .replace(/[çÇ]/g, 'c')
57
- .replace(/[ğĞ]/g, 'g')
58
- .replace(/[ıİ]/g, 'i')
59
- .replace(/[öÖ]/g, 'o')
60
- .replace(/[şŞ]/g, 's')
61
- .replace(/[üÜ]/g, 'u');
62
- }
63
-
64
- function summarizeOrdersByStatus(orders = []) {
65
- if (!Array.isArray(orders) || orders.length === 0) return '';
66
- const counts = {};
67
- orders.forEach(o => {
68
- const s = (o.status || o.shipmentPackageStatus || o.orderStatus || 'UNKNOWN').toString();
69
- counts[s] = (counts[s] || 0) + 1;
70
- });
71
- return Object.entries(counts)
72
- .sort((a, b) => b[1] - a[1])
73
- .map(([s, n]) => `${s}:${n}`)
74
- .join(', ');
75
- }
76
-
77
- function isActiveStatus(status) {
78
- const s = String(status || '').toLowerCase();
79
- return s === 'created' || s === 'picking' || s === 'unpacked' || s === 'shipped';
80
- }
81
-
82
- function extractProductNames(order) {
83
- const lines = Array.isArray(order?.lines) ? order.lines : [];
84
- const names = lines
85
- .map(l => l?.productName || l?.name)
86
- .filter(Boolean);
87
- return names;
88
- }
89
-
90
- function getOrderTimestamp(order) {
91
- const candidates = [
92
- order?.lastModifiedDate,
93
- order?.agreedDeliveryDate,
94
- order?.createdDate,
95
- order?.orderDate
96
- ];
97
- for (const value of candidates) {
98
- if (!value) continue;
99
- const num = Number(value);
100
- if (Number.isFinite(num) && num > 0) return num;
101
- const parsed = Date.parse(value);
102
- if (!Number.isNaN(parsed)) return parsed;
103
- }
104
- return null;
105
- }
106
-
107
- function formatOrderLine(order) {
108
- const number = order.orderNumber || order.id || 'N/A';
109
- const name = order.customerName || order.customerfullName || order.customerFullName || 'Müşteri';
110
- const total = order.totalPrice ?? order.totalAmount ?? order.total ?? '?';
111
- const status = order.status || order.shipmentPackageStatus || order.orderStatus || 'UNKNOWN';
112
- return `#${number} - ${name} - ${total} TL - ${status}`;
113
- }
114
-
115
- function getTenantId(channel, from) {
116
- if (channel === 'whatsapp' && from) return normalizePhone(from);
117
- return 'default';
118
- }
119
-
120
- function ensureConfigShape(config) {
121
- if (!config.tenants) config.tenants = {};
122
- if (!config.automation) config.automation = {};
123
- if (!config.automation.approvals) config.automation.approvals = [];
124
- if (!config.automation.cronJobs) config.automation.cronJobs = [];
125
- return config;
126
- }
127
-
128
- function ensureTenantState(config, tenantId) {
129
- if (!config.tenants[tenantId]) {
130
- config.tenants[tenantId] = { riskAccepted: false };
131
- }
132
- if (!config.tenants[tenantId].session) {
133
- config.tenants[tenantId].session = {};
134
- }
135
- return config.tenants[tenantId];
136
- }
137
-
138
- function toSessionOrder(order) {
139
- return {
140
- orderNumber: order.orderNumber || order.id || 'N/A',
141
- status: order.status || order.shipmentPackageStatus || order.orderStatus || 'UNKNOWN',
142
- productNames: extractProductNames(order)
143
- };
144
- }
145
-
146
- function storeLastOrders(config, tenantId, orders) {
147
- const tenant = ensureTenantState(config, tenantId);
148
- const list = Array.isArray(orders) ? orders.map(toSessionOrder) : [];
149
- tenant.session.lastOrders = list.slice(0, 20);
150
- tenant.session.lastOrderAt = new Date().toISOString();
151
- saveConfig(config);
152
- }
153
-
154
- function newApproval(message, meta, kind = 'action') {
155
- return {
156
- id: crypto.randomUUID(),
157
- channel: meta.channel,
158
- from: meta.from || 'unknown',
159
- message,
160
- kind,
161
- createdAt: new Date().toISOString()
162
- };
163
- }
164
-
165
- function findPendingApproval(config, meta) {
166
- const approvals = config.automation?.approvals || [];
167
- const from = meta.from || 'unknown';
168
- return approvals.find(a => a.from === from && a.channel === meta.channel);
169
- }
170
-
171
- function removeApproval(config, approvalId) {
172
- config.automation.approvals = (config.automation.approvals || []).filter(a => a.id !== approvalId);
173
- }
174
-
175
- async function planWithAI(message, engine) {
176
- const systemPrompt = [
177
- 'Sen Vantuz otomasyon planlayıcısısın.',
178
- 'Kullanıcı mesajını tek bir otomasyon planına çevir ve sadece JSON döndür.',
179
- 'Şema:',
180
- '{ "intent": "report|analysis|change|schedule|other", "risk": "low|high", "schedule": "", "action": "" }',
181
- 'risk = SADECE veri değiştiren/silen işlemler (update/delete/create) varsa "high" olmalı. Listeleme/okuma işlemleri her zaman "low".',
182
- 'schedule = cron ifadesi (boş olabilir).',
183
- 'action = yapılacak işi kısa Türkçe özetle.'
184
- ].join('\n');
185
-
186
- const response = await aiChat(message, {
187
- aiProvider: engine.config.aiProvider || 'gemini',
188
- systemContext: systemPrompt
189
- }, engine.env);
190
-
191
- const jsonMatch = response.match(/\{[\s\S]*\}/);
192
- if (!jsonMatch) return null;
193
- try {
194
- return JSON.parse(jsonMatch[0]);
195
- } catch {
196
- return null;
197
- }
198
- }
199
-
200
- function fallbackPlan(message) {
201
- const risky = messageHasAny(message, RISKY_KEYWORDS);
202
- // Explicitly safe keywords check
203
- const safeKeywords = ['listele', 'göster', 'nedir', 'kaç', 'ne kadar', 'durum', 'rapor'];
204
- const safe = messageHasAny(message, safeKeywords);
205
-
206
- const schedule = message.includes('cron ') ? message.split('cron ')[1].trim() : '';
207
- return {
208
- intent: schedule ? 'schedule' : (risky ? 'change' : 'analysis'),
209
- risk: (risky && !safe) ? 'high' : 'low',
210
- schedule,
211
- action: message
212
- };
213
- }
214
-
215
- export class AutomationManager {
216
- constructor(engine) {
217
- this.engine = engine;
218
- this.scheduler = getScheduler();
219
- this.config = ensureConfigShape(loadConfig());
220
- }
221
-
222
- init() {
223
- this._restoreCronJobs();
224
- }
225
-
226
- _restoreCronJobs() {
227
- const jobs = this.config.automation?.cronJobs || [];
228
- for (const job of jobs) {
229
- this._scheduleJob(job, false);
230
- }
231
- }
232
-
233
- _scheduleJob(job, persist = true) {
234
- if (!job?.name || !job?.cron || !job?.message) return;
235
-
236
- this.scheduler.addJob(job.name, job.cron, async () => {
237
- log('INFO', `Cron job executing: ${job.name}`, { message: job.message });
238
- await this.engine.chat(job.message);
239
- }, true);
240
-
241
- if (persist) {
242
- const exists = this.config.automation.cronJobs.find(j => j.name === job.name);
243
- if (!exists) {
244
- this.config.automation.cronJobs.push(job);
245
- saveConfig(this.config);
246
- }
247
- }
248
- }
249
-
250
- _deleteJob(name) {
251
- this.scheduler.removeJob(name);
252
- this.config.automation.cronJobs = this.config.automation.cronJobs.filter(j => j.name !== name && j.name !== `auto-${name}`);
253
- saveConfig(this.config);
254
- return true;
255
- }
256
-
257
- _listJobs() {
258
- return this.config.automation.cronJobs || [];
259
- }
260
-
261
-
262
- async handleMessage(message, meta = { channel: 'local', from: 'local' }) {
263
- this.config = ensureConfigShape(loadConfig());
264
-
265
- const lower = String(message || '').toLowerCase();
266
- const normalized = normalizeTr(message);
267
- const hasOrderKeyword = lower.includes('sipari?') || normalized.includes('siparis');
268
- const asksApproved = lower.includes('onaylanan') || normalized.includes('onaylanan');
269
- const asksUnshipped = lower.includes('kargoya verilmemi?') || lower.includes('hen?z kargoya') || lower.includes('kargoya verilmedi') || normalized.includes('kargoya verilmemis');
270
- const asksPickingWhich = lower.includes('picking') || normalized.includes('picking');
271
- const asksOrderNames = lower.includes('sipari?lerin ad?') || normalized.includes('siparislerin adi') || lower.includes('?r?n ad?') || normalized.includes('urun adi') || lower.includes('?r?n?n ad?') || normalized.includes('urunun adi');
272
- const asksToday = lower.includes('bug?n') || normalized.includes('bugun');
273
- const asksLast24h = lower.includes('son 24') || normalized.includes('son 24');
274
- const asksYesterday = lower.includes('d?n') || normalized.includes('dun');
275
- const asksNeedShipment = lower.includes('kargoya ??kmas?') || lower.includes('kargoya cikmasi') || normalized.includes('kargoya cikmasi');
276
- const asksWhichProduct = lower.includes('hangi ?r?n') || normalized.includes('hangi urun');
277
-
278
- const tenantId = getTenantId(meta.channel, meta.from);
279
- ensureTenantState(this.config, tenantId);
280
-
281
- if (asksApproved) {
282
- const orders = await this.engine.getOrders({ size: 100, status: 'Picking' });
283
- storeLastOrders(this.config, tenantId, orders);
284
- return {
285
- handled: true,
286
- response: `?u an onaylanan (Picking) ${orders.length} sipari? var.`
287
- };
288
- }
289
-
290
- if (asksUnshipped) {
291
- const orders = await this.engine.getOrders({ size: 100, status: 'Created' });
292
- storeLastOrders(this.config, tenantId, orders);
293
- return {
294
- handled: true,
295
- response: `?u an kargoya verilmemi? (Created) ${orders.length} sipari? var.`
296
- };
297
- }
298
-
299
- if (asksPickingWhich) {
300
- const orders = await this.engine.getOrders({ size: 100, status: 'Picking' });
301
- if (!orders || orders.length === 0) {
302
- return { handled: true, response: 'Picking stat?s?nde sipari? yok.' };
303
- }
304
- storeLastOrders(this.config, tenantId, orders);
305
- const lines = orders.slice(0, 5).map(formatOrderLine).join('\n');
306
- return { handled: true, response: `Picking sipari?leri:\n${lines}` };
307
- }
308
-
309
- if (asksNeedShipment) {
310
- const orders = await this.engine.getOrders({ size: 100, status: 'Created' });
311
- if (!orders || orders.length === 0) {
312
- return { handled: true, response: 'Kargoya ??kmas? gereken (Created) sipari? yok.' };
313
- }
314
- storeLastOrders(this.config, tenantId, orders);
315
- const lines = orders.slice(0, 5).map(formatOrderLine).join('\n');
316
- return { handled: true, response: `Kargoya ??kmas? gereken sipari?ler:\n${lines}` };
317
- }
318
-
319
- if (asksWhichProduct) {
320
- const tenant = ensureTenantState(this.config, tenantId);
321
- const last = tenant.session?.lastOrders || [];
322
- if (last.length === 1 && last[0].productNames?.length) {
323
- return { handled: true, response: `?r?n: ${last[0].productNames.join(', ')}` };
324
- }
325
- if (last.length > 1) {
326
- const lines = last.slice(0, 5).map(o => `#${o.orderNumber} - ${o.productNames?.join(', ') || '?r?n ad? yok'}`).join('\n');
327
- return { handled: true, response: `Hangi sipari?i kastediyorsun?\n${lines}` };
328
- }
329
- return { handled: true, response: '?nce sipari?leri g?rmem gerekiyor. "/siparis" yazabilir misin?' };
330
- }
331
-
332
- if (asksOrderNames) {
333
- const orders = await this.engine.getOrders({ size: 50, allStatuses: true });
334
- if (!orders || orders.length === 0) {
335
- return { handled: true, response: 'Sipari? verisine ula??lamad?.' };
336
- }
337
- const active = orders.filter(o => isActiveStatus(o.status || o.shipmentPackageStatus || o.orderStatus));
338
- const target = active.length > 0 ? active : orders;
339
- storeLastOrders(this.config, tenantId, target);
340
- if (target.length === 1) {
341
- const only = target[0];
342
- const names = extractProductNames(only);
343
- if (names.length > 0) {
344
- return { handled: true, response: `?r?n adlar?: ${names.join(', ')}` };
345
- }
346
- }
347
- const productLines = target
348
- .map(o => {
349
- const names = extractProductNames(o);
350
- const number = o.orderNumber || o.id || 'N/A';
351
- if (names.length === 0) return null;
352
- return `#${number} - ${names.join(', ')}`;
353
- })
354
- .filter(Boolean)
355
- .slice(0, 10)
356
- .join('\n');
357
- if (!productLines) {
358
- const fallback = target.slice(0, 10).map(formatOrderLine).join('\n');
359
- return { handled: true, response: `Sipari?ler:\n${fallback}` };
360
- }
361
- return { handled: true, response: `?r?n adlar?:\n${productLines}` };
362
- }
363
-
364
- if (asksYesterday) {
365
- const orders = await this.engine.getOrders({ size: 200, allStatuses: true });
366
- if (!orders || orders.length === 0) {
367
- return { handled: true, response: 'Sipari? verisine ula??lamad?.' };
368
- }
369
- const now = Date.now();
370
- const end = new Date(new Date().setHours(0, 0, 0, 0)).getTime();
371
- const start = end - 24 * 60 * 60 * 1000;
372
- const filtered = orders.filter(o => {
373
- const ts = getOrderTimestamp(o);
374
- return ts && ts >= start && ts < end;
375
- });
376
- if (filtered.length === 0) {
377
- return { handled: true, response: 'D?n sipari? yok.' };
378
- }
379
- const wantsShipped = lower.includes('g?nder') || normalized.includes('gonder') || lower.includes('kargoya') || normalized.includes('kargoya');
380
- const shippedOnly = wantsShipped ? filtered.filter(o => {
381
- const s = String(o.status || o.shipmentPackageStatus || o.orderStatus || '').toLowerCase();
382
- return s === 'shipped' || s === 'delivered';
383
- }) : filtered;
384
- const target = shippedOnly.length > 0 ? shippedOnly : filtered;
385
- storeLastOrders(this.config, tenantId, target);
386
- const productLines = target
387
- .map(o => {
388
- const names = extractProductNames(o);
389
- const number = o.orderNumber || o.id || 'N/A';
390
- if (names.length === 0) return null;
391
- return `#${number} - ${names.join(', ')}`;
392
- })
393
- .filter(Boolean)
394
- .slice(0, 10)
395
- .join('\n');
396
- if (productLines) {
397
- return { handled: true, response: `D?nk? ?r?nler:\n${productLines}` };
398
- }
399
- const lines = target.slice(0, 10).map(formatOrderLine).join('\n');
400
- return { handled: true, response: `D?nk? sipari?ler:\n${lines}` };
401
- }
402
-
403
- if (asksToday || asksLast24h) {
404
- const orders = await this.engine.getOrders({ size: 200, allStatuses: true });
405
- if (!orders || orders.length === 0) {
406
- return { handled: true, response: 'Sipari? verisine ula??lamad?.' };
407
- }
408
- const now = Date.now();
409
- const start = asksToday
410
- ? new Date(new Date().setHours(0, 0, 0, 0)).getTime()
411
- : now - 24 * 60 * 60 * 1000;
412
- const filtered = orders.filter(o => {
413
- const ts = getOrderTimestamp(o);
414
- return ts && ts >= start && ts <= now;
415
- });
416
- if (filtered.length === 0) {
417
- return { handled: true, response: 'Belirtilen aral?kta sipari? yok.' };
418
- }
419
- storeLastOrders(this.config, tenantId, filtered);
420
- const lines = filtered.slice(0, 10).map(formatOrderLine).join('\n');
421
- return { handled: true, response: `Sipari?ler:\n${lines}` };
422
- }
423
-
424
- if (lower.includes('sipari? var m?') || normalized.includes('siparis var mi') || lower.includes('sipari? varmi') || normalized.includes('siparis varmi')) {
425
- const orders = await this.engine.getOrders({ size: 100, allStatuses: true });
426
- if (!orders || orders.length === 0) {
427
- return { handled: true, response: 'Sipari? verisine ula??lamad?. L?tfen platform API ba?lant?lar?n? kontrol edin.' };
428
- }
429
- const active = orders.filter(o => isActiveStatus(o.status || o.shipmentPackageStatus || o.orderStatus));
430
- if (active.length === 0) {
431
- return { handled: true, response: '?u an aktif (Created/Picking/UnPacked) sipari? yok.' };
432
- }
433
- const summary = summarizeOrdersByStatus(active);
434
- storeLastOrders(this.config, tenantId, active);
435
- return { handled: true, response: `?u an ba?l? platformlardan gelen toplam ${active.length} aktif sipari? var.${summary ? ` Durum k?r?l?m?: ${summary}` : ''}` };
436
- }
437
-
438
- if (hasOrderKeyword) {
439
- const orders = await this.engine.getOrders({ size: 100, allStatuses: true });
440
- if (!orders || orders.length === 0) {
441
- return {
442
- handled: true,
443
- response: 'Sipari? verisine ula??lamad?. L?tfen platform API ba?lant?lar?n? kontrol edin.'
444
- };
445
- }
446
- const active = orders.filter(o => isActiveStatus(o.status || o.shipmentPackageStatus || o.orderStatus));
447
- const summary = summarizeOrdersByStatus(active);
448
- storeLastOrders(this.config, tenantId, active);
449
- return {
450
- handled: true,
451
- response: `?u an ba?l? platformlardan gelen toplam ${active.length} sipari? var.${summary ? ` Durum k?r?l?m?: ${summary}` : ''}`
452
- };
453
- }
454
-
455
- const tenant = ensureTenantState(this.config, tenantId);
456
-
457
- const pending = findPendingApproval(this.config, meta);
458
- if (pending) {
459
- if (messageHasAny(message, APPROVE_KEYWORDS)) {
460
- removeApproval(this.config, pending.id);
461
- if (pending.kind === 'risk-accept') {
462
- tenant.riskAccepted = true;
463
- saveConfig(this.config);
464
- const approval = newApproval(pending.message, meta, 'action');
465
- this.config.automation.approvals.push(approval);
466
- saveConfig(this.config);
467
- return {
468
- handled: true,
469
- response: 'Risk kabul edildi. ??lemi onaylamak i?in "Evet" yaz.'
470
- };
471
- }
472
- saveConfig(this.config);
473
- const result = await this.engine.chat(pending.message);
474
- return { handled: true, response: `Onay al?nd?.\n\n${result}` };
475
- }
476
- if (messageHasAny(message, REJECT_KEYWORDS)) {
477
- removeApproval(this.config, pending.id);
478
- saveConfig(this.config);
479
- return { handled: true, response: '??lem iptal edildi.' };
480
- }
481
- }
482
-
483
- const plan = (await planWithAI(message, this.engine)) || fallbackPlan(message);
484
- const risky = plan.risk === 'high';
485
-
486
- if (risky && !tenant.riskAccepted) {
487
- const approval = newApproval(message, meta, 'risk-accept');
488
- this.config.automation.approvals.push(approval);
489
- saveConfig(this.config);
490
- return {
491
- handled: true,
492
- response: 'Bu i?lem pazaryerlerinde de?i?iklik yapabilir ve risklidir. Riskleri kabul ediyor musun? "Evet" yaz.'
493
- };
494
- }
495
-
496
- if (risky) {
497
- const approval = newApproval(message, meta, 'action');
498
- this.config.automation.approvals.push(approval);
499
- saveConfig(this.config);
500
- return {
501
- handled: true,
502
- response: `Bu i?lem riskli g?r?n?yor.\nOnaylamak i?in "Evet" yaz.`
503
- };
504
- }
505
-
506
- if (plan.intent === 'schedule' && plan.schedule) {
507
- const job = {
508
- name: `auto-${crypto.randomUUID().slice(0, 8)}`,
509
- cron: plan.schedule,
510
- message: plan.action || message
511
- };
512
- this._scheduleJob(job, true);
513
- return {
514
- handled: true,
515
- response: `Zamanl? g?rev olu?turuldu: ${job.name}\nCron: ${job.cron}`
516
- };
517
- }
518
-
519
- return { handled: false };
520
- }
521
- }
522
-
523
- export default AutomationManager;
1
+ // core/automation.js
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import os from 'os';
5
+ import crypto from 'crypto';
6
+ import { log, chat as aiChat } from './ai-provider.js';
7
+ import { getScheduler } from './scheduler.js';
8
+
9
+ const VANTUZ_HOME = path.join(os.homedir(), '.vantuz');
10
+ const CONFIG_JSON = path.join(VANTUZ_HOME, 'config.json');
11
+
12
+ const RISKY_KEYWORDS = [
13
+ 'güncelle', 'update', 'yayınla', 'publish', 'yayından kaldır', 'unpublish',
14
+ 'değiştir', 'change', 'sil', 'kaldır', 'delete', 'remove',
15
+ 'fiyatı yap', 'stoğu yap'
16
+ ];
17
+
18
+ const APPROVE_KEYWORDS = ['onay', 'onayla', 'kabul', 'evet', 'tamam'];
19
+ const REJECT_KEYWORDS = ['hayır', 'iptal', 'vazgeç', 'reddet'];
20
+
21
+ function loadConfig() {
22
+ try {
23
+ if (fs.existsSync(CONFIG_JSON)) {
24
+ return JSON.parse(fs.readFileSync(CONFIG_JSON, 'utf-8'));
25
+ }
26
+ } catch (e) {
27
+ log('WARN', 'Config okunamadı', { error: e.message });
28
+ }
29
+ return {};
30
+ }
31
+
32
+ function saveConfig(config) {
33
+ try {
34
+ fs.writeFileSync(CONFIG_JSON, JSON.stringify(config, null, 2));
35
+ return true;
36
+ } catch (e) {
37
+ log('WARN', 'Config yazılamadı', { error: e.message });
38
+ return false;
39
+ }
40
+ }
41
+
42
+ function normalizePhone(input) {
43
+ if (!input) return '';
44
+ const cleaned = String(input).replace(/[\s-]/g, '');
45
+ return cleaned.startsWith('+') ? cleaned : `+${cleaned}`;
46
+ }
47
+
48
+ function messageHasAny(message, keywords) {
49
+ const lower = message.toLowerCase();
50
+ return keywords.some(k => lower.includes(k));
51
+ }
52
+
53
+ function normalizeTr(input) {
54
+ return String(input || '')
55
+ .toLowerCase()
56
+ .replace(/[çÇ]/g, 'c')
57
+ .replace(/[ğĞ]/g, 'g')
58
+ .replace(/[ıİ]/g, 'i')
59
+ .replace(/[öÖ]/g, 'o')
60
+ .replace(/[şŞ]/g, 's')
61
+ .replace(/[üÜ]/g, 'u');
62
+ }
63
+
64
+ function summarizeOrdersByStatus(orders = []) {
65
+ if (!Array.isArray(orders) || orders.length === 0) return '';
66
+ const counts = {};
67
+ orders.forEach(o => {
68
+ const s = (o.status || o.shipmentPackageStatus || o.orderStatus || 'UNKNOWN').toString();
69
+ counts[s] = (counts[s] || 0) + 1;
70
+ });
71
+ return Object.entries(counts)
72
+ .sort((a, b) => b[1] - a[1])
73
+ .map(([s, n]) => `${s}:${n}`)
74
+ .join(', ');
75
+ }
76
+
77
+ function isActiveStatus(status) {
78
+ const s = String(status || '').toLowerCase();
79
+ return s === 'created' || s === 'picking' || s === 'unpacked' || s === 'shipped';
80
+ }
81
+
82
+ function extractProductNames(order) {
83
+ const lines = Array.isArray(order?.lines) ? order.lines : [];
84
+ const names = lines
85
+ .map(l => l?.productName || l?.name)
86
+ .filter(Boolean);
87
+ return names;
88
+ }
89
+
90
+ function getOrderTimestamp(order) {
91
+ const candidates = [
92
+ order?.lastModifiedDate,
93
+ order?.agreedDeliveryDate,
94
+ order?.createdDate,
95
+ order?.orderDate
96
+ ];
97
+ for (const value of candidates) {
98
+ if (!value) continue;
99
+ const num = Number(value);
100
+ if (Number.isFinite(num) && num > 0) return num;
101
+ const parsed = Date.parse(value);
102
+ if (!Number.isNaN(parsed)) return parsed;
103
+ }
104
+ return null;
105
+ }
106
+
107
+ function formatOrderLine(order) {
108
+ const number = order.orderNumber || order.id || 'N/A';
109
+ const name = order.customerName || order.customerfullName || order.customerFullName || 'Müşteri';
110
+ const total = order.totalPrice ?? order.totalAmount ?? order.total ?? '?';
111
+ const status = order.status || order.shipmentPackageStatus || order.orderStatus || 'UNKNOWN';
112
+ return `#${number} - ${name} - ${total} TL - ${status}`;
113
+ }
114
+
115
+ function getTenantId(channel, from) {
116
+ if (channel === 'whatsapp' && from) return normalizePhone(from);
117
+ return 'default';
118
+ }
119
+
120
+ function ensureConfigShape(config) {
121
+ if (!config.tenants) config.tenants = {};
122
+ if (!config.automation) config.automation = {};
123
+ if (!config.automation.approvals) config.automation.approvals = [];
124
+ if (!config.automation.cronJobs) config.automation.cronJobs = [];
125
+ return config;
126
+ }
127
+
128
+ function ensureTenantState(config, tenantId) {
129
+ if (!config.tenants[tenantId]) {
130
+ config.tenants[tenantId] = { riskAccepted: false };
131
+ }
132
+ if (!config.tenants[tenantId].session) {
133
+ config.tenants[tenantId].session = {};
134
+ }
135
+ return config.tenants[tenantId];
136
+ }
137
+
138
+ function toSessionOrder(order) {
139
+ return {
140
+ orderNumber: order.orderNumber || order.id || 'N/A',
141
+ status: order.status || order.shipmentPackageStatus || order.orderStatus || 'UNKNOWN',
142
+ productNames: extractProductNames(order)
143
+ };
144
+ }
145
+
146
+ function storeLastOrders(config, tenantId, orders) {
147
+ const tenant = ensureTenantState(config, tenantId);
148
+ const list = Array.isArray(orders) ? orders.map(toSessionOrder) : [];
149
+ tenant.session.lastOrders = list.slice(0, 20);
150
+ tenant.session.lastOrderAt = new Date().toISOString();
151
+ saveConfig(config);
152
+ }
153
+
154
+ function newApproval(message, meta, kind = 'action') {
155
+ return {
156
+ id: crypto.randomUUID(),
157
+ channel: meta.channel,
158
+ from: meta.from || 'unknown',
159
+ message,
160
+ kind,
161
+ createdAt: new Date().toISOString()
162
+ };
163
+ }
164
+
165
+ function findPendingApproval(config, meta) {
166
+ const approvals = config.automation?.approvals || [];
167
+ const from = meta.from || 'unknown';
168
+ return approvals.find(a => a.from === from && a.channel === meta.channel);
169
+ }
170
+
171
+ function removeApproval(config, approvalId) {
172
+ config.automation.approvals = (config.automation.approvals || []).filter(a => a.id !== approvalId);
173
+ }
174
+
175
+ async function planWithAI(message, engine) {
176
+ const systemPrompt = [
177
+ 'Sen Vantuz otomasyon planlayıcısısın.',
178
+ 'Kullanıcı mesajını tek bir otomasyon planına çevir ve sadece JSON döndür.',
179
+ 'Şema:',
180
+ '{ "intent": "report|analysis|change|schedule|other", "risk": "low|high", "schedule": "", "action": "" }',
181
+ 'risk = SADECE veri değiştiren/silen işlemler (update/delete/create) varsa "high" olmalı. Listeleme/okuma işlemleri her zaman "low".',
182
+ 'schedule = cron ifadesi (boş olabilir).',
183
+ 'action = yapılacak işi kısa Türkçe özetle.'
184
+ ].join('\n');
185
+
186
+ const response = await aiChat(message, {
187
+ aiProvider: engine.config.aiProvider || 'gemini',
188
+ systemContext: systemPrompt
189
+ }, engine.env);
190
+
191
+ const jsonMatch = response.match(/\{[\s\S]*\}/);
192
+ if (!jsonMatch) return null;
193
+ try {
194
+ return JSON.parse(jsonMatch[0]);
195
+ } catch {
196
+ return null;
197
+ }
198
+ }
199
+
200
+ function fallbackPlan(message) {
201
+ const risky = messageHasAny(message, RISKY_KEYWORDS);
202
+ // Explicitly safe keywords check
203
+ const safeKeywords = ['listele', 'göster', 'nedir', 'kaç', 'ne kadar', 'durum', 'rapor'];
204
+ const safe = messageHasAny(message, safeKeywords);
205
+
206
+ const schedule = message.includes('cron ') ? message.split('cron ')[1].trim() : '';
207
+ return {
208
+ intent: schedule ? 'schedule' : (risky ? 'change' : 'analysis'),
209
+ risk: (risky && !safe) ? 'high' : 'low',
210
+ schedule,
211
+ action: message
212
+ };
213
+ }
214
+
215
+ export class AutomationManager {
216
+ constructor(engine) {
217
+ this.engine = engine;
218
+ this.scheduler = getScheduler();
219
+ this.config = ensureConfigShape(loadConfig());
220
+ }
221
+
222
+ init() {
223
+ this._restoreCronJobs();
224
+ }
225
+
226
+ _restoreCronJobs() {
227
+ const jobs = this.config.automation?.cronJobs || [];
228
+ for (const job of jobs) {
229
+ this._scheduleJob(job, false);
230
+ }
231
+ }
232
+
233
+ _scheduleJob(job, persist = true) {
234
+ if (!job?.name || !job?.cron || !job?.message) return;
235
+
236
+ this.scheduler.addJob(job.name, job.cron, async () => {
237
+ log('INFO', `Cron job executing: ${job.name}`, { message: job.message });
238
+ await this.engine.chat(job.message);
239
+ }, true);
240
+
241
+ if (persist) {
242
+ const exists = this.config.automation.cronJobs.find(j => j.name === job.name);
243
+ if (!exists) {
244
+ this.config.automation.cronJobs.push(job);
245
+ saveConfig(this.config);
246
+ }
247
+ }
248
+ }
249
+
250
+ _deleteJob(name) {
251
+ this.scheduler.removeJob(name);
252
+ this.config.automation.cronJobs = this.config.automation.cronJobs.filter(j => j.name !== name && j.name !== `auto-${name}`);
253
+ saveConfig(this.config);
254
+ return true;
255
+ }
256
+
257
+ _listJobs() {
258
+ return this.config.automation.cronJobs || [];
259
+ }
260
+
261
+
262
+ async handleMessage(message, meta = { channel: 'local', from: 'local' }) {
263
+ this.config = ensureConfigShape(loadConfig());
264
+
265
+ const lower = String(message || '').toLowerCase();
266
+ const normalized = normalizeTr(message);
267
+ const hasOrderKeyword = lower.includes('sipari?') || normalized.includes('siparis');
268
+ const asksApproved = lower.includes('onaylanan') || normalized.includes('onaylanan');
269
+ const asksUnshipped = lower.includes('kargoya verilmemi?') || lower.includes('hen?z kargoya') || lower.includes('kargoya verilmedi') || normalized.includes('kargoya verilmemis');
270
+ const asksPickingWhich = lower.includes('picking') || normalized.includes('picking');
271
+ const asksOrderNames = lower.includes('sipari?lerin ad?') || normalized.includes('siparislerin adi') || lower.includes('?r?n ad?') || normalized.includes('urun adi') || lower.includes('?r?n?n ad?') || normalized.includes('urunun adi');
272
+ const asksToday = lower.includes('bug?n') || normalized.includes('bugun');
273
+ const asksLast24h = lower.includes('son 24') || normalized.includes('son 24');
274
+ const asksYesterday = lower.includes('d?n') || normalized.includes('dun');
275
+ const asksNeedShipment = lower.includes('kargoya ??kmas?') || lower.includes('kargoya cikmasi') || normalized.includes('kargoya cikmasi');
276
+ const asksWhichProduct = lower.includes('hangi ?r?n') || normalized.includes('hangi urun');
277
+
278
+ const tenantId = getTenantId(meta.channel, meta.from);
279
+ ensureTenantState(this.config, tenantId);
280
+
281
+ if (asksApproved) {
282
+ const orders = await this.engine.getOrders({ size: 100, status: 'Picking' });
283
+ storeLastOrders(this.config, tenantId, orders);
284
+ return {
285
+ handled: true,
286
+ response: `?u an onaylanan (Picking) ${orders.length} sipari? var.`
287
+ };
288
+ }
289
+
290
+ if (asksUnshipped) {
291
+ const orders = await this.engine.getOrders({ size: 100, status: 'Created' });
292
+ storeLastOrders(this.config, tenantId, orders);
293
+ return {
294
+ handled: true,
295
+ response: `?u an kargoya verilmemi? (Created) ${orders.length} sipari? var.`
296
+ };
297
+ }
298
+
299
+ if (asksPickingWhich) {
300
+ const orders = await this.engine.getOrders({ size: 100, status: 'Picking' });
301
+ if (!orders || orders.length === 0) {
302
+ return { handled: true, response: 'Picking stat?s?nde sipari? yok.' };
303
+ }
304
+ storeLastOrders(this.config, tenantId, orders);
305
+ const lines = orders.slice(0, 5).map(formatOrderLine).join('\n');
306
+ return { handled: true, response: `Picking sipari?leri:\n${lines}` };
307
+ }
308
+
309
+ if (asksNeedShipment) {
310
+ const orders = await this.engine.getOrders({ size: 100, status: 'Created' });
311
+ if (!orders || orders.length === 0) {
312
+ return { handled: true, response: 'Kargoya ??kmas? gereken (Created) sipari? yok.' };
313
+ }
314
+ storeLastOrders(this.config, tenantId, orders);
315
+ const lines = orders.slice(0, 5).map(formatOrderLine).join('\n');
316
+ return { handled: true, response: `Kargoya ??kmas? gereken sipari?ler:\n${lines}` };
317
+ }
318
+
319
+ if (asksWhichProduct) {
320
+ const tenant = ensureTenantState(this.config, tenantId);
321
+ const last = tenant.session?.lastOrders || [];
322
+ if (last.length === 1 && last[0].productNames?.length) {
323
+ return { handled: true, response: `?r?n: ${last[0].productNames.join(', ')}` };
324
+ }
325
+ if (last.length > 1) {
326
+ const lines = last.slice(0, 5).map(o => `#${o.orderNumber} - ${o.productNames?.join(', ') || '?r?n ad? yok'}`).join('\n');
327
+ return { handled: true, response: `Hangi sipari?i kastediyorsun?\n${lines}` };
328
+ }
329
+ return { handled: true, response: '?nce sipari?leri g?rmem gerekiyor. "/siparis" yazabilir misin?' };
330
+ }
331
+
332
+ if (asksOrderNames) {
333
+ const orders = await this.engine.getOrders({ size: 50, allStatuses: true });
334
+ if (!orders || orders.length === 0) {
335
+ return { handled: true, response: 'Sipari? verisine ula??lamad?.' };
336
+ }
337
+ const active = orders.filter(o => isActiveStatus(o.status || o.shipmentPackageStatus || o.orderStatus));
338
+ const target = active.length > 0 ? active : orders;
339
+ storeLastOrders(this.config, tenantId, target);
340
+ if (target.length === 1) {
341
+ const only = target[0];
342
+ const names = extractProductNames(only);
343
+ if (names.length > 0) {
344
+ return { handled: true, response: `?r?n adlar?: ${names.join(', ')}` };
345
+ }
346
+ }
347
+ const productLines = target
348
+ .map(o => {
349
+ const names = extractProductNames(o);
350
+ const number = o.orderNumber || o.id || 'N/A';
351
+ if (names.length === 0) return null;
352
+ return `#${number} - ${names.join(', ')}`;
353
+ })
354
+ .filter(Boolean)
355
+ .slice(0, 10)
356
+ .join('\n');
357
+ if (!productLines) {
358
+ const fallback = target.slice(0, 10).map(formatOrderLine).join('\n');
359
+ return { handled: true, response: `Sipari?ler:\n${fallback}` };
360
+ }
361
+ return { handled: true, response: `?r?n adlar?:\n${productLines}` };
362
+ }
363
+
364
+ if (asksYesterday) {
365
+ const orders = await this.engine.getOrders({ size: 200, allStatuses: true });
366
+ if (!orders || orders.length === 0) {
367
+ return { handled: true, response: 'Sipari? verisine ula??lamad?.' };
368
+ }
369
+ const now = Date.now();
370
+ const end = new Date(new Date().setHours(0, 0, 0, 0)).getTime();
371
+ const start = end - 24 * 60 * 60 * 1000;
372
+ const filtered = orders.filter(o => {
373
+ const ts = getOrderTimestamp(o);
374
+ return ts && ts >= start && ts < end;
375
+ });
376
+ if (filtered.length === 0) {
377
+ return { handled: true, response: 'D?n sipari? yok.' };
378
+ }
379
+ const wantsShipped = lower.includes('g?nder') || normalized.includes('gonder') || lower.includes('kargoya') || normalized.includes('kargoya');
380
+ const shippedOnly = wantsShipped ? filtered.filter(o => {
381
+ const s = String(o.status || o.shipmentPackageStatus || o.orderStatus || '').toLowerCase();
382
+ return s === 'shipped' || s === 'delivered';
383
+ }) : filtered;
384
+ const target = shippedOnly.length > 0 ? shippedOnly : filtered;
385
+ storeLastOrders(this.config, tenantId, target);
386
+ const productLines = target
387
+ .map(o => {
388
+ const names = extractProductNames(o);
389
+ const number = o.orderNumber || o.id || 'N/A';
390
+ if (names.length === 0) return null;
391
+ return `#${number} - ${names.join(', ')}`;
392
+ })
393
+ .filter(Boolean)
394
+ .slice(0, 10)
395
+ .join('\n');
396
+ if (productLines) {
397
+ return { handled: true, response: `D?nk? ?r?nler:\n${productLines}` };
398
+ }
399
+ const lines = target.slice(0, 10).map(formatOrderLine).join('\n');
400
+ return { handled: true, response: `D?nk? sipari?ler:\n${lines}` };
401
+ }
402
+
403
+ if (asksToday || asksLast24h) {
404
+ const orders = await this.engine.getOrders({ size: 200, allStatuses: true });
405
+ if (!orders || orders.length === 0) {
406
+ return { handled: true, response: 'Sipari? verisine ula??lamad?.' };
407
+ }
408
+ const now = Date.now();
409
+ const start = asksToday
410
+ ? new Date(new Date().setHours(0, 0, 0, 0)).getTime()
411
+ : now - 24 * 60 * 60 * 1000;
412
+ const filtered = orders.filter(o => {
413
+ const ts = getOrderTimestamp(o);
414
+ return ts && ts >= start && ts <= now;
415
+ });
416
+ if (filtered.length === 0) {
417
+ return { handled: true, response: 'Belirtilen aral?kta sipari? yok.' };
418
+ }
419
+ storeLastOrders(this.config, tenantId, filtered);
420
+ const lines = filtered.slice(0, 10).map(formatOrderLine).join('\n');
421
+ return { handled: true, response: `Sipari?ler:\n${lines}` };
422
+ }
423
+
424
+ if (lower.includes('sipari? var m?') || normalized.includes('siparis var mi') || lower.includes('sipari? varmi') || normalized.includes('siparis varmi')) {
425
+ const orders = await this.engine.getOrders({ size: 100, allStatuses: true });
426
+ if (!orders || orders.length === 0) {
427
+ return { handled: true, response: 'Sipari? verisine ula??lamad?. L?tfen platform API ba?lant?lar?n? kontrol edin.' };
428
+ }
429
+ const active = orders.filter(o => isActiveStatus(o.status || o.shipmentPackageStatus || o.orderStatus));
430
+ if (active.length === 0) {
431
+ return { handled: true, response: '?u an aktif (Created/Picking/UnPacked) sipari? yok.' };
432
+ }
433
+ const summary = summarizeOrdersByStatus(active);
434
+ storeLastOrders(this.config, tenantId, active);
435
+ return { handled: true, response: `?u an ba?l? platformlardan gelen toplam ${active.length} aktif sipari? var.${summary ? ` Durum k?r?l?m?: ${summary}` : ''}` };
436
+ }
437
+
438
+ if (hasOrderKeyword) {
439
+ const orders = await this.engine.getOrders({ size: 100, allStatuses: true });
440
+ if (!orders || orders.length === 0) {
441
+ return {
442
+ handled: true,
443
+ response: 'Sipari? verisine ula??lamad?. L?tfen platform API ba?lant?lar?n? kontrol edin.'
444
+ };
445
+ }
446
+ const active = orders.filter(o => isActiveStatus(o.status || o.shipmentPackageStatus || o.orderStatus));
447
+ const summary = summarizeOrdersByStatus(active);
448
+ storeLastOrders(this.config, tenantId, active);
449
+ return {
450
+ handled: true,
451
+ response: `?u an ba?l? platformlardan gelen toplam ${active.length} sipari? var.${summary ? ` Durum k?r?l?m?: ${summary}` : ''}`
452
+ };
453
+ }
454
+
455
+ const tenant = ensureTenantState(this.config, tenantId);
456
+
457
+ const pending = findPendingApproval(this.config, meta);
458
+ if (pending) {
459
+ if (messageHasAny(message, APPROVE_KEYWORDS)) {
460
+ removeApproval(this.config, pending.id);
461
+ if (pending.kind === 'risk-accept') {
462
+ tenant.riskAccepted = true;
463
+ saveConfig(this.config);
464
+ const approval = newApproval(pending.message, meta, 'action');
465
+ this.config.automation.approvals.push(approval);
466
+ saveConfig(this.config);
467
+ return {
468
+ handled: true,
469
+ response: 'Risk kabul edildi. ??lemi onaylamak i?in "Evet" yaz.'
470
+ };
471
+ }
472
+ saveConfig(this.config);
473
+ const result = await this.engine.chat(pending.message);
474
+ return { handled: true, response: `Onay al?nd?.\n\n${result}` };
475
+ }
476
+ if (messageHasAny(message, REJECT_KEYWORDS)) {
477
+ removeApproval(this.config, pending.id);
478
+ saveConfig(this.config);
479
+ return { handled: true, response: '??lem iptal edildi.' };
480
+ }
481
+ }
482
+
483
+ const plan = (await planWithAI(message, this.engine)) || fallbackPlan(message);
484
+ const risky = plan.risk === 'high';
485
+
486
+ if (risky && !tenant.riskAccepted) {
487
+ const approval = newApproval(message, meta, 'risk-accept');
488
+ this.config.automation.approvals.push(approval);
489
+ saveConfig(this.config);
490
+ return {
491
+ handled: true,
492
+ response: 'Bu i?lem pazaryerlerinde de?i?iklik yapabilir ve risklidir. Riskleri kabul ediyor musun? "Evet" yaz.'
493
+ };
494
+ }
495
+
496
+ if (risky) {
497
+ const approval = newApproval(message, meta, 'action');
498
+ this.config.automation.approvals.push(approval);
499
+ saveConfig(this.config);
500
+ return {
501
+ handled: true,
502
+ response: `Bu i?lem riskli g?r?n?yor.\nOnaylamak i?in "Evet" yaz.`
503
+ };
504
+ }
505
+
506
+ if (plan.intent === 'schedule' && plan.schedule) {
507
+ const job = {
508
+ name: `auto-${crypto.randomUUID().slice(0, 8)}`,
509
+ cron: plan.schedule,
510
+ message: plan.action || message
511
+ };
512
+ this._scheduleJob(job, true);
513
+ return {
514
+ handled: true,
515
+ response: `Zamanl? g?rev olu?turuldu: ${job.name}\nCron: ${job.cron}`
516
+ };
517
+ }
518
+
519
+ return { handled: false };
520
+ }
521
+ }
522
+
523
+ export default AutomationManager;