@businesskit/agent 1.0.4 → 1.0.7
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/.claude-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +25 -0
- package/.cursorrules +10 -0
- package/.superconsole-plugin/plugin.json +62 -0
- package/AGENTS.md +105 -63
- package/CLAUDE.md +11 -84
- package/GEMINI.md +11 -34
- package/README.md +95 -154
- package/assets/logo.svg +3 -0
- package/bin/businesskit.js +45 -18
- package/commands/add-contact.md +47 -0
- package/commands/add-inventory-from-invoice.md +80 -0
- package/commands/adjust-stock.md +46 -0
- package/commands/brief.md +12 -0
- package/commands/capabilities.md +33 -0
- package/commands/chase.md +12 -0
- package/commands/check-stock.md +43 -0
- package/commands/create-component.md +109 -0
- package/commands/create-invoice.md +69 -0
- package/commands/create-new-bill.md +65 -0
- package/commands/create-page.md +124 -0
- package/commands/crm.md +13 -0
- package/commands/followups.md +13 -0
- package/commands/list-components.md +41 -0
- package/commands/list-content.md +46 -0
- package/commands/list-pages.md +45 -0
- package/commands/pipeline.md +13 -0
- package/commands/publish-page.md +64 -0
- package/commands/send-invoice.md +42 -0
- package/commands/seo-audit.md +36 -0
- package/commands/update-agent.md +33 -0
- package/commands/update-contact.md +46 -0
- package/commands/update-content.md +48 -0
- package/commands/update-page.md +56 -0
- package/commands/update-price.md +47 -0
- package/commands/write-blog.md +56 -0
- package/commands/write-docs.md +90 -0
- package/commands/write-guide.md +51 -0
- package/commands/write-newsletter.md +50 -0
- package/dist/server.js +4099 -0
- package/mcp_config.json +12 -0
- package/package.json +54 -25
- package/plugin.json +32 -0
- package/scripts/setup.sh +169 -0
- package/scripts/setup.ts +129 -0
- package/scripts/update.sh +56 -0
- package/server.json +21 -0
- package/skills/README.md +20 -27
- package/skills/billing/SKILL.md +64 -0
- package/skills/brand/SKILL.md +30 -86
- package/skills/cms/SKILL.md +111 -0
- package/skills/cms/references/cms-hubs.md +84 -0
- package/skills/cms/references/html-blocks.md +177 -0
- package/skills/copywriting/SKILL.md +1 -1
- package/skills/crm/SKILL.md +24 -0
- package/skills/docs/SKILL.md +65 -0
- package/skills/docs/references/how-to.md +155 -0
- package/skills/inbox/SKILL.md +49 -0
- package/skills/inventory/SKILL.md +69 -0
- package/skills/pages/SKILL.md +214 -0
- package/skills/pages/references/sections-catalog.json +1183 -0
- package/skills/social/SKILL.md +84 -211
- package/skills/social/evals/evals.json +66 -0
- package/skills/social/evals/rubric.md +26 -0
- package/skills/social/examples/repurposing-blog-to-social.md +93 -0
- package/skills/social/examples/weekly-content-calendar.md +30 -0
- package/skills/social/linkedin/SKILL.md +107 -0
- package/skills/social/linkedin/evals/evals.json +106 -0
- package/skills/social/linkedin/evals/rubric.md +28 -0
- package/skills/social/linkedin/examples/gasp-weekly-sprint.md +24 -0
- package/skills/social/linkedin/examples/growth-posts-by-format.md +140 -0
- package/skills/social/linkedin/references/gasp-funnel-and-calibration.md +90 -0
- package/skills/social/linkedin/references/six-growth-formats.md +114 -0
- package/skills/social/references/platforms.md +76 -0
- package/skills/social/references/post-templates.md +105 -0
- package/skills/social/references/reverse-engineering.md +62 -0
- package/src/data/sections-catalog.json +950 -0
- package/src/db.ts +170 -0
- package/src/server.ts +75 -0
- package/src/tools/content.ts +326 -0
- package/src/tools/crm.ts +1416 -0
- package/src/tools/domains.ts +89 -0
- package/src/tools/inbox.ts +270 -0
- package/src/tools/index.ts +116 -0
- package/src/tools/pages.ts +1217 -0
- package/src/tools/shop.ts +771 -0
- package/src/tools/system.ts +94 -0
- package/src/tools/types.ts +17 -0
- package/templates/antigravity.json +8 -0
- package/templates/claude-code.mcp.json +8 -0
- package/templates/cursor.mcp.json +8 -0
- package/templates/vscode.mcp.json +9 -0
- package/.claude/commands/analytics.md +0 -7
- package/.claude/commands/blog-writer.md +0 -9
- package/.claude/commands/cbo.md +0 -7
- package/.claude/commands/ceo.md +0 -10
- package/.claude/commands/cmo.md +0 -7
- package/.claude/commands/compress.md +0 -73
- package/.claude/commands/coo.md +0 -11
- package/.claude/commands/copywriter.md +0 -15
- package/.claude/commands/course-creator.md +0 -9
- package/.claude/commands/crm.md +0 -591
- package/.claude/commands/deep.md +0 -50
- package/.claude/commands/docs-writer.md +0 -8
- package/.claude/commands/forms-builder.md +0 -10
- package/.claude/commands/ingest.md +0 -110
- package/.claude/commands/jobs-manager.md +0 -8
- package/.claude/commands/kb.md +0 -107
- package/.claude/commands/newsletter-writer.md +0 -9
- package/.claude/commands/preserve.md +0 -64
- package/.claude/commands/resume.md +0 -67
- package/.claude/commands/scheduler.md +0 -8
- package/.claude/commands/seo.md +0 -60
- package/.claude/commands/social.md +0 -51
- package/.claude/commands/store-manager.md +0 -11
- package/.claude/settings.json +0 -16
- package/.claude/settings.local.json +0 -11
- package/.env.example +0 -12
- package/.mcp.json +0 -3
- package/HEARTBEAT.md +0 -105
- package/PLAN.md +0 -345
- package/PRD-Agent-Composition.md +0 -149
- package/PRD-Agent-Harness.md +0 -316
- package/REFERENCE.md +0 -160
- package/SOUL.md +0 -148
- package/SYSTEM.md +0 -71
- package/agents/_base.ts +0 -371
- package/agents/analytics/SOUL.md +0 -11
- package/agents/analytics/analytics.ts +0 -405
- package/agents/business/SOUL.md +0 -11
- package/agents/business/business.ts +0 -109
- package/agents/ceo/SOUL.md +0 -15
- package/agents/ceo/ceo.ts +0 -146
- package/agents/content/SOUL.md +0 -11
- package/agents/content/content.ts +0 -379
- package/agents/copywriting/SOUL.md +0 -11
- package/agents/copywriting/copywriting.ts +0 -89
- package/agents/courses/SOUL.md +0 -11
- package/agents/courses/courses.ts +0 -451
- package/agents/docs/SOUL.md +0 -11
- package/agents/docs/docs.ts +0 -77
- package/agents/forms/SOUL.md +0 -11
- package/agents/forms/forms.ts +0 -364
- package/agents/hiring/SOUL.md +0 -11
- package/agents/hiring/hiring.ts +0 -314
- package/agents/marketing/SOUL.md +0 -15
- package/agents/marketing/marketing.ts +0 -109
- package/agents/newsletter/SOUL.md +0 -11
- package/agents/newsletter/newsletter.ts +0 -91
- package/agents/operations/SOUL.md +0 -11
- package/agents/operations/operations.ts +0 -157
- package/agents/sales/SOUL.md +0 -44
- package/agents/sales/sales.ts +0 -883
- package/agents/scheduler/SOUL.md +0 -11
- package/agents/scheduler/scheduler.ts +0 -68
- package/agents/seo/SOUL.md +0 -11
- package/agents/seo/seo.ts +0 -288
- package/agents/social/SOUL.md +0 -11
- package/agents/social/social.ts +0 -744
- package/agents/store/SOUL.md +0 -11
- package/agents/store/store.ts +0 -514
- package/cli.ts +0 -144
- package/context/about-me.md +0 -96
- package/context/brand-voice.md +0 -127
- package/context/brand.md +0 -80
- package/context/business.md +0 -66
- package/context/working-style.md +0 -87
- package/lib/analytics.ts +0 -81
- package/lib/cms.ts +0 -88
- package/lib/db.adapter.ts +0 -30
- package/lib/db.ts +0 -63
- package/lib/enums.ts +0 -25
- package/lib/groups.ts +0 -122
- package/lib/id.ts +0 -43
- package/lib/kb.ts +0 -337
- package/lib/memory.ts +0 -219
- package/lib/pattern-detector.ts +0 -169
- package/lib/profile.ts +0 -155
- package/lib/schema.ts +0 -2015
- package/lib/slug.ts +0 -30
- package/lib/validate.ts +0 -33
- package/setup.ts +0 -141
- package/skills/agents/SKILL.md +0 -56
- package/skills/analytics/SKILL.md +0 -52
- package/skills/blog-writer/SKILL.md +0 -452
- package/skills/ceo/SKILL.md +0 -25
- package/skills/cmo/SKILL.md +0 -8
- package/skills/schema/SKILL.md +0 -86
- package/skills/store/SKILL.md +0 -62
- package/tsconfig.json +0 -14
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
// src/tools/shop.ts
|
|
2
|
+
// Shop & Inventory MCP Tools: Purchases, Restocks, Levels, Pricing, and Invoicing
|
|
3
|
+
|
|
4
|
+
import { execute, generateId, generateSku, query } from '../db.js';
|
|
5
|
+
import type { ToolDefinition, ToolContext } from './types.js';
|
|
6
|
+
|
|
7
|
+
export const shopTools: ToolDefinition[] = [
|
|
8
|
+
{
|
|
9
|
+
name: 'inventory_receive_purchase_invoice',
|
|
10
|
+
domain: 'shop',
|
|
11
|
+
description:
|
|
12
|
+
"Receive inventory items from a vendor purchase invoice, vendor bill, or restock shipment. Records a formal Goods Receipt / Purchase document (doc_type='goods_receipt'), auto-creates missing products in shop_items with clean 10-char alphanumeric SKUs (e.g. '7PKFJ7I5ND'), updates item cost prices, selling prices / markup % (shop_items.price), MRP (default_mrp), taxes, packaging, and logs stock ledger movements with movement_type 'purchase'.",
|
|
13
|
+
inputSchema: {
|
|
14
|
+
type: 'object',
|
|
15
|
+
properties: {
|
|
16
|
+
vendor_name: {
|
|
17
|
+
type: 'string',
|
|
18
|
+
description: "Supplier / Vendor company name (e.g. 'Sun Pharma Healthcare', 'Apple Inc.')",
|
|
19
|
+
},
|
|
20
|
+
invoice_number: {
|
|
21
|
+
type: 'string',
|
|
22
|
+
description: "Vendor's invoice or bill number (e.g. 'INV-MED-44021', 'INV-APL-2026-089')",
|
|
23
|
+
},
|
|
24
|
+
invoice_date: {
|
|
25
|
+
type: 'string',
|
|
26
|
+
description: "Invoice date (e.g. '2026-09-11' or ISO date), optional.",
|
|
27
|
+
},
|
|
28
|
+
location: {
|
|
29
|
+
type: 'string',
|
|
30
|
+
description: 'Warehouse / store name, optional (defaults to Main Warehouse).',
|
|
31
|
+
},
|
|
32
|
+
media_id: {
|
|
33
|
+
type: 'string',
|
|
34
|
+
description: 'Associated media/attachment ID from uploaded invoice document, optional.',
|
|
35
|
+
},
|
|
36
|
+
default_markup_pct: {
|
|
37
|
+
type: 'number',
|
|
38
|
+
description:
|
|
39
|
+
'Default markup % applied to cost_price to compute selling price for shop_items.price (e.g. 20 for cost + 20%), optional.',
|
|
40
|
+
},
|
|
41
|
+
grand_total: {
|
|
42
|
+
type: 'number',
|
|
43
|
+
description:
|
|
44
|
+
'Total final invoice payable amount (after discounts and taxes, e.g. 5091.84), optional.',
|
|
45
|
+
},
|
|
46
|
+
subtotal: {
|
|
47
|
+
type: 'number',
|
|
48
|
+
description: 'Pre-tax/discount subtotal, optional.',
|
|
49
|
+
},
|
|
50
|
+
payment_status: {
|
|
51
|
+
type: 'string',
|
|
52
|
+
enum: ['paid', 'due', 'partial', 'confirmed'],
|
|
53
|
+
description:
|
|
54
|
+
"Payment status of the invoice, optional (defaults to 'confirmed' or 'paid' if paid).",
|
|
55
|
+
},
|
|
56
|
+
payment_method: {
|
|
57
|
+
type: 'string',
|
|
58
|
+
description: "Payment method (e.g. 'cash', 'bank_transfer', 'upi', 'credit'), optional.",
|
|
59
|
+
},
|
|
60
|
+
payment_terms: {
|
|
61
|
+
type: 'string',
|
|
62
|
+
description: "Payment terms (e.g. 'Net 30', 'Net 15', 'Immediate', 'Due on Receipt'), optional.",
|
|
63
|
+
},
|
|
64
|
+
line_items: {
|
|
65
|
+
type: 'array',
|
|
66
|
+
items: {
|
|
67
|
+
type: 'object',
|
|
68
|
+
properties: {
|
|
69
|
+
item: {
|
|
70
|
+
type: 'string',
|
|
71
|
+
description: "Item SKU, ID, or product name (e.g. 'URISPAS TAB', 'Apple Mac Mini', '7PKFJ7I5ND')",
|
|
72
|
+
},
|
|
73
|
+
sku: {
|
|
74
|
+
type: 'string',
|
|
75
|
+
description: 'Explicit product SKU code if provided on bill, optional.',
|
|
76
|
+
},
|
|
77
|
+
quantity: {
|
|
78
|
+
type: 'number',
|
|
79
|
+
description: 'Billed quantity received (e.g. 50, 10)',
|
|
80
|
+
},
|
|
81
|
+
free_qty: {
|
|
82
|
+
type: 'number',
|
|
83
|
+
description: "Free scheme quantity (e.g. 5 for 'buy 50 get 5 free'), optional.",
|
|
84
|
+
},
|
|
85
|
+
unit_cost: {
|
|
86
|
+
type: 'number',
|
|
87
|
+
description: 'Unit cost price before discount/tax (optional if cost_price given).',
|
|
88
|
+
},
|
|
89
|
+
cost_price: {
|
|
90
|
+
type: 'number',
|
|
91
|
+
description: 'Net unit purchase cost price after line discounts.',
|
|
92
|
+
},
|
|
93
|
+
selling_price: {
|
|
94
|
+
type: 'number',
|
|
95
|
+
description: 'Selling price to update on shop_items.price (optional).',
|
|
96
|
+
},
|
|
97
|
+
price: {
|
|
98
|
+
type: 'number',
|
|
99
|
+
description: 'Alias for selling_price (optional).',
|
|
100
|
+
},
|
|
101
|
+
markup_pct: {
|
|
102
|
+
type: 'number',
|
|
103
|
+
description: 'Markup percentage on cost_price (optional).',
|
|
104
|
+
},
|
|
105
|
+
mrp: {
|
|
106
|
+
type: 'number',
|
|
107
|
+
description: 'Maximum Retail Price (default_mrp), optional.',
|
|
108
|
+
},
|
|
109
|
+
tax_pct: {
|
|
110
|
+
type: 'number',
|
|
111
|
+
description: 'GST / Tax percentage (e.g. 12 for 12% GST), optional.',
|
|
112
|
+
},
|
|
113
|
+
batch_number: {
|
|
114
|
+
type: 'string',
|
|
115
|
+
description: 'Batch / Lot number (e.g. ' + "'B2401', optional.",
|
|
116
|
+
},
|
|
117
|
+
expiry_date: {
|
|
118
|
+
type: 'string',
|
|
119
|
+
description: "Expiry date string (e.g. '2026-12', '12/26'), optional.",
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
required: ['item', 'quantity'],
|
|
123
|
+
},
|
|
124
|
+
description: 'List of items received on the purchase invoice',
|
|
125
|
+
},
|
|
126
|
+
notes: { type: 'string', description: 'Optional notes or comments.' },
|
|
127
|
+
},
|
|
128
|
+
required: ['vendor_name', 'line_items'],
|
|
129
|
+
},
|
|
130
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
131
|
+
const { vendor_name, line_items, invoice_number, location, default_markup_pct } = args;
|
|
132
|
+
const profileId = ctx.profileId;
|
|
133
|
+
|
|
134
|
+
// 1. Resolve or create vendor
|
|
135
|
+
let vendorId: string;
|
|
136
|
+
const existingVendors = await query<{ id: string }>(
|
|
137
|
+
'SELECT id FROM shop_vendors WHERE profile_id = ? AND (LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1',
|
|
138
|
+
[profileId, vendor_name.trim(), `%${vendor_name.trim()}%`]
|
|
139
|
+
);
|
|
140
|
+
if (existingVendors.length > 0) {
|
|
141
|
+
vendorId = existingVendors[0].id;
|
|
142
|
+
} else {
|
|
143
|
+
vendorId = generateId('vend');
|
|
144
|
+
await execute(
|
|
145
|
+
'INSERT INTO shop_vendors (id, profile_id, name, payment_terms, is_active) VALUES (?, ?, ?, ?, 1)',
|
|
146
|
+
[vendorId, profileId, vendor_name.trim(), args.payment_terms || 'Net 30']
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// 2. Resolve warehouse
|
|
151
|
+
let warehouseId: string;
|
|
152
|
+
const locName = location || 'Main Warehouse';
|
|
153
|
+
const existingWarehouses = await query<{ id: string }>(
|
|
154
|
+
'SELECT id FROM shop_warehouses WHERE profile_id = ? AND (LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1',
|
|
155
|
+
[profileId, locName, `%${locName}%`]
|
|
156
|
+
);
|
|
157
|
+
if (existingWarehouses.length > 0) {
|
|
158
|
+
warehouseId = existingWarehouses[0].id;
|
|
159
|
+
} else {
|
|
160
|
+
warehouseId = generateId('wh');
|
|
161
|
+
await execute(
|
|
162
|
+
'INSERT INTO shop_warehouses (id, profile_id, name, warehouse_type, is_default, is_active) VALUES (?, ?, ?, ?, 1, 1)',
|
|
163
|
+
[warehouseId, profileId, locName, 'general']
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// 3. Sequential doc number
|
|
168
|
+
const countRes = await query<{ cnt: number }>(
|
|
169
|
+
"SELECT COUNT(*) as cnt FROM shop_documents WHERE profile_id = ? AND doc_type = 'goods_receipt'",
|
|
170
|
+
[profileId]
|
|
171
|
+
);
|
|
172
|
+
const seq = Number(countRes[0]?.cnt || 0) + 1;
|
|
173
|
+
const docNumber = `GR-${String(seq).padStart(4, '0')}`;
|
|
174
|
+
const docId = generateId('doc');
|
|
175
|
+
|
|
176
|
+
let totalCost = 0;
|
|
177
|
+
let totalQty = 0;
|
|
178
|
+
const processedItems = [];
|
|
179
|
+
|
|
180
|
+
// 4. Process line items
|
|
181
|
+
for (const line of line_items) {
|
|
182
|
+
const itemRef = String(line.item || '').trim();
|
|
183
|
+
const billedQty = Number(line.quantity || 0);
|
|
184
|
+
const freeQty = Number(line.free_qty || 0);
|
|
185
|
+
const totalLineQty = billedQty + freeQty;
|
|
186
|
+
const costPrice = Number(line.cost_price || line.unit_cost || 0);
|
|
187
|
+
const mrp = line.mrp ? Number(line.mrp) : undefined;
|
|
188
|
+
let sellingPrice = line.selling_price || line.price ? Number(line.selling_price || line.price) : undefined;
|
|
189
|
+
|
|
190
|
+
if (!sellingPrice && default_markup_pct && costPrice > 0) {
|
|
191
|
+
sellingPrice = Math.round(costPrice * (1 + Number(default_markup_pct) / 100) * 100) / 100;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Find or create item
|
|
195
|
+
let itemId: string;
|
|
196
|
+
let itemSku: string;
|
|
197
|
+
let itemName = itemRef;
|
|
198
|
+
|
|
199
|
+
const itemsFound = await query<{ id: string; name: string; sku: string }>(
|
|
200
|
+
'SELECT id, name, sku FROM shop_items WHERE profile_id = ? AND (sku = ? OR id = ? OR LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1',
|
|
201
|
+
[profileId, itemRef, itemRef, itemRef, `%${itemRef}%`]
|
|
202
|
+
);
|
|
203
|
+
|
|
204
|
+
if (itemsFound.length > 0) {
|
|
205
|
+
itemId = itemsFound[0].id;
|
|
206
|
+
itemName = itemsFound[0].name;
|
|
207
|
+
itemSku = itemsFound[0].sku || generateSku();
|
|
208
|
+
// Update cost and selling price
|
|
209
|
+
const updates: string[] = [];
|
|
210
|
+
const updateParams: any[] = [];
|
|
211
|
+
if (costPrice > 0) {
|
|
212
|
+
updates.push('cost_price = ?');
|
|
213
|
+
updateParams.push(costPrice);
|
|
214
|
+
}
|
|
215
|
+
if (sellingPrice && sellingPrice > 0) {
|
|
216
|
+
updates.push('price = ?');
|
|
217
|
+
updateParams.push(sellingPrice);
|
|
218
|
+
}
|
|
219
|
+
if (mrp && mrp > 0) {
|
|
220
|
+
updates.push('default_mrp = ?');
|
|
221
|
+
updateParams.push(mrp);
|
|
222
|
+
}
|
|
223
|
+
if (updates.length > 0) {
|
|
224
|
+
updates.push("updated_at = strftime('%s','now')");
|
|
225
|
+
updateParams.push(itemId, profileId);
|
|
226
|
+
await execute(
|
|
227
|
+
`UPDATE shop_items SET ${updates.join(', ')} WHERE id = ? AND profile_id = ?`,
|
|
228
|
+
updateParams
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
} else {
|
|
232
|
+
itemId = generateId('item');
|
|
233
|
+
itemSku = (line.sku || (itemRef.length <= 16 && !itemRef.includes(' ') ? itemRef : generateSku())).toUpperCase();
|
|
234
|
+
const slug = `item-${itemName.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
|
|
235
|
+
await execute(
|
|
236
|
+
`INSERT INTO shop_items (id, profile_id, name, sku, slug, cost_price, price, default_mrp, is_active, created_at, updated_at)
|
|
237
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, strftime('%s','now'), strftime('%s','now'))`,
|
|
238
|
+
[itemId, profileId, itemName, itemSku, slug, costPrice, sellingPrice || costPrice, mrp || 0]
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Ledger movement
|
|
243
|
+
const ledgerId = generateId('stk');
|
|
244
|
+
await execute(
|
|
245
|
+
`INSERT INTO shop_stock_ledger (id, profile_id, item_id, warehouse_id, movement_type, qty_in, qty_out, unit_cost, reference_type, reference_id, created_at)
|
|
246
|
+
VALUES (?, ?, ?, ?, 'purchase', ?, 0, ?, 'goods_receipt', ?, strftime('%s','now'))`,
|
|
247
|
+
[ledgerId, profileId, itemId, warehouseId, totalLineQty, costPrice, docId]
|
|
248
|
+
);
|
|
249
|
+
|
|
250
|
+
// Document line
|
|
251
|
+
const lineId = generateId('line');
|
|
252
|
+
const lineTotal = billedQty * costPrice;
|
|
253
|
+
await execute(
|
|
254
|
+
`INSERT INTO shop_document_lines (id, profile_id, document_id, item_id, description, quantity, unit_price, total_amount, created_at)
|
|
255
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, strftime('%s','now'))`,
|
|
256
|
+
[lineId, profileId, docId, itemId, itemName, billedQty, costPrice, lineTotal]
|
|
257
|
+
);
|
|
258
|
+
|
|
259
|
+
totalCost += lineTotal;
|
|
260
|
+
totalQty += totalLineQty;
|
|
261
|
+
processedItems.push({ item_id: itemId, sku: itemSku, name: itemName, quantity: totalLineQty, cost_price: costPrice });
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// 5. Create goods_receipt document
|
|
265
|
+
await execute(
|
|
266
|
+
`INSERT INTO shop_documents (id, profile_id, doc_type, doc_number, vendor_id, warehouse_id, total, status, notes, created_at, updated_at)
|
|
267
|
+
VALUES (?, ?, 'goods_receipt', ?, ?, ?, ?, ?, ?, strftime('%s','now'), strftime('%s','now'))`,
|
|
268
|
+
[docId, profileId, docNumber, vendorId, warehouseId, totalCost, args.payment_status || 'confirmed', args.notes || '']
|
|
269
|
+
);
|
|
270
|
+
|
|
271
|
+
return {
|
|
272
|
+
success: true,
|
|
273
|
+
doc_id: docId,
|
|
274
|
+
doc_number: docNumber,
|
|
275
|
+
vendor_name: vendor_name,
|
|
276
|
+
invoice_number: invoice_number || null,
|
|
277
|
+
warehouse: locName,
|
|
278
|
+
total_items: processedItems.length,
|
|
279
|
+
total_quantity: totalQty,
|
|
280
|
+
grand_total: totalCost,
|
|
281
|
+
items: processedItems,
|
|
282
|
+
};
|
|
283
|
+
},
|
|
284
|
+
},
|
|
285
|
+
{
|
|
286
|
+
name: 'product_update_pricing',
|
|
287
|
+
domain: 'shop',
|
|
288
|
+
description:
|
|
289
|
+
'Directly update product pricing, selling price (shop_items.price), cost price (shop_items.cost_price), markup percentage, MRP, or discounts for an existing item by SKU, ID, or name.',
|
|
290
|
+
inputSchema: {
|
|
291
|
+
type: 'object',
|
|
292
|
+
properties: {
|
|
293
|
+
sku: {
|
|
294
|
+
type: 'string',
|
|
295
|
+
description: "Item SKU, product name, or ID (e.g. '7PKFJ7I5ND', 'Apple Mac Mini', 'item_...')",
|
|
296
|
+
},
|
|
297
|
+
selling_price: { type: 'number', description: 'New selling price (shop_items.price), optional.' },
|
|
298
|
+
price: { type: 'number', description: 'Alias for selling_price, optional.' },
|
|
299
|
+
cost_price: { type: 'number', description: 'New cost / purchase price (shop_items.cost_price), optional.' },
|
|
300
|
+
markup_pct: { type: 'number', description: 'Markup percentage on cost_price to compute selling price, optional.' },
|
|
301
|
+
mrp: { type: 'number', description: 'Maximum Retail Price (default_mrp), optional.' },
|
|
302
|
+
discount_pct: { type: 'number', description: 'Default discount percentage, optional.' },
|
|
303
|
+
},
|
|
304
|
+
required: ['sku'],
|
|
305
|
+
},
|
|
306
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
307
|
+
const profileId = ctx.profileId;
|
|
308
|
+
const ref = String(args.sku).trim();
|
|
309
|
+
|
|
310
|
+
const items = await query<{ id: string; name: string; sku: string; price: number; cost_price: number; default_mrp: number }>(
|
|
311
|
+
'SELECT id, name, sku, price, cost_price, default_mrp FROM shop_items WHERE profile_id = ? AND (sku = ? OR id = ? OR LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1',
|
|
312
|
+
[profileId, ref, ref, ref, `%${ref}%`]
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
if (items.length === 0) {
|
|
316
|
+
throw new Error(`Product not found with identifier: ${ref}`);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const item = items[0];
|
|
320
|
+
const updates: string[] = [];
|
|
321
|
+
const params: any[] = [];
|
|
322
|
+
|
|
323
|
+
let costPrice = item.cost_price;
|
|
324
|
+
if (args.cost_price !== undefined) {
|
|
325
|
+
costPrice = Number(args.cost_price);
|
|
326
|
+
updates.push('cost_price = ?');
|
|
327
|
+
params.push(costPrice);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
let sellingPrice = args.selling_price !== undefined ? Number(args.selling_price) : args.price !== undefined ? Number(args.price) : undefined;
|
|
331
|
+
if (sellingPrice === undefined && args.markup_pct !== undefined && costPrice > 0) {
|
|
332
|
+
sellingPrice = Math.round(costPrice * (1 + Number(args.markup_pct) / 100) * 100) / 100;
|
|
333
|
+
}
|
|
334
|
+
if (sellingPrice !== undefined) {
|
|
335
|
+
updates.push('price = ?');
|
|
336
|
+
params.push(sellingPrice);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (args.mrp !== undefined) {
|
|
340
|
+
updates.push('default_mrp = ?');
|
|
341
|
+
params.push(Number(args.mrp));
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (updates.length === 0) {
|
|
345
|
+
return { success: true, message: 'No pricing updates specified.', item };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
updates.push("updated_at = strftime('%s','now')");
|
|
349
|
+
params.push(item.id, profileId);
|
|
350
|
+
|
|
351
|
+
await execute(`UPDATE shop_items SET ${updates.join(', ')} WHERE id = ? AND profile_id = ?`, params);
|
|
352
|
+
|
|
353
|
+
return {
|
|
354
|
+
success: true,
|
|
355
|
+
sku: item.sku,
|
|
356
|
+
name: item.name,
|
|
357
|
+
previous_price: item.price,
|
|
358
|
+
new_price: sellingPrice ?? item.price,
|
|
359
|
+
previous_cost: item.cost_price,
|
|
360
|
+
new_cost: costPrice,
|
|
361
|
+
};
|
|
362
|
+
},
|
|
363
|
+
},
|
|
364
|
+
{
|
|
365
|
+
name: 'inventory_add_stock',
|
|
366
|
+
domain: 'shop',
|
|
367
|
+
description:
|
|
368
|
+
'Add or adjust stock quantity for a SKU, product name, or item ID. Use for restocks, counts, or corrections.',
|
|
369
|
+
inputSchema: {
|
|
370
|
+
type: 'object',
|
|
371
|
+
properties: {
|
|
372
|
+
sku: { type: 'string', description: "Item SKU, product name, or identifier (e.g. 'Apple Mac Mini', '2B4FYFAVIO')" },
|
|
373
|
+
quantity_delta: { type: 'number', description: 'Positive to add stock, negative to remove.' },
|
|
374
|
+
movement_type: {
|
|
375
|
+
type: 'string',
|
|
376
|
+
enum: ['purchase', 'adjustment'],
|
|
377
|
+
description: "Type of movement: 'purchase' for vendor restock or 'adjustment' for manual count/correction (default: 'adjustment').",
|
|
378
|
+
},
|
|
379
|
+
unit_cost: { type: 'number', description: 'Unit purchase cost if applicable.' },
|
|
380
|
+
vendor_name: { type: 'string', description: 'Vendor name if this is a purchase.' },
|
|
381
|
+
invoice_number: { type: 'string', description: 'Invoice reference number if applicable.' },
|
|
382
|
+
location: { type: 'string', description: 'Optional warehouse name or location tag.' },
|
|
383
|
+
},
|
|
384
|
+
required: ['sku', 'quantity_delta'],
|
|
385
|
+
},
|
|
386
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
387
|
+
const profileId = ctx.profileId;
|
|
388
|
+
const ref = String(args.sku).trim();
|
|
389
|
+
const delta = Number(args.quantity_delta);
|
|
390
|
+
|
|
391
|
+
const items = await query<{ id: string; name: string; sku: string; cost_price: number }>(
|
|
392
|
+
'SELECT id, name, sku, cost_price FROM shop_items WHERE profile_id = ? AND (sku = ? OR id = ? OR LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1',
|
|
393
|
+
[profileId, ref, ref, ref, `%${ref}%`]
|
|
394
|
+
);
|
|
395
|
+
|
|
396
|
+
let itemId: string;
|
|
397
|
+
let itemName = ref;
|
|
398
|
+
let itemSku: string;
|
|
399
|
+
|
|
400
|
+
if (items.length > 0) {
|
|
401
|
+
itemId = items[0].id;
|
|
402
|
+
itemName = items[0].name;
|
|
403
|
+
itemSku = items[0].sku;
|
|
404
|
+
} else {
|
|
405
|
+
itemId = generateId('item');
|
|
406
|
+
itemSku = generateSku();
|
|
407
|
+
const slug = `item-${ref.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
|
|
408
|
+
await execute(
|
|
409
|
+
`INSERT INTO shop_items (id, profile_id, name, sku, slug, cost_price, price, is_active, created_at, updated_at)
|
|
410
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 1, strftime('%s','now'), strftime('%s','now'))`,
|
|
411
|
+
[itemId, profileId, ref, itemSku, slug, args.unit_cost || 0, args.unit_cost || 0]
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// Warehouse
|
|
416
|
+
const loc = args.location || 'Main Warehouse';
|
|
417
|
+
const whs = await query<{ id: string }>('SELECT id FROM shop_warehouses WHERE profile_id = ? LIMIT 1', [profileId]);
|
|
418
|
+
const warehouseId = whs.length > 0 ? whs[0].id : 'default';
|
|
419
|
+
|
|
420
|
+
const qtyIn = delta > 0 ? delta : 0;
|
|
421
|
+
const qtyOut = delta < 0 ? Math.abs(delta) : 0;
|
|
422
|
+
const movementType = args.movement_type || (delta > 0 ? 'adjustment' : 'adjustment');
|
|
423
|
+
const ledgerId = generateId('stk');
|
|
424
|
+
|
|
425
|
+
await execute(
|
|
426
|
+
`INSERT INTO shop_stock_ledger (id, profile_id, item_id, warehouse_id, movement_type, qty_in, qty_out, unit_cost, notes, created_at)
|
|
427
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, strftime('%s','now'))`,
|
|
428
|
+
[ledgerId, profileId, itemId, warehouseId, movementType, qtyIn, qtyOut, args.unit_cost || 0, args.invoice_number || 'Stock Adjustment']
|
|
429
|
+
);
|
|
430
|
+
|
|
431
|
+
// Compute balance
|
|
432
|
+
const balRes = await query<{ balance: number }>(
|
|
433
|
+
'SELECT COALESCE(SUM(qty_in - qty_out), 0) as balance FROM shop_stock_ledger WHERE profile_id = ? AND item_id = ?',
|
|
434
|
+
[profileId, itemId]
|
|
435
|
+
);
|
|
436
|
+
|
|
437
|
+
return {
|
|
438
|
+
success: true,
|
|
439
|
+
sku: itemSku,
|
|
440
|
+
name: itemName,
|
|
441
|
+
quantity_delta: delta,
|
|
442
|
+
current_stock: Number(balRes[0]?.balance || 0),
|
|
443
|
+
movement_type: movementType,
|
|
444
|
+
};
|
|
445
|
+
},
|
|
446
|
+
},
|
|
447
|
+
{
|
|
448
|
+
name: 'inventory_get_levels',
|
|
449
|
+
domain: 'shop',
|
|
450
|
+
description: 'Look up current stock levels, optionally filtered by SKU or category.',
|
|
451
|
+
inputSchema: {
|
|
452
|
+
type: 'object',
|
|
453
|
+
properties: {
|
|
454
|
+
sku: { type: 'string', description: 'Optional SKU or product name to query specific item balance.' },
|
|
455
|
+
category: { type: 'string', description: 'Optional category name filter.' },
|
|
456
|
+
},
|
|
457
|
+
},
|
|
458
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
459
|
+
const profileId = ctx.profileId;
|
|
460
|
+
const skuFilter = args.sku ? `%${String(args.sku).trim()}%` : null;
|
|
461
|
+
|
|
462
|
+
let sql = `
|
|
463
|
+
SELECT i.id, i.name, i.sku, i.price, i.cost_price,
|
|
464
|
+
COALESCE(SUM(l.qty_in - l.qty_out), 0) as stock_on_hand
|
|
465
|
+
FROM shop_items i
|
|
466
|
+
LEFT JOIN shop_stock_ledger l ON i.id = l.item_id AND l.profile_id = i.profile_id
|
|
467
|
+
WHERE i.profile_id = ?
|
|
468
|
+
`;
|
|
469
|
+
const params: any[] = [profileId];
|
|
470
|
+
|
|
471
|
+
if (skuFilter) {
|
|
472
|
+
sql += ' AND (i.sku LIKE ? OR i.name LIKE ? OR i.id = ?)';
|
|
473
|
+
params.push(skuFilter, skuFilter, args.sku.trim());
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
sql += ' GROUP BY i.id ORDER BY i.name ASC LIMIT 100';
|
|
477
|
+
|
|
478
|
+
const items = await query(sql, params);
|
|
479
|
+
return {
|
|
480
|
+
total: items.length,
|
|
481
|
+
items: items.map((r: any) => ({
|
|
482
|
+
id: r.id,
|
|
483
|
+
name: r.name,
|
|
484
|
+
sku: r.sku,
|
|
485
|
+
selling_price: r.price,
|
|
486
|
+
cost_price: r.cost_price,
|
|
487
|
+
stock_on_hand: Number(r.stock_on_hand || 0),
|
|
488
|
+
})),
|
|
489
|
+
};
|
|
490
|
+
},
|
|
491
|
+
},
|
|
492
|
+
{
|
|
493
|
+
name: 'invoice_create',
|
|
494
|
+
domain: 'shop',
|
|
495
|
+
description: 'Create and draft a customer sales invoice in the shop billing system.',
|
|
496
|
+
inputSchema: {
|
|
497
|
+
type: 'object',
|
|
498
|
+
properties: {
|
|
499
|
+
customer_name: { type: 'string', description: 'Customer name or company name' },
|
|
500
|
+
line_items: {
|
|
501
|
+
type: 'array',
|
|
502
|
+
items: {
|
|
503
|
+
type: 'object',
|
|
504
|
+
properties: {
|
|
505
|
+
description: { type: 'string' },
|
|
506
|
+
quantity: { type: 'number' },
|
|
507
|
+
unit_price: { type: 'number' },
|
|
508
|
+
},
|
|
509
|
+
required: ['description', 'quantity', 'unit_price'],
|
|
510
|
+
},
|
|
511
|
+
},
|
|
512
|
+
due_date: { type: 'string', description: 'Due date in YYYY-MM-DD format' },
|
|
513
|
+
},
|
|
514
|
+
required: ['customer_name', 'line_items'],
|
|
515
|
+
},
|
|
516
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
517
|
+
const profileId = ctx.profileId;
|
|
518
|
+
const { customer_name, line_items, due_date } = args;
|
|
519
|
+
|
|
520
|
+
// Customer
|
|
521
|
+
let customerId: string;
|
|
522
|
+
const custs = await query<{ id: string }>(
|
|
523
|
+
'SELECT id FROM shop_customers WHERE profile_id = ? AND (LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1',
|
|
524
|
+
[profileId, customer_name.trim(), `%${customer_name.trim()}%`]
|
|
525
|
+
);
|
|
526
|
+
if (custs.length > 0) {
|
|
527
|
+
customerId = custs[0].id;
|
|
528
|
+
} else {
|
|
529
|
+
customerId = generateId('cust');
|
|
530
|
+
await execute(
|
|
531
|
+
'INSERT INTO shop_customers (id, profile_id, name, customer_type, is_active) VALUES (?, ?, ?, ?, 1)',
|
|
532
|
+
[customerId, profileId, customer_name.trim(), 'individual']
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// Sequential invoice number
|
|
537
|
+
const cntRes = await query<{ cnt: number }>(
|
|
538
|
+
"SELECT COUNT(*) as cnt FROM shop_documents WHERE profile_id = ? AND doc_type = 'invoice'",
|
|
539
|
+
[profileId]
|
|
540
|
+
);
|
|
541
|
+
const seq = Number(cntRes[0]?.cnt || 0) + 1;
|
|
542
|
+
const docNumber = `INV-${String(seq).padStart(4, '0')}`;
|
|
543
|
+
const docId = generateId('doc');
|
|
544
|
+
|
|
545
|
+
let grandTotal = 0;
|
|
546
|
+
for (const line of line_items) {
|
|
547
|
+
const lineTotal = Number(line.quantity || 1) * Number(line.unit_price || 0);
|
|
548
|
+
grandTotal += lineTotal;
|
|
549
|
+
const lineId = generateId('line');
|
|
550
|
+
await execute(
|
|
551
|
+
`INSERT INTO shop_document_lines (id, profile_id, document_id, description, quantity, unit_price, total_amount, created_at)
|
|
552
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, strftime('%s','now'))`,
|
|
553
|
+
[lineId, profileId, docId, line.description, line.quantity, line.unit_price, lineTotal]
|
|
554
|
+
);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
await execute(
|
|
558
|
+
`INSERT INTO shop_documents (id, profile_id, doc_type, doc_number, customer_id, total, status, notes, created_at, updated_at)
|
|
559
|
+
VALUES (?, ?, 'invoice', ?, ?, ?, 'draft', ?, strftime('%s','now'), strftime('%s','now'))`,
|
|
560
|
+
[docId, profileId, docNumber, customerId, grandTotal, due_date ? `Due: ${due_date}` : '']
|
|
561
|
+
);
|
|
562
|
+
|
|
563
|
+
return {
|
|
564
|
+
success: true,
|
|
565
|
+
invoice_id: docId,
|
|
566
|
+
invoice_number: docNumber,
|
|
567
|
+
customer_name,
|
|
568
|
+
total: grandTotal,
|
|
569
|
+
status: 'draft',
|
|
570
|
+
};
|
|
571
|
+
},
|
|
572
|
+
},
|
|
573
|
+
{
|
|
574
|
+
name: 'invoice_send',
|
|
575
|
+
domain: 'shop',
|
|
576
|
+
description: 'Mark a sales invoice as issued and ready for customer dispatch.',
|
|
577
|
+
inputSchema: {
|
|
578
|
+
type: 'object',
|
|
579
|
+
properties: {
|
|
580
|
+
invoice_id: { type: 'string', description: "Invoice document ID or invoice number (e.g. 'doc_...' or 'INV-0001')" },
|
|
581
|
+
recipient_email: { type: 'string', description: 'Customer email to send the invoice notification to' },
|
|
582
|
+
},
|
|
583
|
+
required: ['invoice_id'],
|
|
584
|
+
},
|
|
585
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
586
|
+
const profileId = ctx.profileId;
|
|
587
|
+
const ref = String(args.invoice_id).trim();
|
|
588
|
+
|
|
589
|
+
const docs = await query<{ id: string; doc_number: string; status: string }>(
|
|
590
|
+
'SELECT id, doc_number, status FROM shop_documents WHERE profile_id = ? AND (id = ? OR doc_number = ?) LIMIT 1',
|
|
591
|
+
[profileId, ref, ref]
|
|
592
|
+
);
|
|
593
|
+
|
|
594
|
+
if (docs.length === 0) {
|
|
595
|
+
throw new Error(`Invoice not found with identifier: ${ref}`);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
await execute(
|
|
599
|
+
"UPDATE shop_documents SET status = 'sent', updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?",
|
|
600
|
+
[docs[0].id, profileId]
|
|
601
|
+
);
|
|
602
|
+
|
|
603
|
+
return {
|
|
604
|
+
success: true,
|
|
605
|
+
invoice_id: docs[0].id,
|
|
606
|
+
invoice_number: docs[0].doc_number,
|
|
607
|
+
status: 'sent',
|
|
608
|
+
recipient_email: args.recipient_email || null,
|
|
609
|
+
};
|
|
610
|
+
},
|
|
611
|
+
},
|
|
612
|
+
{
|
|
613
|
+
name: 'shop_create_new_bill',
|
|
614
|
+
domain: 'shop',
|
|
615
|
+
description:
|
|
616
|
+
'Create a new customer sale bill / sales invoice from natural-language or handwritten-bill input. Resolves or auto-creates items, records stock ledger movements (sale), and writes a SAL-NNNN document.',
|
|
617
|
+
inputSchema: {
|
|
618
|
+
type: 'object',
|
|
619
|
+
properties: {
|
|
620
|
+
customer_name: { type: 'string', description: "Customer name, company, or 'Counter Sale' for walk-in (optional)." },
|
|
621
|
+
customer_id: { type: 'string', description: 'Existing customer ID if known (optional).' },
|
|
622
|
+
bill_date: { type: 'string', description: 'Bill date in YYYY-MM-DD or human format (optional, defaults to today).' },
|
|
623
|
+
payment_status: { type: 'string', enum: ['paid', 'due', 'credit'], description: "Payment status: 'paid', 'due'. Default: 'paid'." },
|
|
624
|
+
payment_method: { type: 'string', description: "Payment method: 'cash', 'upi', 'bank_transfer', 'credit'. Default: 'cash'." },
|
|
625
|
+
bill_discount_pct: { type: 'number', description: 'Optional bill-level discount % applied to total.' },
|
|
626
|
+
bill_discount_amt: { type: 'number', description: 'Optional flat bill discount amount.' },
|
|
627
|
+
notes: { type: 'string', description: 'Optional bill notes or remarks.' },
|
|
628
|
+
line_items: {
|
|
629
|
+
type: 'array',
|
|
630
|
+
items: {
|
|
631
|
+
type: 'object',
|
|
632
|
+
properties: {
|
|
633
|
+
item: { type: 'string', description: "Product name, SKU, or ID (e.g. 'Tellzy 40 Tab', 'URISPAS TAB')." },
|
|
634
|
+
qty: { type: 'number', description: 'Quantity to bill (e.g. 5, 10).' },
|
|
635
|
+
price: { type: 'number', description: 'Custom unit selling price.' },
|
|
636
|
+
unit_price: { type: 'number', description: 'Alias for price.' },
|
|
637
|
+
rate: { type: 'number', description: 'Alias for price.' },
|
|
638
|
+
discount_pct: { type: 'number', description: 'Line-level discount %.' },
|
|
639
|
+
tax: { type: 'number', description: 'GST / Tax % for this line.' },
|
|
640
|
+
mrp: { type: 'number', description: 'MRP for this item, optional.' },
|
|
641
|
+
sku: { type: 'string', description: 'Explicit SKU code if provided.' },
|
|
642
|
+
},
|
|
643
|
+
required: ['item', 'qty'],
|
|
644
|
+
},
|
|
645
|
+
description: 'List of items on this bill.',
|
|
646
|
+
},
|
|
647
|
+
},
|
|
648
|
+
required: ['line_items'],
|
|
649
|
+
},
|
|
650
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
651
|
+
const profileId = ctx.profileId;
|
|
652
|
+
const customerName = args.customer_name?.trim() || 'Counter Sale';
|
|
653
|
+
const lineItems = args.line_items || [];
|
|
654
|
+
|
|
655
|
+
// Resolve customer
|
|
656
|
+
let customerId: string;
|
|
657
|
+
const custs = await query<{ id: string }>(
|
|
658
|
+
'SELECT id FROM shop_customers WHERE profile_id = ? AND (LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1',
|
|
659
|
+
[profileId, customerName, `%${customerName}%`]
|
|
660
|
+
);
|
|
661
|
+
if (custs.length > 0) {
|
|
662
|
+
customerId = custs[0].id;
|
|
663
|
+
} else {
|
|
664
|
+
customerId = generateId('cust');
|
|
665
|
+
await execute(
|
|
666
|
+
'INSERT INTO shop_customers (id, profile_id, name, customer_type, is_active) VALUES (?, ?, ?, ?, 1)',
|
|
667
|
+
[customerId, profileId, customerName, 'walk_in']
|
|
668
|
+
);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// Warehouse
|
|
672
|
+
const whs = await query<{ id: string }>('SELECT id FROM shop_warehouses WHERE profile_id = ? LIMIT 1', [profileId]);
|
|
673
|
+
const warehouseId = whs.length > 0 ? whs[0].id : 'default';
|
|
674
|
+
|
|
675
|
+
// Doc number
|
|
676
|
+
const cntRes = await query<{ cnt: number }>(
|
|
677
|
+
"SELECT COUNT(*) as cnt FROM shop_documents WHERE profile_id = ? AND doc_type = 'invoice' AND doc_number LIKE 'SAL-%'",
|
|
678
|
+
[profileId]
|
|
679
|
+
);
|
|
680
|
+
const seq = Number(cntRes[0]?.cnt || 0) + 1;
|
|
681
|
+
const docNumber = `SAL-${String(seq).padStart(4, '0')}`;
|
|
682
|
+
const docId = generateId('doc');
|
|
683
|
+
|
|
684
|
+
let subtotal = 0;
|
|
685
|
+
const billedItems = [];
|
|
686
|
+
|
|
687
|
+
for (const line of lineItems) {
|
|
688
|
+
const itemRef = String(line.item || '').trim();
|
|
689
|
+
const qty = Number(line.qty || 1);
|
|
690
|
+
let rate = Number(line.price ?? line.unit_price ?? line.rate ?? 0);
|
|
691
|
+
const discountPct = Number(line.discount_pct || 0);
|
|
692
|
+
|
|
693
|
+
// Find or create item
|
|
694
|
+
let itemId: string;
|
|
695
|
+
let itemSku: string;
|
|
696
|
+
let itemName = itemRef;
|
|
697
|
+
|
|
698
|
+
const itemsFound = await query<{ id: string; name: string; sku: string; price: number }>(
|
|
699
|
+
'SELECT id, name, sku, price FROM shop_items WHERE profile_id = ? AND (sku = ? OR id = ? OR LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1',
|
|
700
|
+
[profileId, itemRef, itemRef, itemRef, `%${itemRef}%`]
|
|
701
|
+
);
|
|
702
|
+
|
|
703
|
+
if (itemsFound.length > 0) {
|
|
704
|
+
itemId = itemsFound[0].id;
|
|
705
|
+
itemName = itemsFound[0].name;
|
|
706
|
+
itemSku = itemsFound[0].sku;
|
|
707
|
+
if (rate <= 0) {
|
|
708
|
+
rate = itemsFound[0].price || 0;
|
|
709
|
+
}
|
|
710
|
+
} else {
|
|
711
|
+
itemId = generateId('item');
|
|
712
|
+
itemSku = generateSku();
|
|
713
|
+
const slug = `item-${itemName.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
|
|
714
|
+
await execute(
|
|
715
|
+
`INSERT INTO shop_items (id, profile_id, name, sku, slug, price, cost_price, is_active, created_at, updated_at)
|
|
716
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 1, strftime('%s','now'), strftime('%s','now'))`,
|
|
717
|
+
[itemId, profileId, itemName, itemSku, slug, rate, 0]
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const discountedRate = rate * (1 - discountPct / 100);
|
|
722
|
+
const lineTotal = Math.round(discountedRate * qty * 100) / 100;
|
|
723
|
+
subtotal += lineTotal;
|
|
724
|
+
|
|
725
|
+
// Stock deduction
|
|
726
|
+
const ledgerId = generateId('stk');
|
|
727
|
+
await execute(
|
|
728
|
+
`INSERT INTO shop_stock_ledger (id, profile_id, item_id, warehouse_id, movement_type, qty_in, qty_out, unit_cost, reference_type, reference_id, created_at)
|
|
729
|
+
VALUES (?, ?, ?, ?, 'sale', 0, ?, ?, 'invoice', ?, strftime('%s','now'))`,
|
|
730
|
+
[ledgerId, profileId, itemId, warehouseId, qty, rate, docId]
|
|
731
|
+
);
|
|
732
|
+
|
|
733
|
+
// Line item
|
|
734
|
+
const lineId = generateId('line');
|
|
735
|
+
await execute(
|
|
736
|
+
`INSERT INTO shop_document_lines (id, profile_id, document_id, item_id, description, quantity, unit_price, total_amount, created_at)
|
|
737
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, strftime('%s','now'))`,
|
|
738
|
+
[lineId, profileId, docId, itemId, itemName, qty, rate, lineTotal]
|
|
739
|
+
);
|
|
740
|
+
|
|
741
|
+
billedItems.push({ sku: itemSku, name: itemName, qty, unit_price: rate, total: lineTotal });
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
let finalTotal = subtotal;
|
|
745
|
+
if (args.bill_discount_pct) {
|
|
746
|
+
finalTotal = Math.round(subtotal * (1 - Number(args.bill_discount_pct) / 100) * 100) / 100;
|
|
747
|
+
} else if (args.bill_discount_amt) {
|
|
748
|
+
finalTotal = Math.max(0, subtotal - Number(args.bill_discount_amt));
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
await execute(
|
|
752
|
+
`INSERT INTO shop_documents (id, profile_id, doc_type, doc_number, customer_id, warehouse_id, total, status, notes, created_at, updated_at)
|
|
753
|
+
VALUES (?, ?, 'invoice', ?, ?, ?, ?, ?, ?, strftime('%s','now'), strftime('%s','now'))`,
|
|
754
|
+
[docId, profileId, docNumber, customerId, warehouseId, finalTotal, args.payment_status || 'paid', args.notes || '']
|
|
755
|
+
);
|
|
756
|
+
|
|
757
|
+
return {
|
|
758
|
+
success: true,
|
|
759
|
+
doc_id: docId,
|
|
760
|
+
doc_number: docNumber,
|
|
761
|
+
customer_name: customerName,
|
|
762
|
+
payment_status: args.payment_status || 'paid',
|
|
763
|
+
payment_method: args.payment_method || 'cash',
|
|
764
|
+
subtotal,
|
|
765
|
+
final_total: finalTotal,
|
|
766
|
+
items_count: billedItems.length,
|
|
767
|
+
items: billedItems,
|
|
768
|
+
};
|
|
769
|
+
},
|
|
770
|
+
},
|
|
771
|
+
];
|