fix(orders): ensure correct unit price and subtotal calculation on whatsapp orders

This commit is contained in:
AI Bot 2026-10-10 13:14:05 -05:00
parent 610c1024e0
commit 9b5f1205a6
2 changed files with 142 additions and 11 deletions

View File

@ -290,20 +290,30 @@ export async function detectAndProcessWhatsAppOrder(
if (orderItems.length === 0) {
const orderTitle = orderMessage.orderTitle || 'Pedido Catálogo WhatsApp';
const matched = matchProductInCatalog(orderTitle, allProducts);
let price = orderMessage.totalAmount1000
let totalCartPrice = orderMessage.totalAmount1000
? (orderMessage.totalAmount1000 > 1000000 ? Math.round(orderMessage.totalAmount1000 / 1000) : orderMessage.totalAmount1000)
: (matched?.retailPrice || 135000);
if (price < 10000) price = 135000;
calculatedSubtotal = price;
let qty = orderMessage.itemCount || 1;
// unit price is total / qty
let unitPrice = Math.round(totalCartPrice / qty);
if (unitPrice < 10000) {
unitPrice = 135000;
totalCartPrice = unitPrice * qty;
}
calculatedSubtotal = totalCartPrice;
orderItems.push({
productId: matched?.id || `snk-cat-${Date.now()}`,
productName: matched?.name || orderTitle,
brand: matched?.brand || 'Sneakers',
size: 'Por confirmar',
quantity: orderMessage.itemCount || 1,
price,
supplierPrice: matched?.supplierPrice || Math.round(price * 0.7),
quantity: qty,
price: unitPrice,
supplierPrice: matched?.supplierPrice || Math.round(unitPrice * 0.7),
supplierName: matched?.supplierName || 'DIFUSIÓN JOVIC STORE',
supplierPhone: matched?.supplierPhone || '573167455877',
image: matched?.images?.[0] || 'https://images.unsplash.com/photo-1595950653106-6c9ebd614d3a?auto=format&fit=crop&w=800&q=80',
@ -398,7 +408,7 @@ export async function detectAndProcessWhatsAppOrder(
`━━━━━━━━━━━━━━━━━━━━━━`
);
await sendWhatsAppMessage(customerPhone, clientReply, 'DripZone', '83B5BD230796-4324-AE73-3508F69E279D').catch(() => {});
await sendWhatsAppMessage(customerPhone, clientReply, 'DripZone', '83B5BD230796-4324-AE73-3508F69E279D').catch(() => { });
return { handled: true, order: savedOrder };
}
@ -426,7 +436,7 @@ export async function detectAndProcessWhatsAppOrder(
try {
const allOrders = await getOrdersFromAppwrite();
existing = allOrders.find((o: any) => o.id === existingOrderId);
} catch (_) {}
} catch (_) { }
}
if (existing) {
console.log(`ℹ️ [WhatsApp Order Parser] La orden #${existingOrderId} ya existe en la base de datos.`);
@ -453,7 +463,7 @@ export async function detectAndProcessWhatsAppOrder(
`👉 https://drip-zone.online/mis-pedidos?phone=${customerPhone}\n` +
`━━━━━━━━━━━━━━━━━━━━━━`
);
await sendWhatsAppMessage(customerPhone, confirmText, 'DripZone', '83B5BD230796-4324-AE73-3508F69E279D').catch(() => {});
await sendWhatsAppMessage(customerPhone, confirmText, 'DripZone', '83B5BD230796-4324-AE73-3508F69E279D').catch(() => { });
return { handled: true, order: existing, reason: 'Orden ya existente confirmada vía WhatsApp' };
}
}
@ -624,7 +634,7 @@ export async function detectAndProcessWhatsAppOrder(
`━━━━━━━━━━━━━━━━━━━━━━`
);
await sendWhatsAppMessage(parsedPhone, confirmationMsg, 'DripZone', '83B5BD230796-4324-AE73-3508F69E279D').catch(() => {});
await sendWhatsAppMessage(parsedPhone, confirmationMsg, 'DripZone', '83B5BD230796-4324-AE73-3508F69E279D').catch(() => { });
return { handled: true, order: savedOrder };
}
@ -739,7 +749,7 @@ export async function detectAndProcessWhatsAppOrder(
`━━━━━━━━━━━━━━━━━━━━━━`
);
await sendWhatsAppMessage(customerPhone, confirmText, 'DripZone', '83B5BD230796-4324-AE73-3508F69E279D').catch(() => {});
await sendWhatsAppMessage(customerPhone, confirmText, 'DripZone', '83B5BD230796-4324-AE73-3508F69E279D').catch(() => { });
return { handled: true, order: savedOrder };
}

121
scripts/send_apk_direct.py Normal file
View File

@ -0,0 +1,121 @@
import paramiko
import os
import urllib.request
import json
import ssl
import sys
import io
import time
import base64
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
HOST = "161.97.93.156"
USER = "carlos"
PASSWORD = "Innova1978+*?"
REMOTE_BASE = "/home/carlos/apps/dripzone-app"
LOCAL_APP = r"c:\Users\Carlos\dev\almeira-web\dripzone-app"
LOCAL_APK = os.path.join(LOCAL_APP, "public", "DripZone.apk")
REMOTE_APK = f"{REMOTE_BASE}/public/DripZone.apk"
EVOLUTION_API_URL = "https://evolution.almeira.com.co"
EVOLUTION_API_KEY = "EE49029EEB85-4568-8F81-C9FDFC6E2943"
INSTANCE_NAME = "AutomataAlmeira"
TARGET_PHONE = "573167455877"
APK_URL = "https://drip-zone.online/DripZone.apk"
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
def main():
print("[1/4] Verificando APK local compilado...", flush=True)
if not os.path.exists(LOCAL_APK):
print(f" [ERROR] El archivo {LOCAL_APK} no existe.", flush=True)
sys.exit(1)
size_mb = os.path.getsize(LOCAL_APK) / (1024 * 1024)
print(f" -> APK Verificado: {LOCAL_APK} ({size_mb:.2f} MB)", flush=True)
print("[2/4] Conectando por SSH al VPS y sincronizando APK público...", flush=True)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=HOST, username=USER, password=PASSWORD, timeout=30)
sftp = ssh.open_sftp()
print(f" -> Subiendo APK a {REMOTE_APK}...", flush=True)
sftp.put(LOCAL_APK, REMOTE_APK)
sftp.close()
stdin, stdout, stderr = ssh.exec_command("docker ps --format '{{.Names}}'")
containers = [c.strip() for c in stdout.read().decode('utf-8').splitlines() if c.strip()]
drip_containers = [c for c in containers if 'drip' in c.lower() or 'bfmno' in c.lower()]
for c in drip_containers:
ssh.exec_command(f"docker cp {REMOTE_APK} {c}:/app/public/DripZone.apk 2>/dev/null || true")
ssh.exec_command(f"docker cp {REMOTE_APK} {c}:/app/public/dripzone.apk 2>/dev/null || true")
ssh.exec_command(f"docker cp {REMOTE_APK} {c}:/app/DripZone.apk 2>/dev/null || true")
print(f" -> Copiado dentro de contenedor: {c}", flush=True)
ssh.close()
print("[3/4] Verificando URL pública del APK...", flush=True)
time.sleep(2)
try:
req = urllib.request.Request(APK_URL, method='HEAD')
with urllib.request.urlopen(req, context=ctx, timeout=15) as res:
live_size_mb = int(res.headers.get('Content-Length', 0)) / (1024 * 1024)
print(f" [OK] APK online en {APK_URL} (HTTP {res.status}, {live_size_mb:.2f} MB)", flush=True)
except Exception as e:
print(f" [WARN] Verificación HEAD APK: {e}", flush=True)
print("[4/4] Enviando APK y mensaje a WhatsApp (+57 316 745 5877)...", flush=True)
# 1. Mensaje de texto informativo
text_msg = (
"📲 *DripZone - APK Android Actualizado & Listo para Instalar*\n\n"
"¡Hola Carlos! Aquí tienes el archivo APK actualizado de la aplicación móvil con todas las últimas mejoras integradas:\n\n"
"✨ *Novedades de esta versión:*\n"
"• ✅ *Auto-Registro de Clientes:* Creación automática de usuarios desde pedidos recibidos por WhatsApp y Catálogo.\n"
"• ✅ *Pasarela Bold en WhatsApp:* Generación automática e inclusión del enlace directo para pagar la separación por PSE, Nequi, Tarjetas, Bancolombia y QR Bre-B.\n"
"• ✅ *Desglose Detallado:* Liquidación exacta con valor unitario, subtotales, saldo contraentrega y anticipos pendientes.\n"
"• ✅ *Catálogo y Categorías Dinámicas:* Acceso directo y filtrado ágil.\n\n"
f"🔗 *Descarga Alternativa Directa:* {APK_URL}"
)
req_text = urllib.request.Request(
f"{EVOLUTION_API_URL}/message/sendText/{INSTANCE_NAME}",
data=json.dumps({"number": TARGET_PHONE, "text": text_msg, "delay": 500}).encode("utf-8"),
headers={"apikey": EVOLUTION_API_KEY, "Content-Type": "application/json"}
)
try:
with urllib.request.urlopen(req_text, context=ctx, timeout=30) as resp:
print(" [OK] Mensaje de texto enviado a WhatsApp (Status:", resp.status, ")", flush=True)
except Exception as e:
print(" [Error texto WhatsApp]:", e, flush=True)
# 2. Envío del archivo APK como documento adjunto
req_media = urllib.request.Request(
f"{EVOLUTION_API_URL}/message/sendMedia/{INSTANCE_NAME}",
data=json.dumps({
"number": TARGET_PHONE,
"mediatype": "document",
"mimetype": "application/vnd.android.package-archive",
"fileName": "DripZone_Actualizado.apk",
"caption": "📦 *DripZone.apk (37 MB)* - Toca para instalar en tu Android",
"media": APK_URL
}).encode("utf-8"),
headers={"apikey": EVOLUTION_API_KEY, "Content-Type": "application/json"}
)
try:
with urllib.request.urlopen(req_media, context=ctx, timeout=180) as resp:
print(" [OK] Archivo APK enviado con éxito a WhatsApp (Status:", resp.status, ")", flush=True)
except Exception as e:
print(" [Error envío documento APK]:", e, flush=True)
print("\n✅ [PROCESO DE ENVÍO DE APK COMPLETADO EXITOSAMENTE]", flush=True)
if __name__ == "__main__":
main()