experience.js 11.5 KB
"use strict";
const utils = require("@strapi/utils");
const { ApplicationError, ValidationError } = utils.errors;
/**
 * experience controller
 */

const { createCoreController } = require("@strapi/strapi").factories;

module.exports = createCoreController("api::experience.experience", () => ({
  async create(ctx) {
    // Validations
    if (!ctx.request.body.data.vendor) {
      throw new ValidationError("Vendor is a mandatory field.");
    }
    if (!ctx.request.body.data.pincode) {
      throw new ValidationError("Pincode is a mandatory field.");
    }
    if (!ctx.request.body.data.subCategory) {
      throw new ValidationError("Subcategory is a mandatory field");
    }
    if (!ctx.request.body.data.category) {
      throw new ValidationError("Category is a mandatory field");
    }
    const subCategory = await strapi
      .query("api::sub-categorie.sub-categorie")
      .findOne({
        where: {
          name: {
            $eq: ctx.request.body.data.subCategory,
          },
        },
      });

    const category = await strapi.query("api::categorie.categorie").findOne({
      where: {
        name: {
          $eq: ctx.request.body.data.category,
        },
      },
    });

    const repeatedActivities = await strapi
      .query("api::experience.experience")
      .findOne({
        where: {
          $and: [
            { name: ctx.request.body.data.name },
            { vendor: ctx.request.body.data.vendor.id },
          ],
        },
      });

    if (repeatedActivities) {
      throw new ValidationError(
        "Activity with the same name already exists, please rename the activity."
      );
    }
    let finalImageArray = [];

    for (
      let index = 0;
      index < ctx.request.body.data.imagesComponent.length;
      index++
    ) {
      const element = ctx.request.body.data.imagesComponent[index];
      console.log("here >", element);
      finalImageArray = [...finalImageArray, { image: element }];
      console.log("final array", finalImageArray);
    }

    // ctx.request.body.data.imagesComponent;
    // Create Activity
    const activity = await strapi.entityService.create(
      "api::experience.experience",
      {
        data: {
          name: ctx.request.body.data.name,
          description: ctx.request.body.data.description,
          pricePerPerson: ctx.request.body.data.pricePerPerson,
          address: ctx.request.body.data.address,
          masterPincode: ctx.request.body.data.pincode.id,
          minimumDuration: ctx.request.body.data.minimumDuration,
          maximumDuration: ctx.request.body.data.maximumDuration,
          duration: ctx.request.body.data.duration,
          ageLowerLimit: ctx.request.body.data.ageLowerLimit,
          ageNotes: ctx.request.body.data.ageNotes,
          phoneNumber: ctx.request.body.data.phoneNumber,
          minGroupSize: ctx.request.body.data.minGroupSize,
          maxGroupSize: ctx.request.body.data.maxGroupSize,
          activityType: ctx.request.body.data.activityType,
          link: ctx.request.body.data.link,
          cancellationPolicy: ctx.request.body.data.cancellationPolicy,
          vendor: ctx.request.body.data.vendor.id,
          subCategory: subCategory.id,
          category: category.id,
          giftSomeone: ctx.request.body.data.giftSomeone,
          fromDate: ctx.request.body.data.fromDate,
          toDate: ctx.request.body.data.toDate,
          fromTime: ctx.request.body.data.fromTime,
          toTime: ctx.request.body.data.toTime,
          offers: ctx.request.body.data.offers,
          rating: ctx.request.body.data.rating,
          contactPersonForActivity:
            ctx.request.body.data.contactPersonForActivity,
          contactPersonForBooking:
            ctx.request.body.data.contactPersonForBooking,
          approved: ctx.request.body.data.approved,
          imagesComponent: finalImageArray,
          // imagesComponent: finalImageArray,
          ...ctx.request.body.data.daysBoolean,
          image: ctx.request.body.data.image,
          termsConditions: ctx.request.body.data.termsConditions,
        },
      }
    );

    ctx.send({
      success: true,
      message: "Activity Created",
      data: {
        ...activity,
      },
    });
  },

  async update(ctx) {
    const { id } = ctx.params;

    // if (!ctx.request.body.data.vendor) {
    //   throw new ValidationError("Vendor is a mandatory field.");
    // }
    if (
      ctx.request.body.data.approved == "approved" ||
      ctx.request.body.data.approved == "rejected"
    ) {
      const updatedExperience = await strapi
        .query("api::experience.experience")
        .update({
          where: { id },
          data: {
            approved: ctx.request.body.data.approved,
            rejectionReason: ctx.request.body.data.rejectionReason,
          },
        });
      console.log("updatedExperience", updatedExperience);
      return ctx.send({
        success: true,
        message: "Status updated",
        data: {
          ...updatedExperience,
        },
      });
    }
    console.log("ctx>", ctx.request.body);
    if (!ctx.request.body.data.pincode) {
      throw new ValidationError("Pincode is a mandatory field.");
    }
    if (!ctx.request.body.data.subCategory) {
      throw new ValidationError("Subcategory is a mandatory field");
    }
    if (!ctx.request.body.data.category) {
      throw new ValidationError("Category is a mandatory field");
    }
    console.log("subcategoyr", ctx.params);
    console.log(
      "ctx.request.body.data.imagesComponent",
      ctx.request.body.data.imagesComponent,
      ctx.request.body.data.imagesComponent.length
    );
    let finalImageArray = [];
    for (
      let index = 0;
      index < ctx.request.body.data.imagesComponent.length;
      index++
    ) {
      const element = ctx.request.body.data.imagesComponent[index];
      console.log("element", element);
      finalImageArray = [...finalImageArray, { image: element }];
      console.log("final", finalImageArray);
    }
    const subCategory = await strapi
      .query("api::sub-categorie.sub-categorie")
      .findOne({
        where: {
          name: {
            $eq: ctx.request.body.data.subCategory,
          },
        },
      });
    const category = await strapi.query("api::categorie.categorie").findOne({
      where: {
        name: {
          $eq: ctx.request.body.data.category,
        },
      },
    });
    console.log(
      "ctx.request.body.data.activityId",
      ctx.request.body.data.activityId
    );

    const updatedExperience = await strapi.entityService.update(
      "api::experience.experience",
      id,
      {
        data: {
          name: ctx.request.body.data.name,
          description: ctx.request.body.data.description,
          pricePerPerson: ctx.request.body.data.pricePerPerson,
          address: ctx.request.body.data.address,
          masterPincode: ctx.request.body.data.pincode.id,
          minimumDuration: ctx.request.body.data.minimumDuration,
          maximumDuration: ctx.request.body.data.maximumDuration,
          duration: ctx.request.body.data.duration,
          ageLowerLimit: ctx.request.body.data.ageLowerLimit,
          ageNotes: ctx.request.body.data.ageNotes,
          phoneNumber: ctx.request.body.data.phoneNumber,
          minGroupSize: ctx.request.body.data.minGroupSize,
          maxGroupSize: ctx.request.body.data.maxGroupSize,
          activityType: ctx.request.body.data.activityType,
          link: ctx.request.body.data.link,
          cancellationPolicy: ctx.request.body.data.cancellationPolicy,
          subCategory: subCategory.id,
          category: category.id,
          giftSomeone: ctx.request.body.data.giftSomeone,
          fromDate: ctx.request.body.data.fromDate,
          toDate: ctx.request.body.data.toDate,
          fromTime: ctx.request.body.data.fromTime,
          toTime: ctx.request.body.data.toTime,
          offers: ctx.request.body.data.offers,
          rating: ctx.request.body.data.rating,
          contactPersonForActivity:
            ctx.request.body.data.contactPersonForActivity,
          contactPersonForBooking:
            ctx.request.body.data.contactPersonForBooking,
          imagesComponent: finalImageArray,
          approved: ctx.request.body.data.approved,
          ...ctx.request.body.data.daysBoolean,
          image: ctx.request.body.data.image,
          termsConditions: ctx.request.body.data.termsConditions,
        },
      }
    );

    console.log(
      "ctx.request.body.data.imagesArrayComponent",
      ctx.request.body.data.imagesComponent
    );
    // const imagesComponentData = Array.isArray(
    //   ctx.request.body.data.imagesArrayComponent
    // )
    //   ? ctx.request.body.data.imagesArrayComponent
    //   : [ctx.request.body.data.imagesArrayComponent];
    // console.log("imagesComponentData >", imagesComponentData);
    // const updatedExperienceImageComponent = await strapi.entityService.update(
    //   "api::experience.experience",
    //   id,
    //   {
    //     data: { imagesComponent: ctx.request.body.data.imagesComponent },
    //   }
    // );
    console.log("updatedExperience", updatedExperience);
    ctx.send({
      success: true,
      message: "Activity updated",
      data: {
        ...updatedExperience,
      },
    });
  },

  async updateImage(ctx) {
    console.log(ctx.request.body);

    const id = ctx.request.body.id; // Get the ID of the experience entry
    if (!id) {
      return ctx.notFound("Please mention experience ID");
    }
    if (!ctx.request.body.newComponentData > 0) {
      return ctx.notFound("Please mention the URLs");
    }
    const newComponentData = ctx.request.body.newComponentData; // Get the new data for the repeatable component
    try {
      const existingExperience = await strapi.entityService.findOne(
        "api::experience.experience",
        id
      );

      if (!existingExperience) {
        return ctx.notFound("Experience with the given ID not found.");
      }

      // Clear the existing repeatable component data
      await strapi.entityService.update("api::experience.experience", id, {
        data: { imagesComponent: [] },
      });
      // Update the entry with new data
      const updatedExperience = await strapi.entityService.update(
        "api::experience.experience",
        id,
        {
          data: { imagesComponent: newComponentData },
        }
      );

      return ctx.send(updatedExperience);
    } catch (error) {
      ctx.throw(500, error);
    }
  },

  async getSearchResponse(ctx) {
    const string = ctx.request.body.string;
    console.log("str", ctx.request.body.string);
    if (!string.length > 0) {
      return ctx.notFound("Please pass a valid string");
    }
    const activities = await strapi.db
      .query("api::experience.experience")
      .findMany({
        where: {
          $and: [
            {
              name: {
                $contains: string,
              },
            },
            { approved: { $eq: "approved" } },
          ],
        },
      });
    const categories = await strapi.db
      .query("api::categorie.categorie")
      .findMany({
        where: {
          name: {
            $contains: string,
          },
        },
      });
    console.log("activities", activities);
    console.log("categories", categories);
    let responseData = {};
    responseData["categories"] = categories?.map((item) => {
      return { id: item.id, name: item.name };
    });

    responseData["activities"] = activities?.map((item) => {
      return { id: item.id, name: item.name };
    });

    return ctx.send({
      success: true,
      data: responseData,
    });
  },
}));