Sync Tahesab account group catalog with customer sync without touching manual groups.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -213,9 +213,65 @@ export class CustomerGroupsService {
|
||||
}
|
||||
}
|
||||
|
||||
/** ساخت گروه تهحساب با نام یکتا؛ گروههای دستی همنام دست نخورده میمانند. */
|
||||
private async createTahesabGroupUnique(
|
||||
organizationId: string,
|
||||
connectionId: string,
|
||||
baseName: string,
|
||||
cleanGid: string | null,
|
||||
): Promise<string> {
|
||||
const max = await this.prisma.customerGroup.aggregate({
|
||||
where: { organizationId },
|
||||
_max: { position: true },
|
||||
});
|
||||
let position = (max._max.position ?? -1) + 1;
|
||||
const candidates = [
|
||||
baseName,
|
||||
`${baseName} · تهحساب`,
|
||||
...Array.from({ length: 8 }, (_, i) => `${baseName} · تهحساب ${i + 2}`),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const name = normalizeGroupName(candidate);
|
||||
if (!name) continue;
|
||||
const clash = await this.prisma.customerGroup.findFirst({
|
||||
where: { organizationId, name: { equals: name, mode: 'insensitive' } },
|
||||
select: { id: true, tahesabGid: true, tahesabConnectionId: true },
|
||||
});
|
||||
if (
|
||||
clash &&
|
||||
cleanGid &&
|
||||
clash.tahesabGid === cleanGid &&
|
||||
clash.tahesabConnectionId === connectionId
|
||||
) {
|
||||
return clash.id;
|
||||
}
|
||||
if (clash) continue;
|
||||
try {
|
||||
const created = await this.prisma.customerGroup.create({
|
||||
data: {
|
||||
organizationId,
|
||||
name,
|
||||
position,
|
||||
tahesabConnectionId: connectionId,
|
||||
tahesabGid: cleanGid,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return created.id;
|
||||
} catch (e) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
|
||||
position += 1;
|
||||
continue;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
throw new ConflictException(`ساخت گروه تهحساب «${baseName}» ممکن نشد.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* گروه متناظر یک گروه تهحساب: اول با GID روی همان اتصال، بعد با نام.
|
||||
* با تغییر نام در تهحساب گروه تکراری ساخته نمیشود.
|
||||
* گروه متناظر یک گروه تهحساب: اول با GID روی همان اتصال، بعد با نامِ همان اتصال.
|
||||
* گروه دستی همنام را به تهحساب وصل نمیکند.
|
||||
*/
|
||||
async ensureTahesabGroup(
|
||||
organizationId: string,
|
||||
@@ -241,14 +297,27 @@ export class CustomerGroupsService {
|
||||
}
|
||||
}
|
||||
if (!name) return null;
|
||||
const group = await this.findOrCreateByName(organizationId, name);
|
||||
if (cleanGid && !group.tahesabGid) {
|
||||
await this.prisma.customerGroup.update({
|
||||
where: { id: group.id },
|
||||
data: { tahesabConnectionId: connectionId, tahesabGid: cleanGid },
|
||||
});
|
||||
|
||||
const byName = await this.prisma.customerGroup.findFirst({
|
||||
where: { organizationId, name: { equals: name, mode: 'insensitive' } },
|
||||
select: { id: true, tahesabGid: true, tahesabConnectionId: true },
|
||||
});
|
||||
if (byName) {
|
||||
if (
|
||||
cleanGid &&
|
||||
byName.tahesabGid === cleanGid &&
|
||||
byName.tahesabConnectionId === connectionId
|
||||
) {
|
||||
return byName.id;
|
||||
}
|
||||
if (byName.tahesabConnectionId === connectionId && byName.tahesabGid) {
|
||||
return byName.id;
|
||||
}
|
||||
// گروه دستی یا گروه اتصال دیگر با همین نام → جدا بساز
|
||||
return this.createTahesabGroupUnique(organizationId, connectionId, name, cleanGid);
|
||||
}
|
||||
return group.id;
|
||||
|
||||
return this.createTahesabGroupUnique(organizationId, connectionId, name, cleanGid);
|
||||
}
|
||||
|
||||
/** گروههای دستی شخص (جایگزین کامل). منبع لینکهایی که میمانند حفظ میشود. */
|
||||
|
||||
@@ -54,6 +54,10 @@ function asMoshtariList(raw: unknown): Array<Record<string, unknown>> {
|
||||
if (Array.isArray(raw)) return raw as Array<Record<string, unknown>>;
|
||||
if (typeof raw === 'object') {
|
||||
const obj = raw as Record<string, unknown>;
|
||||
for (const key of ['DoListGorooh', 'Gorooh', 'Groups', 'items', 'Items', 'Data']) {
|
||||
const nested = obj[key];
|
||||
if (Array.isArray(nested)) return nested as Array<Record<string, unknown>>;
|
||||
}
|
||||
// پاسخ گاهی دیکشنری با کلید عددی است
|
||||
const vals = Object.values(obj);
|
||||
if (vals.every((v) => v && typeof v === 'object')) {
|
||||
@@ -63,6 +67,15 @@ function asMoshtariList(raw: unknown): Array<Record<string, unknown>> {
|
||||
return [];
|
||||
}
|
||||
|
||||
function pickCatalogGroup(row: Record<string, unknown>): { gid: string; name: string } | null {
|
||||
const rawGid = row.GID ?? row.Gid ?? row.GroupID ?? row.GroupId;
|
||||
const rawName = row.Name ?? row.GoroupName ?? row.GroupName ?? row.Group_Name ?? row.Goroup;
|
||||
const gid = rawGid == null ? '' : String(rawGid).trim();
|
||||
const name = rawName == null ? '' : String(rawName).trim();
|
||||
if (!gid && !name) return null;
|
||||
return { gid: gid || name, name: name || `گروه ${gid}` };
|
||||
}
|
||||
|
||||
function pickCode(row: Record<string, unknown>): number | null {
|
||||
const c =
|
||||
row.Moshtari_Code ??
|
||||
@@ -882,11 +895,64 @@ export class TahesabPersonLinkService {
|
||||
await this.applyTahesabGroup(organizationId, connectionId, personId, row);
|
||||
}
|
||||
|
||||
/**
|
||||
* فهرست کامل گروههای حساب تهحساب (DoListGorooh) → ساخت/بهروزرسانی نام در CRM.
|
||||
* برخلاف همگامسازی صفحهای مشتریان، گروه بدون مشتری لینکشده هم میآید.
|
||||
*/
|
||||
async syncGroupCatalog(organizationId: string, connectionId: string) {
|
||||
const { api } = await this.connections.getApi(organizationId, connectionId);
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = await api.doListGorooh();
|
||||
} catch (err) {
|
||||
throw new BadRequestException(
|
||||
err instanceof Error ? err.message : 'خواندن فهرست گروههای تهحساب ناموفق بود.',
|
||||
);
|
||||
}
|
||||
const rows = asMoshtariList(raw);
|
||||
let upserted = 0;
|
||||
let failed = 0;
|
||||
const errors: string[] = [];
|
||||
for (const row of rows) {
|
||||
const group = pickCatalogGroup(row);
|
||||
if (!group) continue;
|
||||
try {
|
||||
const id = await this.groups.ensureTahesabGroup(
|
||||
organizationId,
|
||||
connectionId,
|
||||
group.gid,
|
||||
group.name,
|
||||
);
|
||||
if (id) upserted += 1;
|
||||
} catch (err) {
|
||||
failed += 1;
|
||||
if (errors.length < 5) {
|
||||
errors.push(err instanceof Error ? err.message : 'خطا');
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
total: rows.length,
|
||||
upserted,
|
||||
failed,
|
||||
error: errors.length ? errors.join('؛ ') : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* همهٔ مشتریان تهحساب را صفحه به صفحه میخواند.
|
||||
* کد تازه وارد میشود؛ کد لینکشده نام و شماره و گروهش تازه میشود.
|
||||
*/
|
||||
async syncAllCustomers(organizationId: string, connectionId: string) {
|
||||
try {
|
||||
await this.syncGroupCatalog(organizationId, connectionId);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`فهرست گروههای تهحساب قبل از همگام مشتریان خوانده نشد: ${
|
||||
err instanceof Error ? err.message : err
|
||||
}`,
|
||||
);
|
||||
}
|
||||
const { api } = await this.connections.getApi(organizationId, connectionId);
|
||||
let page = 1;
|
||||
let emptyStreak = 0;
|
||||
|
||||
@@ -401,6 +401,11 @@ export class TahesabApi {
|
||||
return this.call('DoListHesabBanki', 'DoListHesabBanki', []);
|
||||
}
|
||||
|
||||
/** فهرست همهٔ گروههای حساب تهحساب (Name + GID) */
|
||||
doListGorooh() {
|
||||
return this.call('DoListGorooh', 'DoListGorooh', [], 'POST', undefined, NO_RECORDS);
|
||||
}
|
||||
|
||||
doNewSanadBuySaleGold(args: unknown[]) {
|
||||
return this.call('DoNewSanadBuySaleGOLD', 'DoNewSanadBuySaleGOLD', args);
|
||||
}
|
||||
|
||||
@@ -229,9 +229,20 @@ export class TahesabController {
|
||||
return this.links.importBulk(user.organizationId, dto);
|
||||
}
|
||||
|
||||
/** فهرست کامل گروههای تهحساب (DoListGorooh) → ساخت/بهروزرسانی در CRM */
|
||||
@Post('sync/groups')
|
||||
@Roles('owner', 'admin')
|
||||
syncGroups(
|
||||
@CurrentUser() user: { organizationId: string },
|
||||
@Body() dto: SyncAllCustomersDto,
|
||||
) {
|
||||
return this.links.syncGroupCatalog(user.organizationId, dto.connectionId);
|
||||
}
|
||||
|
||||
/** گروه روی مشتریهای لینکشده (صفحهای از DoListMoshtari) */
|
||||
@Post('sync/groups-on-people')
|
||||
@Roles('owner', 'admin')
|
||||
syncGroupsOnPeople(
|
||||
@CurrentUser() user: { organizationId: string },
|
||||
@Body() dto: SyncGroupsPageDto,
|
||||
) {
|
||||
|
||||
Reference in New Issue
Block a user