lampson 0.2.10 → 0.4.0
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/README.md +52 -1
- package/bin/lampson.js +2 -2
- package/chat.syn +40 -24
- package/cli.syn +6 -3
- package/hub.tpl.syn +15 -0
- package/lampson.ps1 +85 -11
- package/lampson.sh +82 -24
- package/lib/api.syn +292 -0
- package/lib/apikeys.syn +115 -0
- package/lib/approvals.syn +7 -0
- package/lib/channels.syn +340 -0
- package/lib/loop.syn +77 -3
- package/lib/mailbox.syn +440 -0
- package/lib/mcp.syn +128 -9
- package/lib/mcp_server.syn +235 -0
- package/lib/plugins.syn +94 -7
- package/lib/runtime.syn +630 -0
- package/lib/scope.syn +62 -0
- package/lib/session.syn +11 -1
- package/lib/teamrun.syn +142 -0
- package/lib/teams.syn +802 -0
- package/lib/tools.syn +1 -1
- package/lib/workspaces.syn +78 -3
- package/lib/worktree.syn +105 -0
- package/package.json +16 -2
- package/plugins/chatwoot/plugin.json +11 -0
- package/plugins/chatwoot/plugin.syn +143 -0
- package/plugins/orders/INSTRUCTIONS.md +16 -0
- package/plugins/orders/plugin.json +81 -0
- package/plugins/orders/plugin.syn +342 -0
- package/plugins/telegram/plugin.json +11 -0
- package/plugins/telegram/plugin.syn +272 -0
- package/public/css/panel.css +2 -0
- package/public/css/teams.css +159 -0
- package/public/index.html +10 -0
- package/public/js/app.js +1 -1
- package/public/js/engine.js +149 -0
- package/public/js/sessions.js +5 -1
- package/public/js/teams.js +301 -0
- package/public/teams.html +75 -0
- package/run.syn +493 -0
- package/sdk/index.d.ts +94 -0
- package/sdk/index.js +250 -0
- package/sdk/index.mjs +4 -0
- package/web.syn +428 -47
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
-- plugins/orders/plugin.syn — tomar pedidos: catálogo, cotización exacta, pedido guardado, clientes, stock
|
|
2
|
+
--
|
|
3
|
+
-- Lampson lo corre por cada llamada con el techo del manifiesto: solo puede tocar workspace/.lampson/orders/.
|
|
4
|
+
-- catalog.json el catálogo (lo escribe el dueño; ver docs/recipes): store, hours, delivery, payment, products, policies
|
|
5
|
+
-- producto: {sku, name, price, unit, stock, notes, pack: {qty, price}, second_half: true}
|
|
6
|
+
-- P-0001.json … un archivo por pedido
|
|
7
|
+
-- customers.json clientes por teléfono (o por nombre si no dio teléfono): nombre, dirección, pedidos
|
|
8
|
+
-- Los precios se calculan SIEMPRE acá desde el catálogo: el modelo nunca suma ni pone precios.
|
|
9
|
+
intent: "lampson plugin: take orders against a catalog — quote, place, customers, stock"
|
|
10
|
+
|
|
11
|
+
require env("PLUGIN_*")
|
|
12
|
+
require time
|
|
13
|
+
require file("workspace/.lampson/orders")
|
|
14
|
+
require file("workspace/.lampson/orders/*")
|
|
15
|
+
|
|
16
|
+
let DIR be "workspace/.lampson/orders"
|
|
17
|
+
let CATALOG be DIR + "/catalog.json"
|
|
18
|
+
let CUSTOMERS be DIR + "/customers.json"
|
|
19
|
+
|
|
20
|
+
task out(v)
|
|
21
|
+
print(json_encode(v))
|
|
22
|
+
|
|
23
|
+
task fail(msg)
|
|
24
|
+
out({"ok": false, "error": msg})
|
|
25
|
+
|
|
26
|
+
task load_catalog()
|
|
27
|
+
when not file_exists(CATALOG)
|
|
28
|
+
raise("no catalog yet: the store owner writes .lampson/orders/catalog.json")
|
|
29
|
+
give json_decode(read_file(CATALOG))
|
|
30
|
+
|
|
31
|
+
task num(m, k, fallback)
|
|
32
|
+
when contains(m, k) and m[k] != nothing
|
|
33
|
+
give number(m[k])
|
|
34
|
+
give fallback
|
|
35
|
+
|
|
36
|
+
task round_money(x)
|
|
37
|
+
give floor(x + 0.5)
|
|
38
|
+
|
|
39
|
+
-- montos enteros como enteros (3200, no 3200.0); con centavos, tal cual
|
|
40
|
+
task money(x)
|
|
41
|
+
let v be number(x)
|
|
42
|
+
give when v == floor(v) then floor(v) otherwise v
|
|
43
|
+
|
|
44
|
+
-- una línea del carrito: precio de lista, pack (p. ej. docena) y "segunda a mitad de precio"
|
|
45
|
+
task price_line(p, qty)
|
|
46
|
+
let unit be money(p["price"])
|
|
47
|
+
let plain be unit * qty
|
|
48
|
+
let amount be plain
|
|
49
|
+
let promo be ""
|
|
50
|
+
when contains(p, "pack") and p["pack"] != nothing
|
|
51
|
+
let n be floor(num(p["pack"], "qty", 0))
|
|
52
|
+
when n > 1 and qty >= n
|
|
53
|
+
let packs be floor(qty / n)
|
|
54
|
+
set amount to packs * money(p["pack"]["price"]) + (qty - packs * n) * unit
|
|
55
|
+
set promo to text(packs) + " x pack of " + text(n)
|
|
56
|
+
when contains(p, "second_half") and p["second_half"] == true and qty >= 2
|
|
57
|
+
let pairs be floor(qty / 2)
|
|
58
|
+
set amount to plain - round_money(pairs * unit / 2)
|
|
59
|
+
set promo to text(pairs) + " x second at half price"
|
|
60
|
+
give {"sku": p["sku"], "name": p["name"], "qty": qty, "unit_price": unit, "list": plain, "discount": plain - amount, "amount": amount, "promo": promo}
|
|
61
|
+
|
|
62
|
+
-- cotiza un carrito: {ok, lines, subtotal, discount, delivery_fee, total, short, unknown}
|
|
63
|
+
task quote_of(cat, items, delivery)
|
|
64
|
+
let by_sku be {}
|
|
65
|
+
each p in cat["products"]
|
|
66
|
+
set by_sku[upper(text(p["sku"]))] to p
|
|
67
|
+
let merged be {}
|
|
68
|
+
let order be []
|
|
69
|
+
each it in items
|
|
70
|
+
let sku be upper(trim(text(it["sku"])))
|
|
71
|
+
let qty be floor(num(it, "qty", 0))
|
|
72
|
+
when qty > 0
|
|
73
|
+
when not contains(merged, sku)
|
|
74
|
+
set merged[sku] to 0
|
|
75
|
+
set order to append(order, sku)
|
|
76
|
+
set merged[sku] to merged[sku] + qty
|
|
77
|
+
let lines be []
|
|
78
|
+
let short be []
|
|
79
|
+
let unknown be []
|
|
80
|
+
let subtotal be 0
|
|
81
|
+
let discount be 0
|
|
82
|
+
each sku in order
|
|
83
|
+
when not contains(by_sku, sku)
|
|
84
|
+
set unknown to append(unknown, sku)
|
|
85
|
+
otherwise
|
|
86
|
+
let p be by_sku[sku]
|
|
87
|
+
let ln be price_line(p, merged[sku])
|
|
88
|
+
set lines to append(lines, ln)
|
|
89
|
+
set subtotal to subtotal + ln["amount"]
|
|
90
|
+
set discount to discount + ln["discount"]
|
|
91
|
+
let stock be floor(num(p, "stock", 0))
|
|
92
|
+
when merged[sku] > stock
|
|
93
|
+
set short to append(short, {"sku": sku, "name": p["name"], "asked": merged[sku], "available": stock, "notes": when contains(p, "notes") then p["notes"] otherwise ""})
|
|
94
|
+
let fee be 0
|
|
95
|
+
let d be when contains(cat, "delivery") and cat["delivery"] != nothing then cat["delivery"] otherwise {}
|
|
96
|
+
when delivery == "delivery"
|
|
97
|
+
set fee to money(num(d, "fee", 0))
|
|
98
|
+
when contains(d, "free_from") and d["free_from"] != nothing and subtotal >= number(d["free_from"])
|
|
99
|
+
set fee to 0
|
|
100
|
+
-- un sku inventado (visto: "pan-sin-gluten-arroz-mijo") → la lista de los válidos, para que el modelo corrija solo
|
|
101
|
+
let hint be when length(unknown) > 0 then apply(cat["products"], (p) => text(p["sku"]) + " = " + text(p["name"])) otherwise []
|
|
102
|
+
give {"valid_skus": hint, "ok": length(short) == 0 and length(unknown) == 0 and length(lines) > 0, "lines": lines, "subtotal": subtotal, "discount": discount, "delivery": delivery, "delivery_fee": fee, "total": subtotal + fee, "short": short, "unknown": unknown, "currency": when contains(cat, "currency") then cat["currency"] otherwise ""}
|
|
103
|
+
|
|
104
|
+
task load_customers()
|
|
105
|
+
when not file_exists(CUSTOMERS)
|
|
106
|
+
give {}
|
|
107
|
+
give json_decode(read_file(CUSTOMERS))
|
|
108
|
+
|
|
109
|
+
task customer_key(c)
|
|
110
|
+
let phone be when contains(c, "phone") and c["phone"] != nothing then replace(replace(replace(trim(text(c["phone"])), " ", ""), "-", ""), "(", "") otherwise ""
|
|
111
|
+
when phone != ""
|
|
112
|
+
give "tel:" + replace(phone, ")", "")
|
|
113
|
+
give "name:" + lower(trim(text(c["name"])))
|
|
114
|
+
|
|
115
|
+
task order_ids()
|
|
116
|
+
give apply(where(list_dir(DIR), (e) => starts_with(e["name"], "P-") and ends_with(e["name"], ".json")), (e) => slice(e["name"], 0, length(e["name"]) - 5))
|
|
117
|
+
|
|
118
|
+
task next_id()
|
|
119
|
+
let n be length(order_ids()) + 1
|
|
120
|
+
let id be ""
|
|
121
|
+
while true
|
|
122
|
+
let digits be text(n)
|
|
123
|
+
each i in range(length(digits), 4)
|
|
124
|
+
set digits to "0" + digits
|
|
125
|
+
set id to "P-" + digits
|
|
126
|
+
when not file_exists(DIR + "/" + id + ".json")
|
|
127
|
+
give id
|
|
128
|
+
set n to n + 1
|
|
129
|
+
|
|
130
|
+
task arg(args, k)
|
|
131
|
+
when contains(args, k) and args[k] != nothing
|
|
132
|
+
give trim(text(args[k]))
|
|
133
|
+
give ""
|
|
134
|
+
|
|
135
|
+
-- ---------- stock y pedidos guardados (update_order / cancel_order) ----------
|
|
136
|
+
task qty_by_sku(lines)
|
|
137
|
+
let m be {}
|
|
138
|
+
each ln in lines
|
|
139
|
+
let k be upper(text(ln["sku"]))
|
|
140
|
+
set m[k] to (when contains(m, k) then m[k] otherwise 0) + floor(number(ln["qty"]))
|
|
141
|
+
give m
|
|
142
|
+
|
|
143
|
+
-- el catálogo con el stock movido: deltas = {sku: unidades que SALEN} (negativo = vuelven)
|
|
144
|
+
task shift_stock(cat, deltas)
|
|
145
|
+
let prods be []
|
|
146
|
+
each p in cat["products"]
|
|
147
|
+
let k be upper(text(p["sku"]))
|
|
148
|
+
when contains(deltas, k)
|
|
149
|
+
set p["stock"] to floor(num(p, "stock", 0)) - deltas[k]
|
|
150
|
+
set prods to append(prods, p)
|
|
151
|
+
set cat["products"] to prods
|
|
152
|
+
give cat
|
|
153
|
+
|
|
154
|
+
task negate(m)
|
|
155
|
+
let out be {}
|
|
156
|
+
each k in keys(m)
|
|
157
|
+
set out[k] to 0 - m[k]
|
|
158
|
+
give out
|
|
159
|
+
|
|
160
|
+
-- lo que cambia entre dos carritos: nuevo - viejo, por sku
|
|
161
|
+
task delta(new_q, old_q)
|
|
162
|
+
let out be {}
|
|
163
|
+
each k in keys(new_q)
|
|
164
|
+
set out[k] to new_q[k] - (when contains(old_q, k) then old_q[k] otherwise 0)
|
|
165
|
+
each k in keys(old_q)
|
|
166
|
+
when not contains(new_q, k)
|
|
167
|
+
set out[k] to 0 - old_q[k]
|
|
168
|
+
give out
|
|
169
|
+
|
|
170
|
+
task quote_problem(q)
|
|
171
|
+
give (when length(q["unknown"]) > 0 then "unknown sku " + join(q["unknown"], ", ") + " " otherwise "") + (when length(q["short"]) > 0 then "not enough stock for " + join(apply(q["short"], (s) => s["name"] + " (asked " + text(s["asked"]) + ", available " + text(s["available"]) + ")"), ", ") otherwise "") + (when length(q["lines"]) == 0 then "empty cart" otherwise "")
|
|
172
|
+
|
|
173
|
+
-- un pedido guardado que todavía se puede tocar: {ok, order} o {ok: false, error}
|
|
174
|
+
task editable(oid)
|
|
175
|
+
when not matches(oid, "P-[0-9]{1,8}") or not file_exists(DIR + "/" + oid + ".json")
|
|
176
|
+
give {"ok": false, "error": "no order " + oid}
|
|
177
|
+
let o be json_decode(read_file(DIR + "/" + oid + ".json"))
|
|
178
|
+
when o["status"] != "new"
|
|
179
|
+
give {"ok": false, "error": "order " + oid + " is '" + text(o["status"]) + "': it can't be changed or cancelled from here anymore — the customer has to talk to the store"}
|
|
180
|
+
give {"ok": true, "order": o}
|
|
181
|
+
|
|
182
|
+
let tool be env("PLUGIN_TOOL", "")
|
|
183
|
+
let args be json_decode(env("PLUGIN_ARGS", "{}"))
|
|
184
|
+
|
|
185
|
+
try
|
|
186
|
+
when tool == "catalog"
|
|
187
|
+
out(load_catalog())
|
|
188
|
+
otherwise when tool == "quote"
|
|
189
|
+
let items be when contains(args, "items") and args["items"] != nothing then args["items"] otherwise []
|
|
190
|
+
out(quote_of(load_catalog(), items, when arg(args, "delivery") == "" then "pickup" otherwise arg(args, "delivery")))
|
|
191
|
+
otherwise when tool == "place_order"
|
|
192
|
+
let cat be load_catalog()
|
|
193
|
+
let items be when contains(args, "items") and args["items"] != nothing then args["items"] otherwise []
|
|
194
|
+
let delivery be arg(args, "delivery")
|
|
195
|
+
let cust be when contains(args, "customer") and args["customer"] != nothing then args["customer"] otherwise {}
|
|
196
|
+
let name be arg(cust, "name")
|
|
197
|
+
let payment be arg(args, "payment")
|
|
198
|
+
let address be arg(args, "address")
|
|
199
|
+
let methods be when contains(cat, "payment") and cat["payment"] != nothing then cat["payment"] otherwise []
|
|
200
|
+
let missing be []
|
|
201
|
+
when length(items) == 0
|
|
202
|
+
set missing to append(missing, "items")
|
|
203
|
+
when name == ""
|
|
204
|
+
set missing to append(missing, "customer.name")
|
|
205
|
+
when delivery != "delivery" and delivery != "pickup"
|
|
206
|
+
set missing to append(missing, "delivery (delivery or pickup)")
|
|
207
|
+
when delivery == "delivery" and address == ""
|
|
208
|
+
set missing to append(missing, "address")
|
|
209
|
+
when payment == ""
|
|
210
|
+
set missing to append(missing, "payment")
|
|
211
|
+
when length(missing) > 0
|
|
212
|
+
fail("missing: " + join(missing, ", ") + " — ask the customer, then place the order")
|
|
213
|
+
otherwise when length(methods) > 0 and length(where(methods, (m) => lower(text(m)) == lower(payment))) == 0
|
|
214
|
+
fail("payment '" + payment + "' is not accepted; accepted: " + join(apply(methods, (m) => text(m)), ", "))
|
|
215
|
+
otherwise
|
|
216
|
+
when length(methods) > 0
|
|
217
|
+
set payment to text(where(methods, (m) => lower(text(m)) == lower(payment))[0])
|
|
218
|
+
let q be quote_of(cat, items, delivery)
|
|
219
|
+
when not q["ok"]
|
|
220
|
+
out({"ok": false, "error": "cannot place it: " + (when length(q["unknown"]) > 0 then "unknown sku " + join(q["unknown"], ", ") + " " otherwise "") + (when length(q["short"]) > 0 then "not enough stock for " + join(apply(q["short"], (s) => s["name"] + " (asked " + text(s["asked"]) + ", available " + text(s["available"]) + ")"), ", ") otherwise "") + (when length(q["lines"]) == 0 then "empty cart" otherwise ""), "quote": q})
|
|
221
|
+
otherwise
|
|
222
|
+
let id be next_id()
|
|
223
|
+
let ckey be customer_key(cust)
|
|
224
|
+
let d be when contains(cat, "delivery") and cat["delivery"] != nothing then cat["delivery"] otherwise {}
|
|
225
|
+
let order be {"id": id, "created": format_time(now(), "%Y-%m-%d %H:%M"), "status": "new", "customer": {"name": name, "phone": arg(cust, "phone"), "key": ckey}, "lines": q["lines"], "subtotal": q["subtotal"], "discount": q["discount"], "delivery": delivery, "address": address, "delivery_fee": q["delivery_fee"], "total": q["total"], "payment": payment, "when": arg(args, "when"), "notes": arg(args, "notes")}
|
|
226
|
+
write_file(DIR + "/" + id + ".json", json_encode(order))
|
|
227
|
+
-- stock: baja lo vendido en el catálogo
|
|
228
|
+
let sold be {}
|
|
229
|
+
each ln in q["lines"]
|
|
230
|
+
set sold[upper(text(ln["sku"]))] to ln["qty"]
|
|
231
|
+
let prods be []
|
|
232
|
+
each p in cat["products"]
|
|
233
|
+
let k be upper(text(p["sku"]))
|
|
234
|
+
when contains(sold, k)
|
|
235
|
+
set p["stock"] to floor(num(p, "stock", 0)) - sold[k]
|
|
236
|
+
set prods to append(prods, p)
|
|
237
|
+
set cat["products"] to prods
|
|
238
|
+
write_file(CATALOG, json_encode(cat))
|
|
239
|
+
-- cliente: nombre, teléfono, última dirección, sus pedidos
|
|
240
|
+
let cs be load_customers()
|
|
241
|
+
let prev be when contains(cs, ckey) then cs[ckey] otherwise {"orders": []}
|
|
242
|
+
set cs[ckey] to {"name": name, "phone": arg(cust, "phone"), "address": when address != "" then address otherwise (when contains(prev, "address") then prev["address"] otherwise ""), "orders": append(prev["orders"], id), "last": order["created"]}
|
|
243
|
+
write_file(CUSTOMERS, json_encode(cs))
|
|
244
|
+
out({"ok": true, "order_id": id, "total": q["total"], "subtotal": q["subtotal"], "discount": q["discount"], "delivery_fee": q["delivery_fee"], "delivery": delivery, "address": address, "payment": payment, "eta": when delivery == "delivery" and contains(d, "eta") then d["eta"] otherwise "", "lines": q["lines"]})
|
|
245
|
+
otherwise when tool == "update_order"
|
|
246
|
+
let ed be editable(upper(arg(args, "order_id")))
|
|
247
|
+
when not ed["ok"]
|
|
248
|
+
fail(ed["error"])
|
|
249
|
+
otherwise
|
|
250
|
+
let o be ed["order"]
|
|
251
|
+
let cat be load_catalog()
|
|
252
|
+
let old be qty_by_sku(o["lines"])
|
|
253
|
+
-- sin "items" el carrito queda como estaba (cambia solo la entrega, el pago, la hora o las notas)
|
|
254
|
+
let items be when contains(args, "items") and args["items"] != nothing then args["items"] otherwise apply(o["lines"], (l) => {"sku": l["sku"], "qty": l["qty"]})
|
|
255
|
+
let delivery be when arg(args, "delivery") != "" then arg(args, "delivery") otherwise o["delivery"]
|
|
256
|
+
let address be when arg(args, "address") != "" then arg(args, "address") otherwise o["address"]
|
|
257
|
+
let payment be when arg(args, "payment") != "" then arg(args, "payment") otherwise o["payment"]
|
|
258
|
+
let methods be when contains(cat, "payment") and cat["payment"] != nothing then cat["payment"] otherwise []
|
|
259
|
+
when delivery != "delivery" and delivery != "pickup"
|
|
260
|
+
fail("delivery must be delivery or pickup")
|
|
261
|
+
otherwise when delivery == "delivery" and address == ""
|
|
262
|
+
fail("missing: address — ask the customer, then update the order")
|
|
263
|
+
otherwise when length(methods) > 0 and length(where(methods, (m) => lower(text(m)) == lower(payment))) == 0
|
|
264
|
+
fail("payment '" + payment + "' is not accepted; accepted: " + join(apply(methods, (m) => text(m)), ", "))
|
|
265
|
+
otherwise
|
|
266
|
+
when length(methods) > 0
|
|
267
|
+
set payment to text(where(methods, (m) => lower(text(m)) == lower(payment))[0])
|
|
268
|
+
-- lo que este pedido ya tiene reservado cuenta como disponible para él
|
|
269
|
+
let q be quote_of(shift_stock(cat, negate(old)), items, delivery)
|
|
270
|
+
when not q["ok"]
|
|
271
|
+
out({"ok": false, "error": "cannot update it: " + quote_problem(q), "quote": q})
|
|
272
|
+
otherwise
|
|
273
|
+
write_file(CATALOG, json_encode(shift_stock(cat, delta(qty_by_sku(q["lines"]), old))))
|
|
274
|
+
let before be o["total"]
|
|
275
|
+
let stamp be format_time(now(), "%Y-%m-%d %H:%M")
|
|
276
|
+
let hist be when contains(o, "history") and o["history"] != nothing then o["history"] otherwise []
|
|
277
|
+
set o["history"] to append(hist, {"at": stamp, "change": "updated", "total_before": before})
|
|
278
|
+
set o["lines"] to q["lines"]
|
|
279
|
+
set o["subtotal"] to q["subtotal"]
|
|
280
|
+
set o["discount"] to q["discount"]
|
|
281
|
+
set o["delivery"] to delivery
|
|
282
|
+
set o["address"] to address
|
|
283
|
+
set o["delivery_fee"] to q["delivery_fee"]
|
|
284
|
+
set o["total"] to q["total"]
|
|
285
|
+
set o["payment"] to payment
|
|
286
|
+
set o["updated"] to stamp
|
|
287
|
+
when contains(args, "when") and args["when"] != nothing
|
|
288
|
+
set o["when"] to arg(args, "when")
|
|
289
|
+
when contains(args, "notes") and args["notes"] != nothing
|
|
290
|
+
set o["notes"] to arg(args, "notes")
|
|
291
|
+
write_file(DIR + "/" + o["id"] + ".json", json_encode(o))
|
|
292
|
+
when address != "" and contains(o["customer"], "key")
|
|
293
|
+
let cs be load_customers()
|
|
294
|
+
when contains(cs, o["customer"]["key"])
|
|
295
|
+
let c be cs[o["customer"]["key"]]
|
|
296
|
+
set c["address"] to address
|
|
297
|
+
set cs[o["customer"]["key"]] to c
|
|
298
|
+
write_file(CUSTOMERS, json_encode(cs))
|
|
299
|
+
let d be when contains(cat, "delivery") and cat["delivery"] != nothing then cat["delivery"] otherwise {}
|
|
300
|
+
out({"ok": true, "order_id": o["id"], "total": q["total"], "total_before": before, "subtotal": q["subtotal"], "discount": q["discount"], "delivery_fee": q["delivery_fee"], "delivery": delivery, "address": address, "payment": payment, "when": o["when"], "eta": when delivery == "delivery" and contains(d, "eta") then d["eta"] otherwise "", "lines": q["lines"]})
|
|
301
|
+
otherwise when tool == "cancel_order"
|
|
302
|
+
let ed be editable(upper(arg(args, "order_id")))
|
|
303
|
+
when not ed["ok"]
|
|
304
|
+
fail(ed["error"])
|
|
305
|
+
otherwise
|
|
306
|
+
let o be ed["order"]
|
|
307
|
+
-- el stock vuelve al catálogo
|
|
308
|
+
write_file(CATALOG, json_encode(shift_stock(load_catalog(), negate(qty_by_sku(o["lines"])))))
|
|
309
|
+
let stamp be format_time(now(), "%Y-%m-%d %H:%M")
|
|
310
|
+
let hist be when contains(o, "history") and o["history"] != nothing then o["history"] otherwise []
|
|
311
|
+
set o["history"] to append(hist, {"at": stamp, "change": "cancelled", "reason": arg(args, "reason")})
|
|
312
|
+
set o["status"] to "cancelled"
|
|
313
|
+
set o["cancelled"] to stamp
|
|
314
|
+
write_file(DIR + "/" + o["id"] + ".json", json_encode(o))
|
|
315
|
+
out({"ok": true, "order_id": o["id"], "status": "cancelled", "total_was": o["total"]})
|
|
316
|
+
otherwise when tool == "find_customer"
|
|
317
|
+
let cs be load_customers()
|
|
318
|
+
let key be ""
|
|
319
|
+
when arg(args, "phone") != ""
|
|
320
|
+
set key to customer_key({"phone": arg(args, "phone"), "name": ""})
|
|
321
|
+
otherwise when arg(args, "name") != ""
|
|
322
|
+
set key to customer_key({"name": arg(args, "name")})
|
|
323
|
+
when key == "" or not contains(cs, key)
|
|
324
|
+
out({"found": false})
|
|
325
|
+
otherwise
|
|
326
|
+
let c be cs[key]
|
|
327
|
+
let recent be []
|
|
328
|
+
each oid in slice(c["orders"], max(0, length(c["orders"]) - 3), length(c["orders"]))
|
|
329
|
+
when file_exists(DIR + "/" + oid + ".json")
|
|
330
|
+
let o be json_decode(read_file(DIR + "/" + oid + ".json"))
|
|
331
|
+
set recent to append(recent, {"id": oid, "created": o["created"], "total": o["total"], "status": o["status"], "items": apply(o["lines"], (l) => {"sku": l["sku"], "qty": l["qty"], "name": l["name"]}), "delivery": o["delivery"], "payment": o["payment"]})
|
|
332
|
+
out({"found": true, "name": c["name"], "phone": c["phone"], "address": c["address"], "orders": recent})
|
|
333
|
+
otherwise when tool == "order_status"
|
|
334
|
+
let oid be upper(arg(args, "order_id"))
|
|
335
|
+
when not matches(oid, "P-[0-9]{1,8}") or not file_exists(DIR + "/" + oid + ".json")
|
|
336
|
+
fail("no order " + oid)
|
|
337
|
+
otherwise
|
|
338
|
+
out(json_decode(read_file(DIR + "/" + oid + ".json")))
|
|
339
|
+
otherwise
|
|
340
|
+
fail("unknown tool '" + tool + "'")
|
|
341
|
+
recover err
|
|
342
|
+
fail(text(err))
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "telegram",
|
|
3
|
+
"description": "Channel: a Telegram bot answered by a Lampson agent. Free, no middleman: create the bot with @BotFather, put its token in .env, then `lampson channel setup telegram`.",
|
|
4
|
+
"kind": "syn",
|
|
5
|
+
"entry": "plugin.syn",
|
|
6
|
+
"caps": "net",
|
|
7
|
+
"timeout": 30,
|
|
8
|
+
"config": ["TELEGRAM_TOKEN", "TELEGRAM_WEBHOOK_SECRET", "TELEGRAM_API"],
|
|
9
|
+
"channel": {"agent": "", "typing": true, "poll": true},
|
|
10
|
+
"tools": []
|
|
11
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
-- plugins/telegram/plugin.syn — canal Telegram (contrato en lib/channels.syn)
|
|
2
|
+
--
|
|
3
|
+
-- Un bot de Telegram contestado por un agente de Lampson. Gratis y sin intermediarios. Lampson lo corre con techo:
|
|
4
|
+
-- stdout, time, env=PLUGIN_*, net.
|
|
5
|
+
--
|
|
6
|
+
-- setup registra el webhook en Telegram (setWebhook) con la URL que le pasa `lampson channel setup telegram`
|
|
7
|
+
-- y el secreto de LAMPSON_TELEGRAM_WEBHOOK_SECRET; muestra el @usuario del bot (getMe).
|
|
8
|
+
-- receive un Update de Telegram. Si hay secreto, exige X-Telegram-Bot-Api-Secret-Token (Telegram lo manda en cada
|
|
9
|
+
-- webhook). Pasa los mensajes nuevos de personas: ignora ediciones, posts de canales y mensajes de otros
|
|
10
|
+
-- bots. Una FOTO llega como imagen (la versión más grande hasta 1 MB, descargada con getFile; el caption es
|
|
11
|
+
-- el texto); audio/documento/ubicación como una nota en el texto. Avisa "escribiendo…" apenas llega.
|
|
12
|
+
-- typing sendChatAction "typing" (Lampson la renueva mientras el agente trabaja: en Telegram dura ~5 s).
|
|
13
|
+
-- poll SIN URL PÚBLICA: getUpdates con espera larga (LAMPSON_TELEGRAM_POLL_WAIT s, 20 por defecto) desde el
|
|
14
|
+
-- cursor; devuelve los mensajes convertidos igual que receive y el próximo offset.
|
|
15
|
+
-- send sendMessage al chat, en partes de hasta 4000 caracteres (Telegram corta en 4096), texto plano (sin parse
|
|
16
|
+
-- mode: un markdown mal formado haría fallar el envío; se quitan los ** del modelo).
|
|
17
|
+
--
|
|
18
|
+
-- Config (en el .env de Lampson): LAMPSON_TELEGRAM_TOKEN=<token de @BotFather>,
|
|
19
|
+
-- LAMPSON_TELEGRAM_WEBHOOK_SECRET=<cualquier texto largo: letras, números, _ y ->, LAMPSON_CHANNEL_TELEGRAM_AGENT=<el
|
|
20
|
+
-- agente que atiende>. LAMPSON_TELEGRAM_API = otra base (un Bot API server propio, o los tests); por defecto la oficial.
|
|
21
|
+
intent: "lampson channel plugin: Telegram bot ↔ Lampson agent"
|
|
22
|
+
|
|
23
|
+
require env("PLUGIN_*")
|
|
24
|
+
require net
|
|
25
|
+
require time
|
|
26
|
+
|
|
27
|
+
let action be env("PLUGIN_TOOL", "")
|
|
28
|
+
let args be json_decode(env("PLUGIN_ARGS", "{}"))
|
|
29
|
+
|
|
30
|
+
task field(m, k, fallback)
|
|
31
|
+
when m != nothing and type_of(m) == "map" and contains(m, k) and m[k] != nothing
|
|
32
|
+
give m[k]
|
|
33
|
+
give fallback
|
|
34
|
+
|
|
35
|
+
task header(h, name)
|
|
36
|
+
each k in keys(h)
|
|
37
|
+
when lower(k) == name
|
|
38
|
+
give text(h[k])
|
|
39
|
+
give ""
|
|
40
|
+
|
|
41
|
+
task api(method)
|
|
42
|
+
let base be env("PLUGIN_TELEGRAM_API", "")
|
|
43
|
+
when base == ""
|
|
44
|
+
set base to "https://api.telegram.org"
|
|
45
|
+
while ends_with(base, "/")
|
|
46
|
+
set base to slice(base, 0, length(base) - 1)
|
|
47
|
+
give base + "/bot" + env("PLUGIN_TELEGRAM_TOKEN", "") + "/" + method
|
|
48
|
+
|
|
49
|
+
task tg(method, body)
|
|
50
|
+
let r be http_post(api(method), json_encode(body), {"Content-Type": "application/json"}, 20)
|
|
51
|
+
let d be {}
|
|
52
|
+
try
|
|
53
|
+
set d to json_decode(text(field(r, "body", "{}")))
|
|
54
|
+
recover err
|
|
55
|
+
set d to {}
|
|
56
|
+
give {"ok": r["ok"] and field(d, "ok", false) == true, "status": r["status"], "data": d}
|
|
57
|
+
|
|
58
|
+
task out(m)
|
|
59
|
+
print(json_encode(m))
|
|
60
|
+
|
|
61
|
+
task ignore(why)
|
|
62
|
+
out({"messages": [], "ignored": why})
|
|
63
|
+
|
|
64
|
+
task need_token()
|
|
65
|
+
when env("PLUGIN_TELEGRAM_TOKEN", "") == ""
|
|
66
|
+
print("ERROR: set LAMPSON_TELEGRAM_TOKEN in Lampson's .env (the token @BotFather gave you)")
|
|
67
|
+
give false
|
|
68
|
+
give true
|
|
69
|
+
|
|
70
|
+
task setup()
|
|
71
|
+
when not need_token()
|
|
72
|
+
give false
|
|
73
|
+
when text(field(args, "mode", "webhook")) == "poll"
|
|
74
|
+
-- getUpdates no funciona con un webhook registrado: se quita (los mensajes pendientes quedan)
|
|
75
|
+
let me0 be tg("getMe", {})
|
|
76
|
+
let dw be tg("deleteWebhook", {"drop_pending_updates": false})
|
|
77
|
+
when not dw["ok"]
|
|
78
|
+
print("ERROR: deleteWebhook failed (" + text(dw["status"]) + "): " + text(field(dw["data"], "description", "")))
|
|
79
|
+
give false
|
|
80
|
+
print("polling mode: " + (when me0["ok"] then "@" + text(field(field(me0["data"], "result", {}), "username", "?")) otherwise "your bot") + " — Lampson asks Telegram for new messages (no public URL needed)")
|
|
81
|
+
give true
|
|
82
|
+
let url be text(field(args, "webhook_url", ""))
|
|
83
|
+
when not starts_with(url, "https://")
|
|
84
|
+
print("ERROR: Telegram only sends webhooks to an https:// URL (got '" + url + "')")
|
|
85
|
+
give false
|
|
86
|
+
let body be {"url": url, "allowed_updates": ["message"]}
|
|
87
|
+
let sec be env("PLUGIN_TELEGRAM_WEBHOOK_SECRET", "")
|
|
88
|
+
when sec != ""
|
|
89
|
+
set body["secret_token"] to sec
|
|
90
|
+
let me be tg("getMe", {})
|
|
91
|
+
let r be tg("setWebhook", body)
|
|
92
|
+
when not r["ok"]
|
|
93
|
+
print("ERROR: setWebhook failed (" + text(r["status"]) + "): " + text(field(r["data"], "description", "")))
|
|
94
|
+
give false
|
|
95
|
+
let who be when me["ok"] then "@" + text(field(field(me["data"], "result", {}), "username", "?")) otherwise "your bot"
|
|
96
|
+
print("webhook registered: " + who + " → " + url + (when sec == "" then " (no secret: set LAMPSON_TELEGRAM_WEBHOOK_SECRET and run setup again so only Telegram can post here)" otherwise " (with secret token)"))
|
|
97
|
+
give true
|
|
98
|
+
|
|
99
|
+
-- la foto como imagen para el modelo: la versión más grande que entre en 1 MB (Telegram manda varias resoluciones)
|
|
100
|
+
task photo_image(sizes)
|
|
101
|
+
let best be nothing
|
|
102
|
+
each s in sizes
|
|
103
|
+
let sz be field(s, "file_size", 0)
|
|
104
|
+
when sz <= 1000000 and (best == nothing or sz > field(best, "file_size", 0))
|
|
105
|
+
set best to s
|
|
106
|
+
when best == nothing or env("PLUGIN_TELEGRAM_TOKEN", "") == ""
|
|
107
|
+
give nothing
|
|
108
|
+
try
|
|
109
|
+
let f be tg("getFile", {"file_id": field(best, "file_id", "")})
|
|
110
|
+
let fp be text(field(field(f["data"], "result", {}), "file_path", ""))
|
|
111
|
+
when not f["ok"] or fp == ""
|
|
112
|
+
give nothing
|
|
113
|
+
let base be api("getMe")
|
|
114
|
+
set base to slice(base, 0, length(base) - length("/bot" + env("PLUGIN_TELEGRAM_TOKEN", "") + "/getMe"))
|
|
115
|
+
let r be http_bytes("GET", base + "/file/bot" + env("PLUGIN_TELEGRAM_TOKEN", "") + "/" + fp, {}, nothing, nothing, 20)
|
|
116
|
+
when not r["ok"] or length(r["bytes"]) == 0 or length(r["bytes"]) > 1500000
|
|
117
|
+
give nothing
|
|
118
|
+
let mt be when ends_with(lower(fp), ".png") then "image/png" otherwise (when ends_with(lower(fp), ".webp") then "image/webp" otherwise "image/jpeg")
|
|
119
|
+
give {"media_type": mt, "data": decode(r["bytes"], "base64")}
|
|
120
|
+
recover err
|
|
121
|
+
give nothing
|
|
122
|
+
|
|
123
|
+
task typing()
|
|
124
|
+
let meta be field(args, "meta", {})
|
|
125
|
+
let chat_id be field(meta, "chat_id", field(args, "thread", nothing))
|
|
126
|
+
when env("PLUGIN_TELEGRAM_TOKEN", "") == "" or chat_id == nothing
|
|
127
|
+
give false
|
|
128
|
+
tg("sendChatAction", {"chat_id": chat_id, "action": "typing"})
|
|
129
|
+
print("typing")
|
|
130
|
+
give true
|
|
131
|
+
|
|
132
|
+
-- un Update → el mensaje en el formato de Lampson, o nothing (lo comparten receive y poll)
|
|
133
|
+
task convert(up)
|
|
134
|
+
let m be field(up, "message", nothing)
|
|
135
|
+
when m == nothing
|
|
136
|
+
give nothing
|
|
137
|
+
let who be field(m, "from", {})
|
|
138
|
+
when field(who, "is_bot", false) == true
|
|
139
|
+
give nothing
|
|
140
|
+
let content be text(field(m, "text", field(m, "caption", "")))
|
|
141
|
+
let notes be []
|
|
142
|
+
let images be []
|
|
143
|
+
when contains(m, "photo")
|
|
144
|
+
let img be photo_image(field(m, "photo", []))
|
|
145
|
+
when img != nothing
|
|
146
|
+
set images to append(images, img)
|
|
147
|
+
otherwise
|
|
148
|
+
set notes to append(notes, "[the user sent a photo that could not be loaded]")
|
|
149
|
+
when contains(m, "voice") or contains(m, "audio")
|
|
150
|
+
set notes to append(notes, "[the user sent an audio message]")
|
|
151
|
+
when contains(m, "document")
|
|
152
|
+
set notes to append(notes, "[the user sent a file: " + text(field(field(m, "document", {}), "file_name", "")) + "]")
|
|
153
|
+
when contains(m, "location")
|
|
154
|
+
set notes to append(notes, "[the user shared a location]")
|
|
155
|
+
when length(notes) > 0
|
|
156
|
+
set content to trim(content + "\n" + join(notes, "\n"))
|
|
157
|
+
when trim(content) == "" and length(images) > 0
|
|
158
|
+
set content to "[photo]"
|
|
159
|
+
let chat be field(m, "chat", {})
|
|
160
|
+
let chat_id be field(chat, "id", nothing)
|
|
161
|
+
when trim(content) == "" or chat_id == nothing
|
|
162
|
+
give nothing
|
|
163
|
+
let name be trim(text(field(who, "first_name", "")) + " " + text(field(who, "last_name", "")))
|
|
164
|
+
give {"thread": text(chat_id), "text": content, "sent_at": field(m, "date", nothing), "from": {"id": text(field(who, "id", "")), "name": name, "username": text(field(who, "username", "")), "kind": "human"}, "images": images, "meta": {"chat_id": chat_id, "message_id": field(m, "message_id", nothing), "chat_type": text(field(chat, "type", ""))}}
|
|
165
|
+
|
|
166
|
+
task poll()
|
|
167
|
+
when not need_token()
|
|
168
|
+
give false
|
|
169
|
+
let wait be 20
|
|
170
|
+
try
|
|
171
|
+
set wait to int(env("PLUGIN_TELEGRAM_POLL_WAIT", "20"))
|
|
172
|
+
recover err
|
|
173
|
+
set wait to 20
|
|
174
|
+
let body be {"timeout": wait, "allowed_updates": ["message"]}
|
|
175
|
+
let cur be field(args, "cursor", nothing)
|
|
176
|
+
when cur != nothing
|
|
177
|
+
set body["offset"] to cur
|
|
178
|
+
let r be http_post(api("getUpdates"), json_encode(body), {"Content-Type": "application/json"}, wait + 10)
|
|
179
|
+
let d be {}
|
|
180
|
+
try
|
|
181
|
+
set d to json_decode(text(field(r, "body", "{}")))
|
|
182
|
+
recover err
|
|
183
|
+
set d to {}
|
|
184
|
+
when not r["ok"] or field(d, "ok", false) != true
|
|
185
|
+
print("ERROR: getUpdates failed (" + text(r["status"]) + "): " + text(field(d, "description", "")))
|
|
186
|
+
give false
|
|
187
|
+
let msgs be []
|
|
188
|
+
let next be cur
|
|
189
|
+
each up in field(d, "result", [])
|
|
190
|
+
set next to field(up, "update_id", 0) + 1
|
|
191
|
+
let m be convert(up)
|
|
192
|
+
when m != nothing
|
|
193
|
+
try
|
|
194
|
+
tg("sendChatAction", {"chat_id": m["meta"]["chat_id"], "action": "typing"})
|
|
195
|
+
recover err
|
|
196
|
+
set next to next
|
|
197
|
+
set msgs to append(msgs, m)
|
|
198
|
+
out({"messages": msgs, "cursor": next})
|
|
199
|
+
give true
|
|
200
|
+
|
|
201
|
+
task receive()
|
|
202
|
+
let h be field(args, "headers", {})
|
|
203
|
+
let sec be env("PLUGIN_TELEGRAM_WEBHOOK_SECRET", "")
|
|
204
|
+
when sec != "" and header(h, "x-telegram-bot-api-secret-token") != sec
|
|
205
|
+
out({"messages": [], "http": {"status": 401, "body": "invalid secret token"}})
|
|
206
|
+
give false
|
|
207
|
+
let up be nothing
|
|
208
|
+
try
|
|
209
|
+
set up to json_decode(text(field(args, "body", "")))
|
|
210
|
+
recover err
|
|
211
|
+
ignore("body is not JSON")
|
|
212
|
+
give false
|
|
213
|
+
-- solo mensajes nuevos de personas (convert): una edición contestada otra vez sería una respuesta duplicada
|
|
214
|
+
let msg be convert(up)
|
|
215
|
+
when msg == nothing
|
|
216
|
+
ignore("not a new message from a person (edit, channel post, bot, or empty)")
|
|
217
|
+
give false
|
|
218
|
+
-- "escribiendo…" mientras el agente trabaja (dura ~5 s en Telegram; si falla no importa)
|
|
219
|
+
when env("PLUGIN_TELEGRAM_TOKEN", "") != ""
|
|
220
|
+
try
|
|
221
|
+
tg("sendChatAction", {"chat_id": msg["meta"]["chat_id"], "action": "typing"})
|
|
222
|
+
recover err
|
|
223
|
+
set msg to msg
|
|
224
|
+
out({"messages": [msg]})
|
|
225
|
+
give true
|
|
226
|
+
|
|
227
|
+
-- partes de hasta `max` caracteres, cortando en un salto de línea si hay uno cerca
|
|
228
|
+
task chunks(t, max)
|
|
229
|
+
let parts be []
|
|
230
|
+
let rest be t
|
|
231
|
+
while length(rest) > max
|
|
232
|
+
let cut be max
|
|
233
|
+
let head be slice(rest, 0, max)
|
|
234
|
+
let nl be split(head, "\n")
|
|
235
|
+
when length(nl) > 1
|
|
236
|
+
let last_len be length(nl[length(nl) - 1])
|
|
237
|
+
when max - last_len > max / 2
|
|
238
|
+
set cut to max - last_len
|
|
239
|
+
set parts to append(parts, trim(slice(rest, 0, cut)))
|
|
240
|
+
set rest to slice(rest, cut, length(rest))
|
|
241
|
+
when trim(rest) != ""
|
|
242
|
+
set parts to append(parts, trim(rest))
|
|
243
|
+
give parts
|
|
244
|
+
|
|
245
|
+
task send()
|
|
246
|
+
when not need_token()
|
|
247
|
+
give false
|
|
248
|
+
let meta be field(args, "meta", {})
|
|
249
|
+
let chat_id be field(meta, "chat_id", field(args, "thread", nothing))
|
|
250
|
+
let t be replace(text(field(args, "text", "")), "**", "")
|
|
251
|
+
let n be 0
|
|
252
|
+
each part in chunks(t, 4000)
|
|
253
|
+
let r be tg("sendMessage", {"chat_id": chat_id, "text": part})
|
|
254
|
+
when not r["ok"]
|
|
255
|
+
print("ERROR: sendMessage failed (" + text(r["status"]) + "): " + text(field(r["data"], "description", "")))
|
|
256
|
+
give false
|
|
257
|
+
set n to n + 1
|
|
258
|
+
print("sent " + text(n) + " message(s) to chat " + text(chat_id))
|
|
259
|
+
give true
|
|
260
|
+
|
|
261
|
+
when action == "setup"
|
|
262
|
+
setup()
|
|
263
|
+
otherwise when action == "poll"
|
|
264
|
+
poll()
|
|
265
|
+
otherwise when action == "typing"
|
|
266
|
+
typing()
|
|
267
|
+
otherwise when action == "receive"
|
|
268
|
+
receive()
|
|
269
|
+
otherwise when action == "send"
|
|
270
|
+
send()
|
|
271
|
+
otherwise
|
|
272
|
+
print("ERROR: unknown action '" + action + "'")
|
package/public/css/panel.css
CHANGED
|
@@ -165,6 +165,8 @@
|
|
|
165
165
|
.panel .cu-cmd { margin:8px 0; padding:8px 10px; border:1px dashed var(--rule); border-radius:var(--r); font:12px/1.5 var(--mono); color:var(--ink); white-space:pre-wrap; user-select:all; }
|
|
166
166
|
.panel .dform label .chk { display:flex; align-items:center; gap:8px; font:400 13px/1.4 var(--serif); text-transform:none; letter-spacing:0; color:var(--ink); }
|
|
167
167
|
.panel .dform label .chk input { width:16px; height:16px; margin:0; accent-color:var(--accent); }
|
|
168
|
+
.panel .dform .lf .chk { display:inline-flex; align-items:center; gap:6px; margin:2px 14px 2px 0; font:400 13px/1.4 var(--serif); text-transform:none; letter-spacing:0; color:var(--ink); cursor:pointer; }
|
|
169
|
+
.panel .dform .lf .chk input { width:16px; height:16px; margin:0; accent-color:var(--accent); }
|
|
168
170
|
/* interruptor visible (computer use): pill con perilla; el texto al lado dice el estado */
|
|
169
171
|
.panel label.toggle { position:relative; display:inline-flex; align-items:center; gap:10px; margin:0 0 0 auto; cursor:pointer; user-select:none; font:500 12.5px/1 var(--mono); text-transform:none; letter-spacing:0; color:var(--ink-3); }
|
|
170
172
|
.panel .dform .trow label.toggle { margin:0; font:500 13px/1.3 var(--serif); color:var(--ink); }
|