2026-09-26 17:59:16 +03:30
|
|
|
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
|
|
|
|
|
import { Cron } from '@nestjs/schedule';
|
|
|
|
|
import { Prisma } from '@prisma/client';
|
|
|
|
|
import type {
|
|
|
|
|
WooCommerceOrderLinkDto,
|
|
|
|
|
WooCommerceSyncResultDto,
|
|
|
|
|
} from '@mento/shared';
|
|
|
|
|
import { PrismaService } from '../../prisma/prisma.service';
|
2026-11-05 10:51:36 +03:30
|
|
|
import {
|
|
|
|
|
normalizeEmail,
|
|
|
|
|
phoneIdentityKeys,
|
|
|
|
|
storedPhoneNumber,
|
|
|
|
|
} from '../../contacts/normalize';
|
2026-09-26 17:59:16 +03:30
|
|
|
import { WooConnectionsService } from './connections.service';
|
|
|
|
|
import type { WooOrder } from './woo-client';
|
|
|
|
|
|
|
|
|
|
function mapInvoiceStatus(
|
|
|
|
|
wooStatus: string | undefined,
|
|
|
|
|
): 'issued' | 'paid' | 'canceled' {
|
|
|
|
|
const s = (wooStatus ?? '').toLowerCase();
|
|
|
|
|
if (s === 'completed' || s === 'processing') return 'paid';
|
|
|
|
|
if (s === 'cancelled' || s === 'canceled' || s === 'refunded' || s === 'failed') {
|
|
|
|
|
return 'canceled';
|
|
|
|
|
}
|
|
|
|
|
return 'issued';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function isPaidStatus(wooStatus: string | undefined): boolean {
|
|
|
|
|
const s = (wooStatus ?? '').toLowerCase();
|
|
|
|
|
return s === 'completed' || s === 'processing';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class WooSyncService {
|
|
|
|
|
private readonly logger = new Logger(WooSyncService.name);
|
|
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
|
private readonly prisma: PrismaService,
|
|
|
|
|
private readonly connections: WooConnectionsService,
|
|
|
|
|
) {}
|
|
|
|
|
|
|
|
|
|
async syncConnection(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
connectionId: string,
|
|
|
|
|
): Promise<WooCommerceSyncResultDto> {
|
|
|
|
|
const { row, client } = await this.connections.getClient(
|
|
|
|
|
organizationId,
|
|
|
|
|
connectionId,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const result: WooCommerceSyncResultDto = {
|
|
|
|
|
fetched: 0,
|
|
|
|
|
created: 0,
|
|
|
|
|
updated: 0,
|
|
|
|
|
skipped: 0,
|
|
|
|
|
errors: [],
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const after = row.lastSyncAt
|
|
|
|
|
? new Date(row.lastSyncAt.getTime() - 60_000).toISOString()
|
|
|
|
|
: undefined;
|
|
|
|
|
|
|
|
|
|
let page = 1;
|
|
|
|
|
let batch: WooOrder[] = [];
|
|
|
|
|
do {
|
|
|
|
|
batch = await client.listOrders({
|
|
|
|
|
page,
|
|
|
|
|
perPage: 50,
|
|
|
|
|
modifiedAfter: after,
|
|
|
|
|
});
|
|
|
|
|
result.fetched += batch.length;
|
|
|
|
|
for (const order of batch) {
|
|
|
|
|
try {
|
|
|
|
|
const outcome = await this.upsertOrder(
|
|
|
|
|
organizationId,
|
|
|
|
|
connectionId,
|
|
|
|
|
order,
|
|
|
|
|
);
|
|
|
|
|
if (outcome === 'created') result.created += 1;
|
|
|
|
|
else if (outcome === 'updated') result.updated += 1;
|
|
|
|
|
else result.skipped += 1;
|
|
|
|
|
} catch (e) {
|
|
|
|
|
const msg = e instanceof Error ? e.message : String(e);
|
|
|
|
|
result.errors.push(`سفارش ${order.id}: ${msg}`);
|
|
|
|
|
this.logger.warn(`Woo sync order ${order.id}: ${msg}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
page += 1;
|
|
|
|
|
} while (batch.length >= 50 && page <= 20);
|
|
|
|
|
|
|
|
|
|
await this.prisma.wooCommerceConnection.update({
|
|
|
|
|
where: { id: connectionId },
|
|
|
|
|
data: {
|
|
|
|
|
lastSyncAt: new Date(),
|
|
|
|
|
lastHealthAt: new Date(),
|
|
|
|
|
lastHealthOk: true,
|
|
|
|
|
lastError: result.errors.length
|
|
|
|
|
? result.errors.slice(0, 3).join(' | ').slice(0, 500)
|
|
|
|
|
: null,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
} catch (e) {
|
|
|
|
|
const msg = e instanceof Error ? e.message : String(e);
|
|
|
|
|
result.errors.push(msg);
|
|
|
|
|
await this.prisma.wooCommerceConnection.update({
|
|
|
|
|
where: { id: connectionId },
|
|
|
|
|
data: {
|
|
|
|
|
lastHealthAt: new Date(),
|
|
|
|
|
lastHealthOk: false,
|
|
|
|
|
lastError: msg.slice(0, 500),
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async ingestWebhookOrder(
|
|
|
|
|
connectionId: string,
|
|
|
|
|
order: WooOrder,
|
|
|
|
|
): Promise<{ invoiceId: string; outcome: string }> {
|
|
|
|
|
const conn = await this.prisma.wooCommerceConnection.findFirst({
|
|
|
|
|
where: { id: connectionId, enabled: true },
|
|
|
|
|
});
|
|
|
|
|
if (!conn) throw new NotFoundException('اتصال پیدا نشد');
|
|
|
|
|
const outcome = await this.upsertOrder(
|
|
|
|
|
conn.organizationId,
|
|
|
|
|
connectionId,
|
|
|
|
|
order,
|
|
|
|
|
);
|
|
|
|
|
const link = await this.prisma.wooCommerceOrderLink.findUnique({
|
|
|
|
|
where: {
|
|
|
|
|
connectionId_wooOrderId: {
|
|
|
|
|
connectionId,
|
|
|
|
|
wooOrderId: String(order.id),
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
await this.prisma.wooCommerceConnection.update({
|
|
|
|
|
where: { id: connectionId },
|
|
|
|
|
data: { lastSyncAt: new Date() },
|
|
|
|
|
});
|
|
|
|
|
return { invoiceId: link!.invoiceId, outcome };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async listRecentOrders(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
connectionId?: string,
|
|
|
|
|
): Promise<WooCommerceOrderLinkDto[]> {
|
|
|
|
|
const rows = await this.prisma.wooCommerceOrderLink.findMany({
|
|
|
|
|
where: {
|
|
|
|
|
organizationId,
|
|
|
|
|
...(connectionId ? { connectionId } : {}),
|
|
|
|
|
},
|
|
|
|
|
orderBy: { syncedAt: 'desc' },
|
|
|
|
|
take: 40,
|
|
|
|
|
});
|
|
|
|
|
const invoiceIds = rows.map((r) => r.invoiceId);
|
|
|
|
|
const invoices = invoiceIds.length
|
|
|
|
|
? await this.prisma.invoice.findMany({
|
|
|
|
|
where: { id: { in: invoiceIds } },
|
|
|
|
|
select: { id: true, number: true },
|
|
|
|
|
})
|
|
|
|
|
: [];
|
|
|
|
|
const byId = new Map(invoices.map((i) => [i.id, i.number]));
|
|
|
|
|
return rows.map((r) => ({
|
|
|
|
|
id: r.id,
|
|
|
|
|
wooOrderId: r.wooOrderId,
|
|
|
|
|
wooOrderNumber: r.wooOrderNumber,
|
|
|
|
|
invoiceId: r.invoiceId,
|
|
|
|
|
invoiceNumber: byId.get(r.invoiceId) ?? '—',
|
|
|
|
|
status: r.status,
|
|
|
|
|
total: Number(r.total),
|
|
|
|
|
currency: r.currency,
|
|
|
|
|
syncedAt: r.syncedAt.toISOString(),
|
|
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Cron('*/15 * * * *')
|
|
|
|
|
async cronSyncAll(): Promise<void> {
|
|
|
|
|
const connections = await this.prisma.wooCommerceConnection.findMany({
|
|
|
|
|
where: { enabled: true },
|
|
|
|
|
select: { id: true, organizationId: true },
|
|
|
|
|
take: 30,
|
|
|
|
|
});
|
|
|
|
|
for (const c of connections) {
|
|
|
|
|
try {
|
|
|
|
|
await this.syncConnection(c.organizationId, c.id);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
this.logger.warn(
|
|
|
|
|
`Woo cron sync ${c.id}: ${e instanceof Error ? e.message : e}`,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async upsertOrder(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
connectionId: string,
|
|
|
|
|
order: WooOrder,
|
|
|
|
|
): Promise<'created' | 'updated' | 'skipped'> {
|
|
|
|
|
if (!order?.id) return 'skipped';
|
|
|
|
|
|
|
|
|
|
const personId = await this.upsertPerson(organizationId, order);
|
|
|
|
|
const currency = (order.currency ?? 'IRR').trim() || 'IRR';
|
|
|
|
|
const total = Number(order.total ?? 0) || 0;
|
|
|
|
|
const discount = Number(order.discount_total ?? 0) || 0;
|
|
|
|
|
const status = mapInvoiceStatus(order.status);
|
|
|
|
|
const title = `سفارش ووکامرس #${order.number ?? order.id}`;
|
|
|
|
|
const number = `WOO-${order.id}`;
|
|
|
|
|
const issuedAt = order.date_created
|
|
|
|
|
? new Date(order.date_created)
|
|
|
|
|
: new Date();
|
|
|
|
|
const notes = [
|
|
|
|
|
order.payment_method_title
|
|
|
|
|
? `روش پرداخت: ${order.payment_method_title}`
|
|
|
|
|
: null,
|
|
|
|
|
`وضعیت ووکامرس: ${order.status ?? '—'}`,
|
|
|
|
|
]
|
|
|
|
|
.filter(Boolean)
|
|
|
|
|
.join('\n');
|
|
|
|
|
|
|
|
|
|
const lineItems = (order.line_items ?? []).map((item, index) => ({
|
|
|
|
|
name: (item.name ?? 'قلم').trim() || 'قلم',
|
|
|
|
|
quantity: new Prisma.Decimal(item.quantity ?? 1),
|
|
|
|
|
unitPrice: new Prisma.Decimal(
|
|
|
|
|
item.price != null
|
|
|
|
|
? item.price
|
|
|
|
|
: item.quantity
|
|
|
|
|
? Number(item.total ?? 0) / item.quantity
|
|
|
|
|
: Number(item.total ?? 0),
|
|
|
|
|
),
|
|
|
|
|
currency,
|
|
|
|
|
position: index,
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
const existing = await this.prisma.wooCommerceOrderLink.findUnique({
|
|
|
|
|
where: {
|
|
|
|
|
connectionId_wooOrderId: {
|
|
|
|
|
connectionId,
|
|
|
|
|
wooOrderId: String(order.id),
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (existing) {
|
|
|
|
|
await this.prisma.invoice.update({
|
|
|
|
|
where: { id: existing.invoiceId },
|
|
|
|
|
data: {
|
|
|
|
|
title,
|
|
|
|
|
status,
|
|
|
|
|
currency,
|
|
|
|
|
notes,
|
|
|
|
|
discountAmount: new Prisma.Decimal(discount),
|
|
|
|
|
personId,
|
|
|
|
|
issuedAt,
|
|
|
|
|
lineItems: {
|
|
|
|
|
deleteMany: {},
|
|
|
|
|
create: lineItems.length
|
|
|
|
|
? lineItems
|
|
|
|
|
: [
|
|
|
|
|
{
|
|
|
|
|
name: title,
|
|
|
|
|
quantity: new Prisma.Decimal(1),
|
|
|
|
|
unitPrice: new Prisma.Decimal(total),
|
|
|
|
|
currency,
|
|
|
|
|
position: 0,
|
|
|
|
|
},
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
await this.ensurePayment(
|
|
|
|
|
existing.invoiceId,
|
|
|
|
|
order,
|
|
|
|
|
total,
|
|
|
|
|
currency,
|
|
|
|
|
);
|
|
|
|
|
await this.prisma.wooCommerceOrderLink.update({
|
|
|
|
|
where: { id: existing.id },
|
|
|
|
|
data: {
|
|
|
|
|
wooOrderNumber: order.number ? String(order.number) : null,
|
|
|
|
|
status: order.status ?? '',
|
|
|
|
|
total: new Prisma.Decimal(total),
|
|
|
|
|
currency,
|
|
|
|
|
rawPayload: order as unknown as Prisma.InputJsonValue,
|
|
|
|
|
syncedAt: new Date(),
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
return 'updated';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const invoice = await this.prisma.invoice.create({
|
|
|
|
|
data: {
|
|
|
|
|
organizationId,
|
|
|
|
|
number,
|
|
|
|
|
title,
|
|
|
|
|
status,
|
|
|
|
|
kind: 'invoice',
|
|
|
|
|
currency,
|
|
|
|
|
notes,
|
|
|
|
|
discountAmount: new Prisma.Decimal(discount),
|
|
|
|
|
taxPercent: new Prisma.Decimal(0),
|
|
|
|
|
issuedAt,
|
|
|
|
|
personId,
|
|
|
|
|
lineItems: {
|
|
|
|
|
create: lineItems.length
|
|
|
|
|
? lineItems
|
|
|
|
|
: [
|
|
|
|
|
{
|
|
|
|
|
name: title,
|
|
|
|
|
quantity: new Prisma.Decimal(1),
|
|
|
|
|
unitPrice: new Prisma.Decimal(total),
|
|
|
|
|
currency,
|
|
|
|
|
position: 0,
|
|
|
|
|
},
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
await this.ensurePayment(invoice.id, order, total, currency);
|
|
|
|
|
|
|
|
|
|
await this.prisma.wooCommerceOrderLink.create({
|
|
|
|
|
data: {
|
|
|
|
|
organizationId,
|
|
|
|
|
connectionId,
|
|
|
|
|
wooOrderId: String(order.id),
|
|
|
|
|
wooOrderNumber: order.number ? String(order.number) : null,
|
|
|
|
|
invoiceId: invoice.id,
|
|
|
|
|
status: order.status ?? '',
|
|
|
|
|
total: new Prisma.Decimal(total),
|
|
|
|
|
currency,
|
|
|
|
|
rawPayload: order as unknown as Prisma.InputJsonValue,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return 'created';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async ensurePayment(
|
|
|
|
|
invoiceId: string,
|
|
|
|
|
order: WooOrder,
|
|
|
|
|
total: number,
|
|
|
|
|
currency: string,
|
|
|
|
|
) {
|
|
|
|
|
if (!isPaidStatus(order.status) || total <= 0) return;
|
|
|
|
|
const existing = await this.prisma.payment.findFirst({
|
|
|
|
|
where: { invoiceId, notes: { contains: 'woocommerce' } },
|
|
|
|
|
});
|
|
|
|
|
if (existing) {
|
|
|
|
|
await this.prisma.payment.update({
|
|
|
|
|
where: { id: existing.id },
|
|
|
|
|
data: {
|
|
|
|
|
amount: new Prisma.Decimal(total),
|
|
|
|
|
currency,
|
|
|
|
|
paidAt: order.date_paid ? new Date(order.date_paid) : new Date(),
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
await this.prisma.payment.create({
|
|
|
|
|
data: {
|
|
|
|
|
invoiceId,
|
|
|
|
|
amount: new Prisma.Decimal(total),
|
|
|
|
|
currency,
|
|
|
|
|
method: 'card',
|
|
|
|
|
paidAt: order.date_paid ? new Date(order.date_paid) : new Date(),
|
|
|
|
|
notes: `woocommerce order #${order.id}`,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async upsertPerson(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
order: WooOrder,
|
|
|
|
|
): Promise<string | null> {
|
|
|
|
|
const billing = order.billing ?? {};
|
|
|
|
|
const email = normalizeEmail(billing.email ?? null);
|
2026-11-05 10:51:36 +03:30
|
|
|
const mobile = storedPhoneNumber(billing.phone ?? null);
|
|
|
|
|
const mobileKeys = phoneIdentityKeys(mobile);
|
2026-09-26 17:59:16 +03:30
|
|
|
const firstName = (billing.first_name ?? '').trim() || 'مشتری';
|
|
|
|
|
const lastName = (billing.last_name ?? '').trim() || 'ووکامرس';
|
|
|
|
|
|
|
|
|
|
if (!email && !mobile) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const existing = await this.prisma.person.findFirst({
|
|
|
|
|
where: {
|
|
|
|
|
organizationId,
|
|
|
|
|
OR: [
|
|
|
|
|
...(email ? [{ email }] : []),
|
2026-11-05 10:51:36 +03:30
|
|
|
...(mobileKeys.length
|
|
|
|
|
? [{ mobile: { in: mobileKeys } }, { phone: { in: mobileKeys } }]
|
|
|
|
|
: []),
|
2026-09-26 17:59:16 +03:30
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
select: { id: true },
|
|
|
|
|
});
|
|
|
|
|
if (existing) {
|
|
|
|
|
await this.prisma.person.update({
|
|
|
|
|
where: { id: existing.id },
|
|
|
|
|
data: {
|
|
|
|
|
...(email ? { email } : {}),
|
|
|
|
|
...(mobile ? { mobile } : {}),
|
|
|
|
|
firstName,
|
|
|
|
|
lastName,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
return existing.id;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const created = await this.prisma.person.create({
|
|
|
|
|
data: {
|
|
|
|
|
organizationId,
|
|
|
|
|
firstName,
|
|
|
|
|
lastName,
|
|
|
|
|
email,
|
|
|
|
|
mobile,
|
|
|
|
|
phone: mobile,
|
|
|
|
|
notes: order.customer_id
|
|
|
|
|
? `ووکامرس customer_id=${order.customer_id}`
|
|
|
|
|
: 'واردشده از ووکامرس',
|
|
|
|
|
tags: ['woocommerce'],
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
return created.id;
|
|
|
|
|
}
|
|
|
|
|
}
|