fix: switch DingTalk attendance API from getcolumnval to listRecord

This commit is contained in:
2026-07-08 14:49:22 +08:00
parent 166d0b2694
commit f1959f0d2a
3 changed files with 70 additions and 19 deletions

View File

@@ -392,18 +392,17 @@ export class DingTalkService {
if (!this.configured) throw new Error('DingTalk not configured'); if (!this.configured) throw new Error('DingTalk not configured');
const token = await this.getAccessToken(); const token = await this.getAccessToken();
const columnIdList = ['1','2','3','4','5','6','8','9']; const dateFrom = params.startDate.includes(' ') ? params.startDate : `${params.startDate} 00:00:00`;
const dateTo = params.endDate.includes(' ') ? params.endDate : `${params.endDate} 23:59:59`;
const body: Record<string, unknown> = { const body: Record<string, unknown> = {
column_id_list: columnIdList.join(','), checkDateFrom: dateFrom,
from_date: params.startDate, checkDateTo: dateTo,
to_date: params.endDate,
offset: params.offset ?? 0,
limit: params.limit ?? 50,
}; };
if (params.userIds?.length) body.userid_list = params.userIds.join(','); if (params.userIds?.length) body.userIds = params.userIds;
const res = await fetch( const res = await fetch(
`https://oapi.dingtalk.com/topapi/attendance/getcolumnval?access_token=${token}`, `https://oapi.dingtalk.com/attendance/listRecord?access_token=${token}`,
{ {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@@ -412,14 +411,26 @@ export class DingTalkService {
); );
const data = await res.json() as { const data = await res.json() as {
errcode: number; errmsg: string; errcode: number; errmsg: string;
result: { hasMore: boolean; column_vals?: Array<{ column_vals: string[] }> }; recordresult?: Array<{
id: number; userId: string; workDate: number;
userCheckTime: number; sourceType: string;
checkType?: string; timeResult?: string;
locationResult?: string; locationMethod?: string;
userAddress?: string; userLongitude?: number; userLatitude?: number;
}>;
}; };
if (data.errcode !== 0) throw new Error(`钉钉考勤获取失败: ${data.errmsg}`); if (data.errcode !== 0) throw new Error(`钉钉考勤获取失败: ${data.errmsg}`);
return (data.result?.column_vals ?? []).map((col) => { return (data.recordresult ?? []).map((r) => ({
const v = col.column_vals ?? []; userId: r.userId,
return { userId: v[0]??'', workDate: v[1]??'', timeResult: v[2]??'', locationResult: v[3]??'', planCheckTime: v[4]??'', actualCheckTime: v[5]??'', checkId: v[7]??'', checkType: v[8]??'' }; workDate: new Date(r.workDate).toISOString().slice(0, 10),
}); timeResult: r.timeResult ?? r.sourceType ?? '',
locationResult: r.locationResult ?? r.locationMethod ?? r.userAddress ?? '',
planCheckTime: '',
actualCheckTime: new Date(r.userCheckTime).toISOString(),
checkId: String(r.id),
checkType: r.checkType ?? r.sourceType ?? '',
}));
} }
private delay(requestIndex: number): Promise<void> { private delay(requestIndex: number): Promise<void> {

View File

@@ -2,15 +2,17 @@ import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule'; import { ScheduleModule } from '@nestjs/schedule';
import { TypeOrmModule } from '@nestjs/typeorm'; import { TypeOrmModule } from '@nestjs/typeorm';
import { IntegrationModule } from '../integration/integration.module'; import { IntegrationModule } from '../integration/integration.module';
import { SyncLog, SyncState } from '../entities'; import { AttendanceModule } from '../attendance/attendance.module';
import { SyncLog, SyncState, UserDingMapping } from '../entities';
import { SyncService } from './sync.service'; import { SyncService } from './sync.service';
import { SyncController } from './sync.controller'; import { SyncController } from './sync.controller';
@Module({ @Module({
imports: [ imports: [
ScheduleModule.forRoot(), ScheduleModule.forRoot(),
TypeOrmModule.forFeature([SyncLog, SyncState]), TypeOrmModule.forFeature([SyncLog, SyncState, UserDingMapping]),
IntegrationModule, IntegrationModule,
AttendanceModule,
], ],
controllers: [SyncController], controllers: [SyncController],
providers: [SyncService], providers: [SyncService],

View File

@@ -2,22 +2,25 @@ import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule'; import { Cron } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm'; import { Repository } from 'typeorm';
import { SyncLog, SyncState } from '../entities'; import { SyncLog, SyncState, UserDingMapping } from '../entities';
import type { SyncPlatform, SyncType, SyncStatus } from '../entities/sync-log.entity'; import type { SyncPlatform, SyncType, SyncStatus } from '../entities/sync-log.entity';
import { DingTalkService } from '../integration/dingtalk.service'; import { DingTalkService } from '../integration/dingtalk.service';
import { WeComService } from '../integration/wecom.service'; import { WeComService } from '../integration/wecom.service';
import { AttendanceImportService } from '../attendance/attendance-import.service';
@Injectable() @Injectable()
export class SyncService { export class SyncService {
private readonly logger = new Logger(SyncService.name); private readonly logger = new Logger(SyncService.name);
constructor( constructor(
@InjectRepository(SyncLog) @InjectRepository(SyncLog)
private readonly syncLogRepo: Repository<SyncLog>, private readonly syncLogRepo: Repository<SyncLog>,
@InjectRepository(SyncState) @InjectRepository(SyncState)
private readonly syncStateRepo: Repository<SyncState>, private readonly syncStateRepo: Repository<SyncState>,
@InjectRepository(UserDingMapping)
private readonly mappingRepo: Repository<UserDingMapping>,
private readonly dingTalkService: DingTalkService, private readonly dingTalkService: DingTalkService,
private readonly weComService: WeComService, private readonly weComService: WeComService,
private readonly attendanceImportService: AttendanceImportService,
) {} ) {}
// ── Scheduled cron: daily at 2 AM ── // ── Scheduled cron: daily at 2 AM ──
@@ -151,9 +154,44 @@ export class SyncService {
await this.syncLogRepo.save(log); await this.syncLogRepo.save(log);
} }
private async performDingTalkSync(_lastSyncAt: Date | null): Promise<number> { private async performDingTalkSync(lastSyncAt: Date | null): Promise<number> {
// Stage 1: Sync departments and users
const result = await this.dingTalkService.syncAll(); const result = await this.dingTalkService.syncAll();
return result.deptCount + result.userCount; let total = result.deptCount + result.userCount;
// Stage 2: Import attendance data (last 7 days or since last sync)
try {
const endDate = new Date();
const startDate = new Date();
// If never synced, import last 7 days; otherwise import since last sync
if (lastSyncAt) {
startDate.setTime(lastSyncAt.getTime());
} else {
startDate.setDate(startDate.getDate() - 7);
}
const start = startDate.toISOString().slice(0, 10);
const end = endDate.toISOString().slice(0, 10);
this.logger.log(`Importing DingTalk attendance: ${start} ~ ${end}`);
const mappings = await this.mappingRepo.find();
const userIds = mappings.map((m) => m.dingUserId).filter(Boolean);
const importResult = await this.attendanceImportService.importFromDingTalk({
startDate: start,
endDate: end,
userIds: userIds.length > 0 ? userIds : undefined,
autoMatch: true,
});
total += importResult.imported;
this.logger.log(`DingTalk attendance import: ${importResult.imported} imported, ${importResult.skipped} skipped`);
} catch (err: unknown) {
// Attendance import failure should not block the sync
const msg = err instanceof Error ? err.message : String(err);
this.logger.warn(`DingTalk attendance import failed (non-fatal): ${msg}`);
}
return total;
} }
private async performWeComSync(_lastSyncAt: Date | null): Promise<number> { private async performWeComSync(_lastSyncAt: Date | null): Promise<number> {