Skip to content

Commit

Permalink
arrivals sms
Browse files Browse the repository at this point in the history
  • Loading branch information
ehsan-g committed Jul 15, 2024
1 parent db553e4 commit aeabda7
Show file tree
Hide file tree
Showing 5 changed files with 95 additions and 21 deletions.
63 changes: 56 additions & 7 deletions src/features/campaign/campaign.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,14 +252,14 @@ export class CampaignService {

async sendSwAnnounceReminder() {
function findSwById(
objects: { swId: number; counter: number }[],
objects: { swId: number; eligible: number; total: number }[],
id: number,
): { swId: number; counter: number } {
): { swId: number; eligible: number; total: number } {
return objects.find((object) => object.swId === id);
}
try {
const list: [{ swId: number; counter: number }] = [
{ swId: 0, counter: 0 },
const list: [{ swId: number; eligible: number; total: number }] = [
{ swId: null, eligible: null, total: null },
];
const needs = await this.needService.getArrivalUpdateCandidates();
console.log(`Number of needs: ${needs[1]}`);
Expand All @@ -285,20 +285,69 @@ export class CampaignService {
) {
console.log(`Adding need: ${need.id} Sw Id: ${need.created_by_id}`);

let foundObject: { counter: any; swId: number };
let foundObject: { swId: number; eligible: number; total: any };
if (!list || list.length < 1) {
foundObject = null;
} else {
foundObject = findSwById(list, need.created_by_id);
}
if (foundObject) {
foundObject.counter++;
foundObject.total++;
let isEligible: boolean;
if (need.type === NeedTypeEnum.PRODUCT) {
isEligible =
daysDifference(need.expected_delivery_date, new Date()) > 1;
}
if (need.type === NeedTypeEnum.SERVICE) {
isEligible =
daysDifference(need.expected_delivery_date, new Date()) > 1;
}
isEligible && foundObject.eligible++;
} else {
list.push({ swId: need.created_by_id, counter: 1 });
let isEligible: boolean;
if (need.type === NeedTypeEnum.PRODUCT) {
isEligible =
daysDifference(need.expected_delivery_date, new Date()) > 1;
}
if (need.type === NeedTypeEnum.SERVICE) {
isEligible =
daysDifference(need.expected_delivery_date, new Date()) > 1;
}

list.push({
swId: need.created_by_id,
eligible: isEligible ? 1 : 0,
total: 1,
});
}
}
}
}
let once = true;
list.forEach(async (object) => {
if (object.swId) {
const sw = await this.userService.getFlaskSocialWorker(object.swId);
const to = sw.phone_number;
const from = process.env.SMS_FROM;

const text = `سلام ${sw.firstName}،\nدر حال حاضر ${object.eligible} از ${object.total} نیاز ثبت شده توسط شما در انتظار <<اعلام رسیدن>> هستند.\n لطفا وارد پنل شوید و از ستون سوم صفحه من در پنل، نیاز را پیدا کنید و از طریق منوی هر یک از نیازها گزینه اعلام رسیدن را انتخاب کنید.\n در صورتی که کالا یا مبلغ به شما تحویل داده نشده است، لطفا تیکتی جدید به نیاز اضافه کنید. \n با احترام، \n SAY \nپنل: https://panel.saydao.org \n لغو۱۱`;

await this.smsRest.send(to, from, text);
console.log(to);
console.log(from);
console.log(text);
if (once) {
once = false;
await this.smsRest.send(
process.env.SAY_ADMIN_SMS,
from,
'just sent the arrival updates!',
);
sleep(2000);
}
console.log('------------------------\n');
}
});
console.log(list);
} catch (e) {
console.log(e);
Expand Down
23 changes: 21 additions & 2 deletions src/features/children/children.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export class ChildrenController {

@UsePipes(new ValidationPipe()) // validation for dto files
@Patch(`preregister/approve/:id`)
@ApiOperation({ description: 'Delete a pre register' })
@ApiOperation({ description: 'Approve a pre register' })
@UseInterceptors(FileInterceptor('voiceFile', voiceStorage))
async approvePreregister(
@Req() req: Request,
Expand Down Expand Up @@ -546,7 +546,26 @@ export class ChildrenController {
) {
throw new ForbiddenException('You Are not the Super admin');
}

// if(body.flaskChildId>0){
// const token =
// config().dataCache.fetchPanelAuthentication(panelFlaskUserId).token;
// const configs = {
// headers: {
// 'Content-Type': 'multipart/form-data',
// Authorization: token,
// processData: false,
// contentType: false,
// },
// };
// const formData = new FormData();
// formData.append('ngo_id', String(preRegister.flaskNgoId));
// // create flask child
// const { data } = await axios.post(
// 'https://api.sayapp.company/api/v2/child/add/',
// formData,
// configs,
// );
// }
try {
return await this.childrenService.preRegisterUpdate(body.id, {
bio: { fa: body.bio, en: '' },
Expand Down
2 changes: 1 addition & 1 deletion src/features/need/need.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ export class NeedController {
`Last prepare: ${
toBeConfirmed.createdAt &&
timeDifference(toBeConfirmed.createdAt, new Date()).mm
} ago`,
} minutes ago`,
);

if (expired) {
Expand Down
27 changes: 16 additions & 11 deletions src/features/schedule/schedule.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,18 +128,18 @@ export class ScheduleService {
}

// ERROR [Scheduler] ServerError: Can't send mail - all recipients were rejected: 550 <[email protected]> No such user here
@Cron('37 17 * * Sun', {
name: 'MonthlyCampaigns try At 17:37 on Sunday.', // we try every week and only send to those who did not receive (because their child have no needs, etc.)
@Cron('00 17 * * Sun', {
name: 'MonthlyCampaigns try At 17:00 on Sunday.', // we try every week and only send to those who did not receive (because their child have no needs, etc.)
timeZone: 'Asia/Tehran',
})
async handleMonthlyCampaignsCron() {
const farsiDay = persianDay(new Date());
// if (farsiDay > 20) {
// this.logger.warn(
// `We are near the end of this month let's skip one more week`,
// );
// return;
// }
if (farsiDay > 20) {
this.logger.warn(
`We are near the end of this month let's skip one more week`,
);
return;
}
// ############## BE CAREFUL #################
if (process.env.NODE_ENV === 'production') {
this.logger.debug(
Expand All @@ -160,11 +160,16 @@ export class ScheduleService {
}
}

@Timeout(5000)
@Cron('30 9 * * Wed', {
name: 'Reminders to announce arrivals At 09:30 on Wednesday.',
timeZone: 'Asia/Tehran',
})
async handleAnnounceArrivalCron() {
if (process.env.NODE_ENV === 'production') {
// this.logger.debug('Sending Reminder to Social workers to announce arrivals');
// await this.campaignService.sendSwAnnounceReminder();
this.logger.debug(
'Sending Reminder to Social workers to announce arrivals',
);
await this.campaignService.sendSwAnnounceReminder();
}
}
// @Cron('30 8 * * Sat', {
Expand Down
1 change: 1 addition & 0 deletions src/types/dtos/CreateChild.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export class PreparePreRegisterChildDto {


export class UpdatePreRegisterChildDto {
flaskChildId: number;
@IsNotEmpty()
id: string;
@IsNotEmpty()
Expand Down

0 comments on commit aeabda7

Please sign in to comment.