Browse Source

Добавлена поддержка файлов

Vadim 3 months ago
parent
commit
bdee4de986

+ 2 - 1
.gitignore

@@ -1,4 +1,5 @@
 node_modules
 logs
 .dev.env
-.env
+.env
+files

+ 62 - 76
src/modules/client/users/c-users-controller.ts

@@ -1,19 +1,14 @@
-// db
-import { selPool, updPool } from "#db";
-import { DbSchema } from "#db-schema";
-import { sql } from "slonik";
-
 // api
 import { api } from "#api";
 
-// other
-import { z } from "zod";
-
 import { RouterUtils } from "#utils/router-utils.js";
 
 import { Request, Response } from "express";
 import sessionService from "#modules/users/auth/services/session-service.js";
-import { Validator } from "#api/v_0.1.0/types/pe-types.js";
+import { cCustomFieldsValidateService } from "../custom-fields/c-cf-validate-service.js";
+import { ApiError } from "#exceptions/api-error.js";
+import { cUsersService } from "./c-users-service.js";
+import { updPool } from "#db/db.js";
 
 class ClientUsersController {
   async getUserEventData(
@@ -24,47 +19,19 @@ class ClientUsersController {
     const event = await sessionService.getCurrentEventFromReq(req);
     const user = sessionService.getUserFromReq(req);
 
-    const userData = await selPool.any(sql.type(
-      z.object({
-        fieldDefinitionId: DbSchema.cf.customFieldDefinitions.fieldDefinitionId,
-        userEfId: DbSchema.ev.userEventFields.userEfId,
-        code: DbSchema.cf.customFieldDefinitions.code,
-        fieldTypeCode: DbSchema.cf.fieldTypes.code,
-        title: DbSchema.cf.customFieldDefinitions.title,
-        mask: DbSchema.cf.customFieldDefinitions.mask,
-        options: DbSchema.cf.customFieldDefinitions.options,
-        validators: z.array(Validator),
-        value: DbSchema.ev.userEventFieldValues.value,
-      }),
-    )`
-      select
-        uef.field_definition_id as "fieldDefinitionId",
-        uef.user_ef_id as "userEfId",
-        cfwv.code,
-        cfwv.field_type_code as "fieldTypeCode",
-        COALESCE(uef.field_title_override, cfwv.title) as "title",
-        cfwv.mask,
-        cfwv."options",
-        cfwv.validators,
-        uefv.value as "value"
-      from
-        ev.user_event_fields uef
-      join cf.custom_fields_with_validators cfwv on
-        uef.field_definition_id = cfwv.field_definition_id
-      left join ev.user_event_field_values uefv on
-        uef.user_ef_id = uefv.user_ef_id 
-        and uefv.user_id = ${user.userId}
-      where
-        uef.event_id = ${event.eventId}
-
-    `);
+    const userData = await cUsersService.getUserEventDataWithValues(
+      event.eventId,
+      user.userId,
+    );
 
     RouterUtils.validAndSendResponse(
       api.client.users.GET_UserEventData.res,
       res,
       {
         code: "success",
-        userData: [...userData],
+        userData: {
+          fields: [...userData],
+        },
       },
     );
   }
@@ -75,40 +42,59 @@ class ClientUsersController {
     // next: NextFunction
   ) {
     const user = sessionService.getUserFromReq(req);
-    const { userData } = api.client.users.PATCH_UserEventData.req.parse(
-      req.body,
-    );
+    const { fields } =
+      api.client.users.PATCH_UserEventData.req.formData.body.parse(
+        JSON.parse(req.body.body),
+      );
 
+    const event = await sessionService.getCurrentEventFromReq(req);
     const userId = user.userId;
-    // TODO: добавить валидацию
-    updPool.transaction(async (t) => {
-      for (const field of userData) {
-        const userEfId = field.userEfId;
-        const value = field.value;
-
-        t.query(sql.unsafe`
-            delete from
-              ev.user_event_field_values v
-            where
-              v.user_ef_id = ${userEfId}
-              and 
-              v.user_id = ${userId};
-          `);
-
-        t.query(sql.unsafe`
-            insert
-              into
-              ev.user_event_field_values (
-              user_id,
-              user_ef_id,
-              value)
-            values (
-              ${userId},
-              ${userEfId},
-              ${value}
-            );
-          `);
-      }
+
+    const files = req.files;
+
+    const userData = await cUsersService.getUserEventDataWithValues(
+      event.eventId,
+      user.userId,
+    );
+
+    const refFields = userData
+      .map((f) => ({
+        ...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: userId,
+        action: "userProfile",
+        inputFields: validatedFields,
+        files,
+        isDeleteBefore: true,
+      });
     });
 
     RouterUtils.validAndSendResponse(

+ 2 - 0
src/modules/client/users/c-users-router.ts

@@ -2,6 +2,7 @@ import { RouterUtils } from "#utils/router-utils.js";
 
 import express from "express";
 import { clientUsersController } from "./c-users-controller.js";
+import { upload } from "#utils/files-utils.js";
 const router = express.Router();
 export default router;
 
@@ -12,6 +13,7 @@ router.get(
 
 router.patch(
   "/userEventData",
+  upload.any(),
   RouterUtils.asyncHandler(clientUsersController.patchUserEventData),
 );
 

+ 36 - 0
src/modules/client/users/c-users-service.ts

@@ -0,0 +1,36 @@
+import { CustomFieldWithValidatorsAndValue } from "#api/v_0.1.0/types/custom-fields-types.js";
+import { DbSchema } from "#db/db-schema.js";
+import { selPool } from "#db/db.js";
+import { sql } from "slonik";
+
+class CUsersService {
+  async getUserEventDataWithValues(eventId: string, userId: string) {
+    return await selPool.any(sql.type(
+      CustomFieldWithValidatorsAndValue.extend({
+        userEfId: DbSchema.ev.userEventFields.userEfId,
+      }),
+    )`
+          select
+            uef.field_definition_id as "fieldDefinitionId",
+            uef.user_ef_id as "userEfId",
+            cfwv.code,
+            cfwv.field_type_code as "fieldTypeCode",
+            COALESCE(uef.field_title_override, cfwv.title) as "title",
+            cfwv.mask,
+            cfwv."options",
+            cfwv.validators,
+            uefv.value as "value"
+          from
+            ev.user_event_fields uef
+          join cf.custom_fields_with_validators cfwv on
+            uef.field_definition_id = cfwv.field_definition_id
+          left join ev.user_event_field_values uefv on
+            uef.user_ef_id = uefv.user_ef_id 
+            and uefv.user_id = ${userId}
+          where
+            uef.event_id = ${eventId}
+        `);
+  }
+}
+
+export const cUsersService = new CUsersService();