diff --git a/apps/api/src/customer-groups/customer-groups.service.ts b/apps/api/src/customer-groups/customer-groups.service.ts index 6cea8ce..0636ea2 100644 --- a/apps/api/src/customer-groups/customer-groups.service.ts +++ b/apps/api/src/customer-groups/customer-groups.service.ts @@ -213,9 +213,65 @@ export class CustomerGroupsService { } } + /** ساخت گروه ته‌حساب با نام یکتا؛ گروه‌های دستی هم‌نام دست نخورده می‌مانند. */ + private async createTahesabGroupUnique( + organizationId: string, + connectionId: string, + baseName: string, + cleanGid: string | null, + ): Promise { + 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); } /** گروه‌های دستی شخص (جایگزین کامل). منبع لینک‌هایی که می‌مانند حفظ می‌شود. */ diff --git a/apps/api/src/integrations/tahesab/person-link.service.ts b/apps/api/src/integrations/tahesab/person-link.service.ts index 41074ec..db6b4aa 100644 --- a/apps/api/src/integrations/tahesab/person-link.service.ts +++ b/apps/api/src/integrations/tahesab/person-link.service.ts @@ -54,6 +54,10 @@ function asMoshtariList(raw: unknown): Array> { if (Array.isArray(raw)) return raw as Array>; if (typeof raw === 'object') { const obj = raw as Record; + for (const key of ['DoListGorooh', 'Gorooh', 'Groups', 'items', 'Items', 'Data']) { + const nested = obj[key]; + if (Array.isArray(nested)) return nested as Array>; + } // پاسخ گاهی دیکشنری با کلید عددی است const vals = Object.values(obj); if (vals.every((v) => v && typeof v === 'object')) { @@ -63,6 +67,15 @@ function asMoshtariList(raw: unknown): Array> { return []; } +function pickCatalogGroup(row: Record): { 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): 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; diff --git a/apps/api/src/integrations/tahesab/tahesab-methods.ts b/apps/api/src/integrations/tahesab/tahesab-methods.ts index a770b3e..3ee223b 100644 --- a/apps/api/src/integrations/tahesab/tahesab-methods.ts +++ b/apps/api/src/integrations/tahesab/tahesab-methods.ts @@ -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); } diff --git a/apps/api/src/integrations/tahesab/tahesab.controller.ts b/apps/api/src/integrations/tahesab/tahesab.controller.ts index 4f009c6..06b982e 100644 --- a/apps/api/src/integrations/tahesab/tahesab.controller.ts +++ b/apps/api/src/integrations/tahesab/tahesab.controller.ts @@ -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, ) { diff --git a/apps/web/src/components/CustomerGroupsManager.vue b/apps/web/src/components/CustomerGroupsManager.vue index 1661b45..4aea1a1 100644 --- a/apps/web/src/components/CustomerGroupsManager.vue +++ b/apps/web/src/components/CustomerGroupsManager.vue @@ -180,8 +180,10 @@ watch(

هر شخص یا شرکت می‌تواند چند گروه داشته باشد. مسئولان گروه (اختیاری) اعضای آن گروه را مثل - مشتریان خود می‌بینند. گروه‌های ته‌حساب با برچسب «ته‌حساب» مشخص شده‌اند. + مشتریان خود می‌بینند. گروه‌های ته‌حساب با برچسب «ته‌حساب» مشخص شده‌اند و با بروزرسانی + مشتریان ته‌حساب خودکار می‌آیند؛ گروه‌های دستی جدا می‌مانند.

+

{{ error }}

@@ -218,8 +220,6 @@ watch(
-

{{ error }}

-

گروه‌های موجود