import type { GroupChatDto } from '../../apps/pc/qiwe/services/groups.service.js'; import type { CommunityDto } from '../../apps/pc/qiwe/services/community.service.js'; /** 上海城市范围默认门店编码 */ export const SHANGHAI_STORE_CODE = 'SH001'; /** 从小区地址解析上海区级名称,如「上海市黄浦区…」→「黄浦区」 */ export function parseShanghaiDistrict(address: string): string | null { if (!address || !address.includes('上海')) return null; const m = address.match(/上海市([^市区县]+[市区县])/); return m?.[1] ?? null; } export function isShanghaiAddress(address: string): boolean { return Boolean(address && address.includes('上海')); } export interface CommunityDistrictIndex { byCommunityId: Map; districts: string[]; } export function buildCommunityDistrictIndex(communities: CommunityDto[]): CommunityDistrictIndex { const byCommunityId = new Map(); const districtSet = new Set(); for (const c of communities) { const district = parseShanghaiDistrict(c.address) || '其他'; byCommunityId.set(c.id, district); if (isShanghaiAddress(c.address)) { districtSet.add(district); } } const districts = Array.from(districtSet).sort((a, b) => { if (a === '其他') return 1; if (b === '其他') return -1; return a.localeCompare(b, 'zh-CN'); }); return { byCommunityId, districts }; } export function filterGroupsForDashboardScope( groups: GroupChatDto[], scope: { level: string; storeId?: string; shanghaiStoreId?: string; district?: string; roomId?: string; storeIds?: string[]; communityIndex?: CommunityDistrictIndex; }, ): GroupChatDto[] { if (scope.level === 'group' && scope.roomId) { return groups.filter((g) => g.roomId === scope.roomId); } let result = groups; if (scope.level === 'city' && scope.shanghaiStoreId) { const idx = scope.communityIndex; result = result.filter((g) => { if (!g.storeId || g.storeId === scope.shanghaiStoreId) return true; if (g.communityId && idx?.byCommunityId.has(g.communityId)) { const comm = idx.byCommunityId.get(g.communityId)!; return comm !== '其他'; } return false; }); } else if (scope.level === 'global') { // 全局:全部群(含未绑定门店的企微同步群) result = groups; } else if (scope.level === 'region' && scope.storeIds?.length) { const allowed = new Set(scope.storeIds); result = result.filter((g) => !g.storeId || allowed.has(g.storeId)); } else if (scope.level === 'store' && scope.storeId) { // 门店:匹配门店 ID,或未绑定门店的群(企微同步常见) result = result.filter((g) => !g.storeId || g.storeId === scope.storeId); } if (scope.level === 'district' && scope.district && scope.communityIndex) { const idx = scope.communityIndex; if (scope.shanghaiStoreId) { result = result.filter((g) => { if (!g.storeId || g.storeId === scope.shanghaiStoreId) return true; if (g.communityId && idx.byCommunityId.has(g.communityId)) { return idx.byCommunityId.get(g.communityId)! !== '其他'; } return false; }); } result = result.filter((g) => { if (!g.communityId) return scope.district === '未分区'; const d = idx.byCommunityId.get(g.communityId) || '未分区'; return d === scope.district; }); } return result; }