feat: show this month's birthdays and send a greeting SMS

Each owner sees their customers born this Jalali month and can text a custom greeting.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-10-13 19:55:11 +03:30
co-authored by Cursor
parent cf326d1ed9
commit 13ee70764b
9 changed files with 556 additions and 3 deletions
+70
View File
@@ -0,0 +1,70 @@
import { jalaliMonthName, toJalali } from '../common/jalali';
export const BIRTHDAY_SMS_DEFAULT = '{نام} عزیز، تولدتان مبارک.';
export type BirthdayRow = {
id: string;
firstName: string;
lastName: string;
mobile: string | null;
birthDate: Date;
};
export type BirthdayPick = {
id: string;
firstName: string;
lastName: string;
mobile: string | null;
day: number;
};
export function fillBirthdaySmsText(template: string, firstName: string, lastName: string) {
const name = `${firstName} ${lastName}`.trim().replace(/\s+/g, ' ');
return template.replaceAll('{نام}', name).replaceAll('{name}', name).trim();
}
function tehranJalali(d: Date) {
const [gy, gm, gd] = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Tehran',
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
.format(d)
.split('-')
.map(Number);
return toJalali(gy, gm, gd);
}
function birthJalali(d: Date) {
return toJalali(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate());
}
/** متولدین ماه جاری تهران. پیش‌نمایش فقط روزهای امروز و بعد است. */
export function selectMonthBirthdays(people: BirthdayRow[], now = new Date(), previewLimit = 6) {
const today = tehranJalali(now);
const matched = people.flatMap((person) => {
const birth = birthJalali(person.birthDate);
if (birth.jm !== today.jm) return [];
return [
{
id: person.id,
firstName: person.firstName,
lastName: person.lastName,
mobile: person.mobile,
day: birth.jd,
},
];
});
const byDay = (a: BirthdayPick, b: BirthdayPick) => a.day - b.day || a.firstName.localeCompare(b.firstName, 'fa');
const upcoming = matched.filter((row) => row.day >= today.jd).sort(byDay);
const passed = matched.filter((row) => row.day < today.jd).sort(byDay);
return {
month: today.jm,
monthName: jalaliMonthName(today.jm),
today: today.jd,
total: matched.length,
preview: upcoming.slice(0, previewLimit),
items: [...upcoming, ...passed],
};
}
+2 -1
View File
@@ -8,6 +8,7 @@ import { CompaniesService } from './companies.service';
import { PeopleController } from './people.controller';
import { PeopleService } from './people.service';
import { ContactsExcelService } from './contacts-excel.service';
import { SmsService } from '../common/sms.service';
@Module({
imports: [
@@ -17,7 +18,7 @@ import { ContactsExcelService } from './contacts-excel.service';
PublicApiModule,
],
controllers: [PeopleController, CompaniesController],
providers: [PeopleService, CompaniesService, ContactsExcelService],
providers: [PeopleService, CompaniesService, ContactsExcelService, SmsService],
exports: [PeopleService, CompaniesService],
})
export class ContactsModule {}
+7
View File
@@ -17,6 +17,13 @@ import {
} from 'class-validator';
import { PERSON_IMPORT_SOURCES, PERSON_MOODS } from '@mento/shared';
export class BirthdaySmsDto {
@IsString()
@MinLength(1)
@MaxLength(500)
text!: string;
}
export class BulkDeletePeopleDto {
@IsArray()
@ArrayMinSize(1)
+15 -1
View File
@@ -22,7 +22,7 @@ import { CurrentUser } from '../auth/current-user.decorator';
import type { Actor } from '../common/record-scope';
import { OrgModuleGuard } from '../billing/org-module.guard';
import { RequireOrgModule } from '../billing/org-module.decorator';
import { BulkDeletePeopleDto, CreatePersonDto, ListQueryDto, UpdatePersonDto } from './dto';
import { BirthdaySmsDto, BulkDeletePeopleDto, CreatePersonDto, ListQueryDto, UpdatePersonDto } from './dto';
import { PeopleService } from './people.service';
import { ContactsExcelService } from './contacts-excel.service';
import { brand } from '@mento/shared';
@@ -105,6 +105,20 @@ export class PeopleController {
});
}
@Get('birthdays')
birthdays(@CurrentUser() user: Actor) {
return this.peopleService.birthdaysThisMonth(user);
}
@Post(':id/birthday-sms')
birthdaySms(
@CurrentUser() user: Actor,
@Param('id') id: string,
@Body() dto: BirthdaySmsDto,
) {
return this.peopleService.sendBirthdaySms(user, id, dto.text);
}
@Get(':id')
get(@CurrentUser() user: Actor, @Param('id') id: string) {
return this.peopleService.get(user, id);
+107
View File
@@ -1,8 +1,11 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
Injectable,
Logger,
NotFoundException,
ServiceUnavailableException,
type OnModuleInit,
} from '@nestjs/common';
import type {
@@ -35,6 +38,8 @@ import { MessageAutomationsService } from '../message-automations/message-automa
import { WebhooksService } from '../public-api/webhooks.service';
import { GamificationService } from '../gamification/gamification.service';
import { parseBirthDate } from '../common/excel';
import { SmsService } from '../common/sms.service';
import { fillBirthdaySmsText, selectMonthBirthdays } from './birthday-month';
import { normalizeTags } from '../common/tags';
import { buildSearchWhere, ci } from '../common/search';
import {
@@ -97,6 +102,7 @@ export class PeopleService implements OnModuleInit {
private readonly messageAutomations: MessageAutomationsService,
private readonly webhooks: WebhooksService,
private readonly game: GamificationService,
private readonly sms: SmsService,
) {}
async list(
@@ -447,6 +453,107 @@ export class PeopleService implements OnModuleInit {
throw new ConflictException('شخص تکراری است');
}
async birthdaysThisMonth(actor: Actor) {
const rows = await this.prisma.person.findMany({
where: {
organizationId: actor.organizationId,
ownerId: actor.userId,
birthDate: { not: null },
},
select: {
id: true,
firstName: true,
lastName: true,
mobile: true,
phone: true,
birthDate: true,
},
});
const selected = selectMonthBirthdays(
rows.flatMap((row) =>
row.birthDate
? [
{
id: row.id,
firstName: row.firstName,
lastName: row.lastName,
mobile: row.mobile || row.phone,
birthDate: row.birthDate,
},
]
: [],
),
);
const toItem = (row: (typeof selected.items)[number]) => ({
id: row.id,
firstName: row.firstName,
lastName: row.lastName,
fullName: `${row.firstName} ${row.lastName}`.trim(),
mobile: row.mobile,
day: row.day,
});
return {
month: selected.month,
monthName: selected.monthName,
today: selected.today,
total: selected.total,
preview: selected.preview.map(toItem),
items: selected.items.map(toItem),
};
}
async sendBirthdaySms(actor: Actor, personId: string, text: string) {
const body = text.trim();
if (!body || body.length > 500) {
throw new BadRequestException('متن پیامک را تا ۵۰۰ نویسه بنویسید.');
}
const person = await this.prisma.person.findFirst({
where: { id: personId, organizationId: actor.organizationId },
select: {
id: true,
firstName: true,
lastName: true,
mobile: true,
phone: true,
ownerId: true,
birthDate: true,
},
});
if (!person) throw new NotFoundException('مشتری پیدا نشد');
if (person.ownerId !== actor.userId) {
throw new ForbiddenException('فقط مسئول این مشتری می‌تواند پیامک تبریک بفرستد.');
}
if (!person.birthDate) {
throw new BadRequestException('برای این مشتری تاریخ تولد ثبت نشده است.');
}
const inMonth = selectMonthBirthdays(
[
{
id: person.id,
firstName: person.firstName,
lastName: person.lastName,
mobile: person.mobile || person.phone,
birthDate: person.birthDate,
},
],
);
if (!inMonth.total) {
throw new BadRequestException('تولد این مشتری در ماه جاری نیست.');
}
const mobile = person.mobile || person.phone;
if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.');
const message = fillBirthdaySmsText(body, person.firstName, person.lastName);
const result = await this.sms.sendSmsDetailed(mobile, message);
if (!result.ok) {
throw new ServiceUnavailableException(
result.reason === 'SMS not configured'
? 'ارسال پیامک روی سرور فعال نیست.'
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
);
}
return { ok: true };
}
private toDto(row: PersonRow): PersonDto {
const previousFullName = `${row.previousFirstName ?? ''} ${row.previousLastName ?? ''}`.trim();
const importSource = row.importSource || 'manual';