import { map } from 'modern-async'; import { DB } from 'lib/DB'; import { Global } from '@nextgenleads/dnc'; import { Log } from 'lib/Log'; import { ServerError, Status } from 'nice-grpc'; const log = Log.child({ module: 'grpc', service: 'Global', method: 'append', }); export async function append(request: Global.AppendRequest): Promise { if (!Array.isArray(request.dncs) || !request.dncs.every((dnc) => dnc.phone_number)) { throw new ServerError(Status.INVALID_ARGUMENT, 'Missing required argument'); } let created_count = 0; let duplicate_count = 0; try { const results = await map(request.dncs, async (dnc) => { const decoded = Global.decodeAppendRequestDNCRequest(dnc); // NOTE: We need to know if _any_ DNC exists then upsert from there // as a duplicate will be created for the record const any_exists = await DB.DNC.findOne({ where: { company_id: null, phone_number: dnc.phone_number, }, }); const [record, created] = await DB.DNC.upsert({ phone_number: dnc.phone_number, source_code: dnc.source_code, vertical_id: decoded.vertical_id, state: decoded.state, }); let created_count = 0; let duplicate_count = 0; if (any_exists || !created) { await DB.Duplicate.create({ DNCId: record.id, }); duplicate_count += 1; } else { created_count += 1; } return { created_count, duplicate_count }; }); const aggregate = results.reduce( (acc, result) => { acc.created_count += result.created_count; acc.duplicate_count += result.duplicate_count; return acc; }, { created_count: 0, duplicate_count: 0 } ); created_count += aggregate.created_count; duplicate_count += aggregate.duplicate_count; } catch (err) { log.error('Failed to append to DNC', err); } log.info('Created %d DNC records (%d duplicate)', created_count, duplicate_count); return { created_count, duplicate_count }; }