Skip to content

Commit

Permalink
children edit after confirmed
Browse files Browse the repository at this point in the history
  • Loading branch information
ehsan-g committed Jul 17, 2024
1 parent ac3e4b9 commit 0c7af49
Show file tree
Hide file tree
Showing 8 changed files with 254 additions and 37 deletions.
14 changes: 14 additions & 0 deletions src/db/migrations/1721217801774-new.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class New1721217801774 implements MigrationInterface {
name = 'New1721217801774'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE UNIQUE INDEX "IDX_903eafd5f6dc9f1179d176d437" ON "children_pre_register_entity" ("flaskChildId") `);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP INDEX "public"."IDX_903eafd5f6dc9f1179d176d437"`);
}

}
1 change: 1 addition & 0 deletions src/entities/childrenPreRegister.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export class ChildrenPreRegisterEntity extends BaseEntity {
@Column({ nullable: true })
birthPlaceId: number;

@Index({ unique: true })
@Column({ nullable: true })
flaskChildId: number;

Expand Down
196 changes: 176 additions & 20 deletions src/features/children/children.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { UserService } from '../user/user.service';
import {
CreateFlaskChildDto,
PreparePreRegisterChildDto,
UpdateApprovedPreRegisterDto,
UpdatePreRegisterChildDto,
} from 'src/types/dtos/CreateChild.dto';
import { ValidateChildTsPipe } from './pipes/validate-child.ts/validate-child.ts.pipe';
Expand Down Expand Up @@ -64,6 +65,7 @@ import { checkIfFileOrDirectoryExists, moveFile } from 'src/utils/file';
import fs from 'fs';
import { CampaignService } from '../campaign/campaign.service';
import { File } from '@web-std/file';
import { ChildrenPreRegisterEntity } from 'src/entities/childrenPreRegister.entity';

@ApiTags('Children')
@ApiSecurity('flask-access-token')
Expand Down Expand Up @@ -548,6 +550,142 @@ export class ChildrenController {
}
}

@ApiOperation({
description: 'update pre register',
})
@Patch(`preregister/update-approved/:flaskChildId`)
@UsePipes(new ValidationPipe())
async preRegisterUpdateApproved(
@Param('flaskChildId') flaskChildId: number,
@Req() req: Request,
) {
const panelFlaskUserId = req.headers['panelFlaskUserId'];
const panelFlaskTypeId = req.headers['panelFlaskTypeId'];
if (
!isAuthenticated(panelFlaskUserId, panelFlaskTypeId) ||
!(
panelFlaskTypeId === FlaskUserTypesEnum.SOCIAL_WORKER ||
panelFlaskTypeId === FlaskUserTypesEnum.NGO_SUPERVISOR ||
panelFlaskTypeId === FlaskUserTypesEnum.SUPER_ADMIN ||
panelFlaskTypeId === FlaskUserTypesEnum.ADMIN
)
) {
throw new ForbiddenException('You Are not the Super admin');
}
let preRegister: ChildrenPreRegisterEntity;
try {
const flaskChild = await this.childrenService.getFlaskChild(flaskChildId);
preRegister = await this.childrenService.getChildrenPreRegisterByFlaskId(
flaskChildId,
);
if (!preRegister) {
preRegister = await this.childrenService.createPreRegisterChild(
flaskChild.awakeAvatarUrl,
flaskChild.sleptAvatarUrl,
{
fa: flaskChild.sayname_translations.fa,
en: flaskChild.sayname_translations.en,
},
flaskChild.gender === false ? SexEnum.FEMALE : SexEnum.MALE,
);
console.log(preRegister);
}
const preRegisterDetails = {
birthDate: new Date(flaskChild.birthDate),
firstName: {
fa: flaskChild.firstName_translations.fa,
en: flaskChild.firstName_translations.en,
},
lastName: {
fa: flaskChild.lastName_translations.fa,
en: flaskChild.lastName_translations.en,
},
sayName: {
fa: flaskChild.sayname_translations.fa,
en: flaskChild.sayname_translations.en,
},
birthPlaceId: Number(flaskChild.nationality),
phoneNumber: flaskChild.phoneNumber,
address: flaskChild.address,
country: Number(flaskChild.country),
city: Number(flaskChild.country),
state: Number(flaskChild.city),
awakeUrl: flaskChild.awakeAvatarUrl,
sleptUrl: flaskChild.sleptAvatarUrl,
voiceUrl: flaskChild.voiceUrl,
sex: flaskChild.gender === false ? SexEnum.FEMALE : SexEnum.MALE,
bio: {
fa: flaskChild.bio_translations.fa,
en: flaskChild.bio_translations.en,
},
housingStatus: Number(flaskChild.housingStatus),
educationLevel: Number(flaskChild.education),
familyCount: Number(flaskChild.familyCount),
};
console.log('\x1b[36m%s\x1b[0m', 'Updating the preRegister ...\n');

await this.childrenService.preRegisterUpdateApproved(
flaskChildId,
preRegister.id,
preRegisterDetails,
);

preRegister = await this.childrenService.getChildrenPreRegisterByFlaskId(
flaskChildId,
);
console.log(preRegister);
console.log('preRegister--------------------');

const childDetails = {
flaskId: flaskChild.id,
sayName: flaskChild.sayname_translations.en,
sayNameTranslations: flaskChild.sayname_translations,
nationality: flaskChild.nationality,
country: flaskChild.country,
city: flaskChild.city,
awakeAvatarUrl: flaskChild.awakeAvatarUrl,
sleptAvatarUrl: flaskChild.sleptAvatarUrl,
adultAvatarUrl: flaskChild.adult_avatar_url,
bioSummaryTranslations: flaskChild.bio_summary_translations,
bioTranslations: flaskChild.bio_translations,
voiceUrl: flaskChild.voiceUrl,
birthPlace: flaskChild.birthPlace,
housingStatus: flaskChild.housingStatus,
familyCount: flaskChild.familyCount,
sayFamilyCount: flaskChild.sayFamilyCount,
education: flaskChild.education,
created: flaskChild.created,
updated: flaskChild.updated,
isDeleted: flaskChild.isDeleted,
isConfirmed: flaskChild.isConfirmed,
flaskConfirmUser: flaskChild.confirmUser,
confirmDate: flaskChild.confirmDate,
existenceStatus: flaskChild.existence_status,
generatedCode: flaskChild.generatedCode,
isMigrated: flaskChild.isMigrated,
migratedId: flaskChild.migratedId,
birthDate: flaskChild.birthDate && new Date(flaskChild.birthDate),
migrateDate: flaskChild.migrateDate && new Date(flaskChild.migrateDate),
};

const nestChild = await this.childrenService.getChildById(flaskChildId);
console.log(
'\x1b[36m%s\x1b[0m',
'Updated the preRegister, Now updating Nest child ...\n',
);

if (!nestChild) {
throw new ServerError('Hmmm... No child was found', 500);
} else if (nestChild && nestChild.updated !== flaskChild.updated) {
await this.childrenService.updateChild(childDetails, nestChild).then();
console.log('\x1b[36m%s\x1b[0m', 'Child updated ...\n');
}
return preRegister;
} catch (e) {
throw new ServerError(e.message, e.status);
}
}

@ApiOperation({
description: 'update pre register',
})
Expand All @@ -570,26 +708,6 @@ 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 Expand Up @@ -712,6 +830,44 @@ export class ChildrenController {
return await this.childrenService.getFlaskActiveChildren();
}

@ApiOperation({
description: 'update child',
})
@Patch(`flaskChildId=:flaskChildId`)
@UseInterceptors(FileInterceptor('voiceFile', voiceStorage))
@UsePipes(new ValidationPipe())
async updateChild(
@Req() req: Request,
@UploadedFile() voiceFile: Express.Multer.File,
@Body() body,
) {
const panelFlaskUserId = req.headers['panelFlaskUserId'];
const panelFlaskTypeId = req.headers['panelFlaskTypeId'];
if (
!isAuthenticated(panelFlaskUserId, panelFlaskTypeId) &&
!(
panelFlaskTypeId === FlaskUserTypesEnum.SUPER_ADMIN ||
panelFlaskTypeId === FlaskUserTypesEnum.ADMIN
)
) {
throw new ForbiddenException('You Are not the Super admin');
}
let theVoiceFile: File;
if (voiceFile) {
const fileBuffer = await fs.promises.readFile(
`uploads/children/voices/${voiceFile.filename}`,
);

theVoiceFile = new File([fileBuffer], `${voiceFile.filename}`, {
type: voiceFile.mimetype,
});
}
console.log(body);
console.log(theVoiceFile);

return theVoiceFile;
}

@Get(`check/names/:newName/:lang`)
@ApiOperation({ description: 'Check similar names' })
async checkChildrenNames(
Expand Down
15 changes: 14 additions & 1 deletion src/features/children/children.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { NeedSummary } from 'src/types/interfaces/Need';
import {
ChildParams,
PreRegisterChildPrepareParams,
PreRegisterChildUpdateApprovedParams,
PreRegisterChildUpdateParams,
createFlaskChildParams,
} from 'src/types/parameters/ChildParameters';
Expand Down Expand Up @@ -205,6 +206,17 @@ export class ChildrenService {
);
}

preRegisterUpdateApproved(
flaskChildId: number,
theId: string,
childDetails: PreRegisterChildUpdateApprovedParams,
): Promise<UpdateResult> {
return this.preRegisterChildrenRepository.update(
{ id: theId },
{ flaskChildId, ...childDetails },
);
}

createChild(
childDetails: ChildParams,
ngo: NgoEntity,
Expand Down Expand Up @@ -314,7 +326,8 @@ export class ChildrenService {
options,
queryBuilder,
{
sortableColumns: ['createdAt'],
defaultSortBy: [['createdAt', 'DESC']],
sortableColumns: ['id'],
nullSort: 'last',
},
);
Expand Down
2 changes: 1 addition & 1 deletion src/features/sync/sync.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ export class SyncService {
),
);
console.log('\x1b[36m%s\x1b[0m', 'Created a Child ...\n');
} else if (nestChild && nestChild.updated === flaskNeed.updated) {
} else if (nestChild && nestChild.updated !== flaskChild.updated) {
await this.childrenService.updateChild(childDetails, nestChild).then();
nestChild = await this.childrenService.getChildById(childId);

Expand Down
37 changes: 26 additions & 11 deletions src/types/dtos/CreateChild.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,32 @@ import {
SexEnum,
} from '../interfaces/interface';

export class CreateChildrenDto {
/**
* @memberof SwmypageInner
*/
id?: number;
sayName?: string;
firstName?: string;
lastName?: string;
birthDate?: string;
awakeAvatarUrl?: string;
export class UpdateApprovedPreRegisterDto {
addedState: number;
id: number;
id_ngo: number;
id_social_worker: number;
firstName_translations: { en: string; fa: string };
lastName_translations: { en: string; fa: string };
sayname_translations: { en: string; fa: string };
phoneNumber: string;
nationality: string;
country: number;
city: number;
awakeAvatarUrl: string;
sleptAvatarUrl: string;
gender: boolean;
bio_translations: { en: string; fa: string };
bio_summary_translations: { en: string; fa: string };
sayFamilyCount: number;
voiceUrl: string;
birthPlace: Date;
birthDate: Date;
address: string;
housingStatus: HousingEnum;
familyCount: number;
education: EducationEnum;
avatarUrl: string;
}

export class CreateFlaskChildDto {
Expand Down Expand Up @@ -64,7 +80,6 @@ export class PreparePreRegisterChildDto {
swId: number;
}


export class UpdatePreRegisterChildDto {
flaskChildId: number;
@IsNotEmpty()
Expand Down
4 changes: 0 additions & 4 deletions src/types/interfaces/Children.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import { EducationEnum, HousingEnum } from './interface';
export class CreateChildrenDto {
childData: Children[];
}


export class ChildrenData {
totalCount: number;
Expand Down
22 changes: 22 additions & 0 deletions src/types/parameters/ChildParameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
HousingEnum,
PreRegisterStatusEnum,
SchoolTypeEnum,
SexEnum,
} from '../interfaces/interface';

export type ChildParams = {
Expand Down Expand Up @@ -93,3 +94,24 @@ export type PreRegisterChildUpdateParams = {
firstName: { fa: string; en: string };
lastName: { fa: string; en: string };
};

export type PreRegisterChildUpdateApprovedParams = {
awakeUrl: string;
sleptUrl: string;
sayName: { fa: string; en: string };
firstName: { fa: string; en: string };
lastName: { fa: string; en: string };
bio: { fa: string; en: string };
birthDate: Date;
birthPlaceId: number;
city: number;
state: number;
country: number;
sex: SexEnum;
educationLevel: EducationEnum;
housingStatus: HousingEnum;
address: string;
familyCount: number;
phoneNumber: string;
voiceUrl: string;
};

0 comments on commit 0c7af49

Please sign in to comment.