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
package/core/dashboard.js CHANGED
@@ -1,230 +1,230 @@
1
- // core/dashboard.js
2
- // System Health Dashboard — Vantuz OS V2 Control Tower
3
- // Aggregates status from all modules into a single real-time overview.
4
-
5
- import os from 'os';
6
- import { log } from './ai-provider.js';
7
-
8
- // ═══════════════════════════════════════════════════════════════════════════
9
- // UPTIME TRACKER
10
- // ═══════════════════════════════════════════════════════════════════════════
11
-
12
- const BOOT_TIME = Date.now();
13
-
14
- function formatUptime(ms) {
15
- const seconds = Math.floor(ms / 1000);
16
- const days = Math.floor(seconds / 86400);
17
- const hours = Math.floor((seconds % 86400) / 3600);
18
- const minutes = Math.floor((seconds % 3600) / 60);
19
-
20
- const parts = [];
21
- if (days > 0) parts.push(`${days}g`);
22
- if (hours > 0) parts.push(`${hours}s`);
23
- parts.push(`${minutes}dk`);
24
- return parts.join(' ');
25
- }
26
-
27
- // ═══════════════════════════════════════════════════════════════════════════
28
- // DASHBOARD
29
- // ═══════════════════════════════════════════════════════════════════════════
30
-
31
- class Dashboard {
32
- constructor() {
33
- this.moduleRefs = {}; // name -> getter function
34
- this.customMetrics = {}; // name -> { value, updatedAt }
35
- this.alerts = []; // { level, message, timestamp }
36
- log('INFO', '📊 Dashboard initialized');
37
- }
38
-
39
- /**
40
- * Register a module for health reporting.
41
- * @param {string} name - Module name (e.g., 'warroom', 'oracle').
42
- * @param {function} statusFn - Function that returns module status object.
43
- */
44
- registerModule(name, statusFn) {
45
- this.moduleRefs[name] = statusFn;
46
- }
47
-
48
- /**
49
- * Set a custom metric (can be called from anywhere).
50
- */
51
- setMetric(name, value) {
52
- this.customMetrics[name] = { value, updatedAt: new Date().toISOString() };
53
- }
54
-
55
- /**
56
- * Push a dashboard alert.
57
- */
58
- pushAlert(level, message) {
59
- this.alerts.push({
60
- level, // 'info', 'warning', 'critical'
61
- message,
62
- timestamp: new Date().toISOString()
63
- });
64
- // Keep last 50
65
- if (this.alerts.length > 50) this.alerts = this.alerts.slice(-50);
66
- }
67
-
68
- /**
69
- * Get full system health report.
70
- * @returns {object} Complete health snapshot.
71
- */
72
- getHealth() {
73
- const uptimeMs = Date.now() - BOOT_TIME;
74
-
75
- // ── System Info ──
76
- const system = {
77
- uptime: formatUptime(uptimeMs),
78
- uptimeMs,
79
- bootTime: new Date(BOOT_TIME).toISOString(),
80
- memory: {
81
- total: Math.round(os.totalmem() / 1024 / 1024) + ' MB',
82
- free: Math.round(os.freemem() / 1024 / 1024) + ' MB',
83
- usage: Math.round((1 - os.freemem() / os.totalmem()) * 100) + '%'
84
- },
85
- platform: os.platform(),
86
- nodeVersion: process.version
87
- };
88
-
89
- // ── Module Status ──
90
- const modules = {};
91
- for (const [name, statusFn] of Object.entries(this.moduleRefs)) {
92
- try {
93
- modules[name] = { status: 'online', ...statusFn() };
94
- } catch (e) {
95
- modules[name] = { status: 'error', error: e.message };
96
- }
97
- }
98
-
99
- // ── Overall Health Score ──
100
- const moduleCount = Object.keys(modules).length;
101
- const onlineCount = Object.values(modules).filter(m => m.status === 'online').length;
102
- const healthPercent = moduleCount > 0 ? Math.round((onlineCount / moduleCount) * 100) : 0;
103
-
104
- let overallStatus = '🟢 Healthy';
105
- if (healthPercent < 100) overallStatus = '🟡 Degraded';
106
- if (healthPercent < 50) overallStatus = '🔴 Critical';
107
-
108
- return {
109
- overallStatus,
110
- healthPercent,
111
- system,
112
- modules,
113
- metrics: this.customMetrics,
114
- recentAlerts: this.alerts.slice(-10),
115
- generatedAt: new Date().toISOString()
116
- };
117
- }
118
-
119
- /**
120
- * Get a human-readable summary (for TUI / AI context).
121
- */
122
- getSummary() {
123
- const h = this.getHealth();
124
- const lines = [
125
- `${h.overallStatus} | Uptime: ${h.system.uptime} | RAM: ${h.system.memory.usage}`,
126
- `Modüller: ${h.healthPercent}% online (${Object.keys(h.modules).length} kayıtlı)`,
127
- ''
128
- ];
129
-
130
- for (const [name, mod] of Object.entries(h.modules)) {
131
- const icon = mod.status === 'online' ? '✅' : '❌';
132
- const details = [];
133
-
134
- // Module-specific summary lines
135
- if (mod.autonomous !== undefined) {
136
- details.push(mod.autonomous ? 'Otonom' : '⚠️ Manuel Mod');
137
- }
138
- if (mod.netScore !== undefined) {
139
- details.push(`Skor: ${mod.netScore}`);
140
- }
141
- if (mod.totalErrors !== undefined) {
142
- details.push(`Hata: ${mod.totalErrors}`);
143
- }
144
- if (mod.trackedProducts !== undefined) {
145
- details.push(`Takip: ${mod.trackedProducts} ürün`);
146
- }
147
- if (mod.critical !== undefined) {
148
- details.push(`Kritik: ${mod.critical}`);
149
- }
150
- if (mod.recentDecisions !== undefined) {
151
- details.push(`Karar: ${mod.recentDecisions}`);
152
- }
153
- if (mod.killSwitch?.active) {
154
- details.push('🛑 KILL SWITCH AKTİF');
155
- }
156
- if (mod.activeModules !== undefined) {
157
- details.push(`Aktif: ${mod.activeModules}/${mod.totalModules}`);
158
- }
159
- if (mod.running !== undefined) {
160
- details.push(mod.running ? '🫀 Çalışıyor' : '⏸️ Durdu');
161
- }
162
- if (mod.avgScore !== undefined) {
163
- details.push(`Sağlık: ${mod.avgScore}/100`);
164
- }
165
- if (mod.totalProcessed !== undefined) {
166
- details.push(`İşlenen: ${mod.totalProcessed}`);
167
- }
168
- if (mod.escalatedCount !== undefined && mod.escalatedCount > 0) {
169
- details.push(`🚨 Eskalasyon: ${mod.escalatedCount}`);
170
- }
171
-
172
- lines.push(`${icon} ${name}: ${details.join(' | ') || mod.status}`);
173
- }
174
-
175
- // Custom metrics
176
- if (Object.keys(h.metrics).length > 0) {
177
- lines.push('', '📈 Metrikler:');
178
- for (const [name, m] of Object.entries(h.metrics)) {
179
- lines.push(` ${name}: ${m.value}`);
180
- }
181
- }
182
-
183
- // Recent alerts
184
- const criticalAlerts = h.recentAlerts.filter(a => a.level === 'critical');
185
- if (criticalAlerts.length > 0) {
186
- lines.push('', '🚨 Kritik Uyarılar:');
187
- for (const a of criticalAlerts.slice(-3)) {
188
- lines.push(` ${a.message}`);
189
- }
190
- }
191
-
192
- return lines.join('\n');
193
- }
194
- }
195
-
196
- let dashboardInstance = null;
197
-
198
- export function getDashboard() {
199
- if (!dashboardInstance) {
200
- dashboardInstance = new Dashboard();
201
- }
202
- return dashboardInstance;
203
- }
204
-
205
- /**
206
- * Helper: Wire up all V2 modules to the dashboard.
207
- * Call this after all modules are initialized.
208
- */
209
- export function wireModulesToDashboard(refs = {}) {
210
- const dash = getDashboard();
211
-
212
- if (refs.agentLoop) dash.registerModule('AgentLoop', () => refs.agentLoop.getStatus());
213
- if (refs.pricingEngine) dash.registerModule('WarRoom', () => refs.pricingEngine.getStatus());
214
- if (refs.oracle) dash.registerModule('Oracle', () => refs.oracle.getStatus());
215
- if (refs.crm) dash.registerModule('CRM', () => refs.crm.getStatus());
216
- if (refs.healer) dash.registerModule('ListingHealer', () => refs.healer.getStatus());
217
- if (refs.selfHealer) dash.registerModule('SelfHealer', () => refs.selfHealer.getStatus());
218
- if (refs.learning) dash.registerModule('Learning', () => refs.learning.getStatus());
219
- if (refs.researcher) dash.registerModule('Researcher', () => refs.researcher.getStatus());
220
- if (refs.queue) dash.registerModule('Queue', () => refs.queue.getStatus());
221
- if (refs.memory) dash.registerModule('Memory', () => ({
222
- factsCount: refs.memory.facts?.length || 0,
223
- strategiesCount: refs.memory.strategies?.length || 0
224
- }));
225
-
226
- log('INFO', `📊 Dashboard wired: ${Object.keys(refs).length} modules`);
227
- return dash;
228
- }
229
-
230
- export default Dashboard;
1
+ // core/dashboard.js
2
+ // System Health Dashboard — Vantuz OS V2 Control Tower
3
+ // Aggregates status from all modules into a single real-time overview.
4
+
5
+ import os from 'os';
6
+ import { log } from './ai-provider.js';
7
+
8
+ // ═══════════════════════════════════════════════════════════════════════════
9
+ // UPTIME TRACKER
10
+ // ═══════════════════════════════════════════════════════════════════════════
11
+
12
+ const BOOT_TIME = Date.now();
13
+
14
+ function formatUptime(ms) {
15
+ const seconds = Math.floor(ms / 1000);
16
+ const days = Math.floor(seconds / 86400);
17
+ const hours = Math.floor((seconds % 86400) / 3600);
18
+ const minutes = Math.floor((seconds % 3600) / 60);
19
+
20
+ const parts = [];
21
+ if (days > 0) parts.push(`${days}g`);
22
+ if (hours > 0) parts.push(`${hours}s`);
23
+ parts.push(`${minutes}dk`);
24
+ return parts.join(' ');
25
+ }
26
+
27
+ // ═══════════════════════════════════════════════════════════════════════════
28
+ // DASHBOARD
29
+ // ═══════════════════════════════════════════════════════════════════════════
30
+
31
+ class Dashboard {
32
+ constructor() {
33
+ this.moduleRefs = {}; // name -> getter function
34
+ this.customMetrics = {}; // name -> { value, updatedAt }
35
+ this.alerts = []; // { level, message, timestamp }
36
+ log('INFO', '📊 Dashboard initialized');
37
+ }
38
+
39
+ /**
40
+ * Register a module for health reporting.
41
+ * @param {string} name - Module name (e.g., 'warroom', 'oracle').
42
+ * @param {function} statusFn - Function that returns module status object.
43
+ */
44
+ registerModule(name, statusFn) {
45
+ this.moduleRefs[name] = statusFn;
46
+ }
47
+
48
+ /**
49
+ * Set a custom metric (can be called from anywhere).
50
+ */
51
+ setMetric(name, value) {
52
+ this.customMetrics[name] = { value, updatedAt: new Date().toISOString() };
53
+ }
54
+
55
+ /**
56
+ * Push a dashboard alert.
57
+ */
58
+ pushAlert(level, message) {
59
+ this.alerts.push({
60
+ level, // 'info', 'warning', 'critical'
61
+ message,
62
+ timestamp: new Date().toISOString()
63
+ });
64
+ // Keep last 50
65
+ if (this.alerts.length > 50) this.alerts = this.alerts.slice(-50);
66
+ }
67
+
68
+ /**
69
+ * Get full system health report.
70
+ * @returns {object} Complete health snapshot.
71
+ */
72
+ getHealth() {
73
+ const uptimeMs = Date.now() - BOOT_TIME;
74
+
75
+ // ── System Info ──
76
+ const system = {
77
+ uptime: formatUptime(uptimeMs),
78
+ uptimeMs,
79
+ bootTime: new Date(BOOT_TIME).toISOString(),
80
+ memory: {
81
+ total: Math.round(os.totalmem() / 1024 / 1024) + ' MB',
82
+ free: Math.round(os.freemem() / 1024 / 1024) + ' MB',
83
+ usage: Math.round((1 - os.freemem() / os.totalmem()) * 100) + '%'
84
+ },
85
+ platform: os.platform(),
86
+ nodeVersion: process.version
87
+ };
88
+
89
+ // ── Module Status ──
90
+ const modules = {};
91
+ for (const [name, statusFn] of Object.entries(this.moduleRefs)) {
92
+ try {
93
+ modules[name] = { status: 'online', ...statusFn() };
94
+ } catch (e) {
95
+ modules[name] = { status: 'error', error: e.message };
96
+ }
97
+ }
98
+
99
+ // ── Overall Health Score ──
100
+ const moduleCount = Object.keys(modules).length;
101
+ const onlineCount = Object.values(modules).filter(m => m.status === 'online').length;
102
+ const healthPercent = moduleCount > 0 ? Math.round((onlineCount / moduleCount) * 100) : 0;
103
+
104
+ let overallStatus = '🟢 Healthy';
105
+ if (healthPercent < 100) overallStatus = '🟡 Degraded';
106
+ if (healthPercent < 50) overallStatus = '🔴 Critical';
107
+
108
+ return {
109
+ overallStatus,
110
+ healthPercent,
111
+ system,
112
+ modules,
113
+ metrics: this.customMetrics,
114
+ recentAlerts: this.alerts.slice(-10),
115
+ generatedAt: new Date().toISOString()
116
+ };
117
+ }
118
+
119
+ /**
120
+ * Get a human-readable summary (for TUI / AI context).
121
+ */
122
+ getSummary() {
123
+ const h = this.getHealth();
124
+ const lines = [
125
+ `${h.overallStatus} | Uptime: ${h.system.uptime} | RAM: ${h.system.memory.usage}`,
126
+ `Modüller: ${h.healthPercent}% online (${Object.keys(h.modules).length} kayıtlı)`,
127
+ ''
128
+ ];
129
+
130
+ for (const [name, mod] of Object.entries(h.modules)) {
131
+ const icon = mod.status === 'online' ? '✅' : '❌';
132
+ const details = [];
133
+
134
+ // Module-specific summary lines
135
+ if (mod.autonomous !== undefined) {
136
+ details.push(mod.autonomous ? 'Otonom' : '⚠️ Manuel Mod');
137
+ }
138
+ if (mod.netScore !== undefined) {
139
+ details.push(`Skor: ${mod.netScore}`);
140
+ }
141
+ if (mod.totalErrors !== undefined) {
142
+ details.push(`Hata: ${mod.totalErrors}`);
143
+ }
144
+ if (mod.trackedProducts !== undefined) {
145
+ details.push(`Takip: ${mod.trackedProducts} ürün`);
146
+ }
147
+ if (mod.critical !== undefined) {
148
+ details.push(`Kritik: ${mod.critical}`);
149
+ }
150
+ if (mod.recentDecisions !== undefined) {
151
+ details.push(`Karar: ${mod.recentDecisions}`);
152
+ }
153
+ if (mod.killSwitch?.active) {
154
+ details.push('🛑 KILL SWITCH AKTİF');
155
+ }
156
+ if (mod.activeModules !== undefined) {
157
+ details.push(`Aktif: ${mod.activeModules}/${mod.totalModules}`);
158
+ }
159
+ if (mod.running !== undefined) {
160
+ details.push(mod.running ? '🫀 Çalışıyor' : '⏸️ Durdu');
161
+ }
162
+ if (mod.avgScore !== undefined) {
163
+ details.push(`Sağlık: ${mod.avgScore}/100`);
164
+ }
165
+ if (mod.totalProcessed !== undefined) {
166
+ details.push(`İşlenen: ${mod.totalProcessed}`);
167
+ }
168
+ if (mod.escalatedCount !== undefined && mod.escalatedCount > 0) {
169
+ details.push(`🚨 Eskalasyon: ${mod.escalatedCount}`);
170
+ }
171
+
172
+ lines.push(`${icon} ${name}: ${details.join(' | ') || mod.status}`);
173
+ }
174
+
175
+ // Custom metrics
176
+ if (Object.keys(h.metrics).length > 0) {
177
+ lines.push('', '📈 Metrikler:');
178
+ for (const [name, m] of Object.entries(h.metrics)) {
179
+ lines.push(` ${name}: ${m.value}`);
180
+ }
181
+ }
182
+
183
+ // Recent alerts
184
+ const criticalAlerts = h.recentAlerts.filter(a => a.level === 'critical');
185
+ if (criticalAlerts.length > 0) {
186
+ lines.push('', '🚨 Kritik Uyarılar:');
187
+ for (const a of criticalAlerts.slice(-3)) {
188
+ lines.push(` ${a.message}`);
189
+ }
190
+ }
191
+
192
+ return lines.join('\n');
193
+ }
194
+ }
195
+
196
+ let dashboardInstance = null;
197
+
198
+ export function getDashboard() {
199
+ if (!dashboardInstance) {
200
+ dashboardInstance = new Dashboard();
201
+ }
202
+ return dashboardInstance;
203
+ }
204
+
205
+ /**
206
+ * Helper: Wire up all V2 modules to the dashboard.
207
+ * Call this after all modules are initialized.
208
+ */
209
+ export function wireModulesToDashboard(refs = {}) {
210
+ const dash = getDashboard();
211
+
212
+ if (refs.agentLoop) dash.registerModule('AgentLoop', () => refs.agentLoop.getStatus());
213
+ if (refs.pricingEngine) dash.registerModule('WarRoom', () => refs.pricingEngine.getStatus());
214
+ if (refs.oracle) dash.registerModule('Oracle', () => refs.oracle.getStatus());
215
+ if (refs.crm) dash.registerModule('CRM', () => refs.crm.getStatus());
216
+ if (refs.healer) dash.registerModule('ListingHealer', () => refs.healer.getStatus());
217
+ if (refs.selfHealer) dash.registerModule('SelfHealer', () => refs.selfHealer.getStatus());
218
+ if (refs.learning) dash.registerModule('Learning', () => refs.learning.getStatus());
219
+ if (refs.researcher) dash.registerModule('Researcher', () => refs.researcher.getStatus());
220
+ if (refs.queue) dash.registerModule('Queue', () => refs.queue.getStatus());
221
+ if (refs.memory) dash.registerModule('Memory', () => ({
222
+ factsCount: refs.memory.facts?.length || 0,
223
+ strategiesCount: refs.memory.strategies?.length || 0
224
+ }));
225
+
226
+ log('INFO', `📊 Dashboard wired: ${Object.keys(refs).length} modules`);
227
+ return dash;
228
+ }
229
+
230
+ export default Dashboard;
package/core/database.js CHANGED
@@ -1,41 +1,136 @@
1
- const { Sequelize, DataTypes } = require('sequelize');
1
+ const Database = require('better-sqlite3');
2
2
  const path = require('path');
3
3
  const fs = require('fs');
4
4
 
5
- // Veritabanı dosyasının yolu (Kullanıcının home dizininde veya proje klasöründe)
6
5
  const dbPath = path.join(process.cwd(), 'vantuz.sqlite');
6
+ let db;
7
7
 
8
- const sequelize = new Sequelize({
9
- dialect: 'sqlite',
10
- storage: dbPath,
11
- dialectModule: require('better-sqlite3'),
12
- logging: false // Konsolu kirletmesin
13
- });
8
+ try {
9
+ db = new Database(dbPath);
10
+ console.log('✅ SQLite DB connected directly.');
11
+ } catch (e) {
12
+ console.error('❌ SQLite connection failed:', e);
13
+ process.exit(1);
14
+ }
15
+
16
+ // Simple Model Wrapper to mimic Sequelize API partially
17
+ class Model {
18
+ constructor(tableName, schema) {
19
+ this.tableName = tableName;
20
+ this.schema = schema;
21
+ this._initTable();
22
+ }
23
+
24
+ _initTable() {
25
+ // Basic schema to SQL
26
+ const cols = Object.entries(this.schema).map(([key, props]) => {
27
+ let type = 'TEXT';
28
+ if (props.type === 'INTEGER') type = 'INTEGER';
29
+ if (props.type === 'FLOAT') type = 'REAL';
30
+ if (props.type === 'BOOLEAN') type = 'INTEGER'; // SQLite uses 0/1
31
+
32
+ let def = `${key} ${type}`;
33
+ if (props.allowNull === false) def += ' NOT NULL';
34
+ if (props.unique) def += ' UNIQUE';
35
+ if (props.defaultValue !== undefined) {
36
+ const val = typeof props.defaultValue === 'string' ? `'${props.defaultValue}'` : props.defaultValue;
37
+ def += ` DEFAULT ${val}`;
38
+ }
39
+ return def;
40
+ }).join(', ');
41
+
42
+ const sql = `CREATE TABLE IF NOT EXISTS ${this.tableName} (id INTEGER PRIMARY KEY AUTOINCREMENT, ${cols}, createdAt TEXT, updatedAt TEXT)`;
43
+ db.prepare(sql).run();
44
+ }
45
+
46
+ async findAll(query = {}) {
47
+ // Basic implementation
48
+ const stmt = db.prepare(`SELECT * FROM ${this.tableName}`);
49
+ const rows = stmt.all();
50
+ return rows.map(r => this._parseRow(r));
51
+ }
14
52
 
15
- // --- MODELLER ---
53
+ async findOne(query = {}) {
54
+ if (!query.where) return null;
55
+ const keys = Object.keys(query.where);
56
+ if (keys.length === 0) return null;
57
+
58
+ const whereClause = keys.map(k => `${k} = ?`).join(' AND ');
59
+ const values = keys.map(k => query.where[k]);
60
+
61
+ const stmt = db.prepare(`SELECT * FROM ${this.tableName} WHERE ${whereClause} LIMIT 1`);
62
+ const row = stmt.get(...values);
63
+ return row ? this._parseRow(row) : null;
64
+ }
65
+
66
+ async create(data) {
67
+ const keys = Object.keys(data);
68
+ const placeholders = keys.map(() => '?').join(', ');
69
+ const values = keys.map(k => {
70
+ const val = data[k];
71
+ return typeof val === 'object' ? JSON.stringify(val) : val;
72
+ });
73
+
74
+ const now = new Date().toISOString();
75
+ // Add timestamps
76
+ const allKeys = [...keys, 'createdAt', 'updatedAt'];
77
+ const allPlaceholders = [...keys.map(() => '?'), '?', '?'];
78
+ const allValues = [...values, now, now];
16
79
 
17
- // Mağaza Ayarları (API Keyler vb.)
18
- const Store = sequelize.define('Store', {
80
+ const sql = `INSERT INTO ${this.tableName} (${allKeys.join(', ')}) VALUES (${allPlaceholders.join(', ')})`;
81
+ const info = db.prepare(sql).run(...allValues);
82
+ return { ...data, id: info.lastInsertRowid, createdAt: now, updatedAt: now };
83
+ }
84
+
85
+ async count() {
86
+ const stmt = db.prepare(`SELECT COUNT(*) as count FROM ${this.tableName}`);
87
+ return stmt.get().count;
88
+ }
89
+
90
+ _parseRow(row) {
91
+ // Convert JSON fields back to objects
92
+ for (const [key, props] of Object.entries(this.schema)) {
93
+ if (props.type === 'JSON' && row[key]) {
94
+ try { row[key] = JSON.parse(row[key]); } catch {}
95
+ }
96
+ if (props.type === 'BOOLEAN') {
97
+ row[key] = Boolean(row[key]);
98
+ }
99
+ }
100
+ return row;
101
+ }
102
+ }
103
+
104
+ // Define Models manually with simple types
105
+ const DataTypes = {
106
+ STRING: 'TEXT',
107
+ TEXT: 'TEXT',
108
+ INTEGER: 'INTEGER',
109
+ FLOAT: 'FLOAT',
110
+ BOOLEAN: 'BOOLEAN',
111
+ JSON: 'JSON',
112
+ DATE: 'TEXT'
113
+ };
114
+
115
+ const Store = new Model('Stores', {
19
116
  name: { type: DataTypes.STRING, allowNull: false },
20
- platform: { type: DataTypes.STRING, allowNull: false }, // trendyol, amazon, etc.
21
- credentials: { type: DataTypes.JSON, allowNull: false }, // { apiKey: '...', apiSecret: '...' }
22
- isActive: { type: DataTypes.BOOLEAN, defaultValue: true }
117
+ platform: { type: DataTypes.STRING, allowNull: false },
118
+ credentials: { type: DataTypes.JSON, allowNull: false },
119
+ isActive: { type: DataTypes.BOOLEAN, defaultValue: 1 }
23
120
  });
24
121
 
25
- // Ürünler
26
- const Product = sequelize.define('Product', {
122
+ const Product = new Model('Products', {
27
123
  name: { type: DataTypes.STRING, allowNull: false },
28
124
  barcode: { type: DataTypes.STRING, unique: true },
29
125
  sku: { type: DataTypes.STRING },
30
126
  description: { type: DataTypes.TEXT },
31
127
  brand: { type: DataTypes.STRING },
32
- images: { type: DataTypes.JSON }, // Resim URL'leri listesi
33
- marketData: { type: DataTypes.JSON }, // { trendyol: { price: 100, stock: 10 }, amazon: { ... } }
34
- aiAnalysis: { type: DataTypes.TEXT } // AI tarafından üretilen satış önerileri
128
+ images: { type: DataTypes.JSON },
129
+ marketData: { type: DataTypes.JSON },
130
+ aiAnalysis: { type: DataTypes.TEXT }
35
131
  });
36
132
 
37
- // Siparişler
38
- const Order = sequelize.define('Order', {
133
+ const Order = new Model('Orders', {
39
134
  platform: { type: DataTypes.STRING, allowNull: false },
40
135
  orderNumber: { type: DataTypes.STRING, unique: true },
41
136
  customerName: { type: DataTypes.STRING },
@@ -43,33 +138,36 @@ const Order = sequelize.define('Order', {
43
138
  currency: { type: DataTypes.STRING, defaultValue: 'TRY' },
44
139
  status: { type: DataTypes.STRING },
45
140
  orderDate: { type: DataTypes.DATE },
46
- items: { type: DataTypes.JSON } // Sipariş içeriği
141
+ items: { type: DataTypes.JSON }
47
142
  });
48
143
 
49
- // Loglar ve AI Önerileri
50
- const Insight = sequelize.define('Insight', {
51
- type: { type: DataTypes.STRING }, // 'pricing', 'stock', 'trend'
144
+ const Insight = new Model('Insights', {
145
+ type: { type: DataTypes.STRING },
52
146
  message: { type: DataTypes.TEXT },
53
- priority: { type: DataTypes.INTEGER }, // 1: Düşük, 5: Kritik
54
- isRead: { type: DataTypes.BOOLEAN, defaultValue: false }
147
+ priority: { type: DataTypes.INTEGER },
148
+ isRead: { type: DataTypes.BOOLEAN, defaultValue: 0 }
55
149
  });
56
150
 
57
- // Veritabanını Başlat
58
151
  async function initDB() {
59
- try {
60
- await sequelize.sync({ alter: true }); // Tabloları güncelle
61
- return true;
62
- } catch (error) {
63
- console.error('Veritabanı hatası:', error);
64
- return false;
65
- }
152
+ return true; // Tables created in constructor
153
+ }
154
+
155
+ function getDatabase() {
156
+ return {
157
+ Store,
158
+ Product,
159
+ Order,
160
+ Insight,
161
+ init: initDB,
162
+ isAvailable: true
163
+ };
66
164
  }
67
165
 
68
166
  module.exports = {
69
- sequelize,
70
167
  Store,
71
168
  Product,
72
169
  Order,
73
170
  Insight,
74
- initDB
171
+ initDB,
172
+ getDatabase
75
173
  };