123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246 |
- import { api } from "#api/current-api.js";
- import { Request, Response } from "express";
- import sessionService from "./auth/services/session-service.js";
- import { cCustomFieldsValidateService } from "../custom-fields/c-cf-validate-service.js";
- import { cUsersService } from "./c-users-service.js";
- import { ApiError } from "#exceptions/api-error.js";
- import { v7 as uuidv7 } from "uuid";
- import { updPool } from "#db";
- import { sql } from "slonik";
- import { RouterUtils } from "#utils/router-utils.js";
- class ChildrenController {
- async createChild(req: Request, res: Response) {
- const { fields } = api.client.users.POST_Child.req.formData.body.parse(
- JSON.parse(req.body.body),
- );
- const event = await sessionService.getCurrentEventFromReq(req);
- const files = req.files;
- const user = sessionService.getUserFromReq(req);
- // поля пользователя
- const userData = await cUsersService.getUserEventFieldsWithValidators(
- event.eventId,
- );
- const refFields = userData.map((f) => {
- // TODO: костылёк для возраста ребенка
- if (f.code === "birth-date") {
- return {
- ...f,
- idKey: "userEfId",
- validators: f.validators.filter((v) => v.code !== "minAge"),
- };
- }
- return {
- ...f,
- idKey: "userEfId",
- };
- });
- // валидация полей
- const validationResult =
- await cCustomFieldsValidateService.processAndValidateFields({
- inputFields: fields,
- referenceFields: refFields,
- files,
- idKey: "userEfId",
- addOldValue: false,
- });
- if (!validationResult.isValid)
- throw ApiError.BadRequest(
- "fieldsValidationFailed",
- JSON.stringify(validationResult.messages),
- );
- const validatedFields = validationResult.checkedfields;
- // вставляем в базу и сохраняем файлы
- const childId = uuidv7();
- await updPool.transaction(async (tr) => {
- await tr.query(
- sql.unsafe`
- insert into usr.users
- (user_id, is_child, parent_id)
- values
- (${childId}, true, ${user.userId})`,
- );
- await cCustomFieldsValidateService.saveCustomFieldValuesInTransaction({
- tr,
- parentId: childId,
- action: "userProfile",
- inputFields: validatedFields,
- files,
- isDeleteBefore: false,
- });
- });
- RouterUtils.validAndSendResponse(api.client.users.POST_Child.res, res, {
- code: "success",
- childId: childId,
- });
- }
- async patchChild(req: Request, res: Response) {
- const user = sessionService.getUserFromReq(req);
- const { fields } = api.client.users.PATCH_Child.req.formData.body.parse(
- JSON.parse(req.body.body),
- );
- const childId = api.client.users.PATCH_Child.req.params.childId.parse(
- req.params.childId,
- );
- const event = await sessionService.getCurrentEventFromReq(req);
- const files = req.files;
- const isChildParent = await cUsersService.checkChildParent({
- userId: user.userId,
- childId,
- });
- if (!isChildParent) {
- throw ApiError.ForbiddenError();
- }
- const userData =
- await cUsersService.getUserEventFieldsWithValuesAndValidators(
- event.eventId,
- childId,
- );
- const refFields = userData
- .map((f) => {
- // TODO: костылёк для возраста ребенка
- if (f.code === "birth-date") {
- return {
- ...f,
- idKey: "userEfId",
- validators: f.validators.filter((v) => v.code !== "minAge"),
- };
- }
- return {
- ...f,
- idKey: "userEfId",
- };
- })
- // только изменяемые
- .filter((f) => fields.some((ff) => ff.userEfId === f.userEfId));
- // валидация
- const validationResult =
- await cCustomFieldsValidateService.processAndValidateFields({
- inputFields: fields,
- referenceFields: refFields,
- files,
- idKey: "userEfId",
- addOldValue: true,
- });
- if (!validationResult.isValid)
- throw ApiError.BadRequest(
- "fieldsValidationFailed",
- JSON.stringify(validationResult.messages),
- );
- const validatedFields = validationResult.checkedfields;
- //
- //
- // вставляем в базу и сохраняем файлы
- await updPool.transaction(async (tr) => {
- await cCustomFieldsValidateService.saveCustomFieldValuesInTransaction({
- tr,
- parentId: childId,
- action: "userProfile",
- inputFields: validatedFields,
- files,
- isDeleteBefore: true,
- });
- });
- RouterUtils.validAndSendResponse(
- api.client.users.PATCH_UserEventData.res,
- res,
- { code: "success" },
- );
- }
- async getChildren(req: Request, res: Response) {
- const user = sessionService.getUserFromReq(req);
- const children = await cUsersService.getChildrens(user.userId);
- RouterUtils.validAndSendResponse(api.client.users.GET_Children.res, res, {
- code: "success",
- children: [...children],
- });
- }
- async getChild(req: Request, res: Response) {
- const user = sessionService.getUserFromReq(req);
- const event = await sessionService.getCurrentEventFromReq(req);
- const { childId } = api.client.users.GET_Child.req.params.parse(req.params);
- const isChildParent = await cUsersService.checkChildParent({
- userId: user.userId,
- childId,
- });
- if (!isChildParent) {
- throw ApiError.ForbiddenError();
- }
- const childFields = await cUsersService.getUserEventFieldsWithValues(
- event.eventId,
- childId,
- );
- RouterUtils.validAndSendResponse(api.client.users.GET_Child.res, res, {
- code: "success",
- userData: {
- fields: [...childFields],
- },
- });
- }
- async getChildForPatch(req: Request, res: Response) {
- const user = sessionService.getUserFromReq(req);
- const event = await sessionService.getCurrentEventFromReq(req);
- const childId = api.client.users.GET_ChildForPatch.req.params.childId.parse(
- req.params.childId,
- );
- const isChildParent = await cUsersService.checkChildParent({
- userId: user.userId,
- childId,
- });
- if (!isChildParent) {
- throw ApiError.ForbiddenError();
- }
- const childFields =
- await cUsersService.getUserEventFieldsWithValuesAndValidators(
- event.eventId,
- childId,
- );
- RouterUtils.validAndSendResponse(
- api.client.users.GET_ChildForPatch.res,
- res,
- {
- code: "success",
- userData: {
- fields: [...childFields],
- },
- },
- );
- }
- }
- export const childrenController = new ChildrenController();
|