index
int64
0
0
repo_id
stringclasses
87 values
file_path
stringlengths
41
143
content
stringlengths
6
1.82M
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/post/post.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Attachment } from 'src/models/attachment.model'; import { Comment } from 'src/models/comment.model'; import { CommentReply } from 'src/models/commentReply.model'; import { Like } from 'src/models/like.model'; import { Post } from 'src/models/post.model'; import { Repost } from 'src/models/repost.model'; import { PostController } from './post.controller'; import { PostService } from './post.service'; import { User } from 'src/models/user.model'; import { Retailer } from 'src/models/retailer.model'; import { Brand } from 'src/models/brand.model'; @Module({ imports: [ SequelizeModule.forFeature([ Post, Attachment, Repost, Comment, CommentReply, Like, User, Brand, Retailer, ]), ], controllers: [PostController], providers: [PostService, MailServiceService], }) export class PostModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/post/post.controller.ts
import { Body, Controller, Delete, Get, Param, Post, Query, Request, UploadedFiles, UseGuards, UseInterceptors, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { FilesInterceptor } from '@nestjs/platform-express'; import { diskStorage } from 'multer'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { IResponse } from 'src/common/interfaces/response.interface'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { CreatePostDto } from './dto/create-post.dto'; import { CreateRepostDto } from './dto/create-re-post.dto'; import { GetPostDto } from './dto/get-posts-dto'; import { PostService } from './post.service'; import path = require('path'); export const uploadFiles = { storage: diskStorage({ destination: '../assets/postedMedia', filename: (req, file, cb) => { //console.log(file.originalname); let filename: string = path.parse('file-').name.replace(/\s/g, '') + Date.now() + '-' + Math.round(Math.random() * 1e9); filename = filename; const extension: string = path.parse(file.originalname).ext; cb(null, `${filename}${extension}`); }, }), }; @Controller() export class PostController { constructor(private readonly postService: PostService) {} //@UseGuards(AuthGuard('jwt')) @UseGuards(JwtAuthGuard) @Post() async getPosts( @Body() getPostDto: GetPostDto, @Request() req, ): Promise<IResponse> { const posts = await this.postService.getPosts(getPostDto, req.user); return new ResponseSuccess('Posts', posts); } @UseGuards(AuthGuard('jwt')) @Get(':userId') async getUserPosts(@Param('userId') userId: string): Promise<IResponse> { const userPosts = await this.postService.getUserPosts(+userId); return new ResponseSuccess('Posts', userPosts); } @UseGuards(AuthGuard('jwt')) @Post('activity') @UseInterceptors(FilesInterceptor('attachment', null, uploadFiles)) async createPost( @Body() createPostDto: CreatePostDto, @Request() req, @UploadedFiles() files: Array<Express.Multer.File>, ): Promise<IResponse> { const isCreated = await this.postService.createPost( createPostDto, req.user, files, ); return new ResponseSuccess('Post successfully.', isCreated); } @UseGuards(AuthGuard('jwt')) @Post('repost') async createRepost( @Body() createRepostDto: CreateRepostDto, @Request() req, ): Promise<IResponse> { const isCreated = await this.postService.createRepost( createRepostDto, req.user, ); return new ResponseSuccess('Repost successfully.', isCreated); } @UseGuards(AuthGuard('jwt')) @Get(':pId/reposts') async getReposts( @Param('pId') postUniqueId: string, @Query('page') page: string, @Query('limit') limit: string, @Request() req, ): Promise<IResponse> { const reposts = await this.postService.getReposts( postUniqueId, page, limit, req.user, ); return new ResponseSuccess('Reposts', reposts); } @UseGuards(AuthGuard('jwt')) @Get(':pId/likes') async getLikes( @Param('pId') postUniqueId: string, @Query('page') page: string, @Query('limit') limit: string, @Request() req, ): Promise<IResponse> { const likes = await this.postService.getLikes( postUniqueId, page, limit, req.user, ); return new ResponseSuccess('Likes', likes); } @UseGuards(AuthGuard('jwt')) @Post('/handlePostLike') async handlePostLike( @Body('pId') postId: string, @Request() req, ): Promise<IResponse> { const like = await this.postService.handlePostLike(+postId, req.user); return new ResponseSuccess('post liked', like); } @UseGuards(JwtAuthGuard) @Get('single/:postUniqueId') async getSingle( @Param('postUniqueId') postUniqueId: string, // @Query('page') page: string, // @Query('limit') limit: string, @Request() req, ): Promise<IResponse> { const post = await this.postService.getSingle(postUniqueId, req.user); return new ResponseSuccess('Single post', [post]); } @UseGuards(JwtAuthGuard) @Post('axis-point') async getAxisPointPost( @Body('limit') limit: string, @Body('page') page: string, @Request() req, ): Promise<IResponse> { const posts = await this.postService.getAxisPointPosts( +limit, +page, req.user, ); return new ResponseSuccess('Posts', posts); } @UseGuards(JwtAuthGuard) @Delete() async deletePost(@Request() req, @Body('id') id: number) { const deletedPost = await this.postService.deletePost(req.user, id); return new ResponseSuccess('Post deleted successfully.', deletedPost); } @UseGuards(AuthGuard('jwt')) @Post('users') async getUser( @Body('keyword') keyword: string, @Body('limit') limit: string, @Body('page') page: string, ): Promise<IResponse> { const posts = await this.postService.getUsers(keyword, +limit, +page); return new ResponseSuccess('users', posts); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules/post
/content/gmx-projects/gmx-admin/backend/src/modules/post/dto/create-post.dto.ts
import { IsNotEmpty, IsOptional } from 'class-validator'; export class CreatePostDto { @IsNotEmpty() type: string; @IsOptional() post: string; @IsOptional() mentions: string; @IsOptional() attachableType: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/post
/content/gmx-projects/gmx-admin/backend/src/modules/post/dto/create-re-post.dto.ts
import { IsNotEmpty, IsOptional } from 'class-validator'; export class CreateRepostDto { @IsNotEmpty() type: number; @IsOptional() post: string; @IsOptional() mentions: string; @IsNotEmpty() repostId: number; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/post
/content/gmx-projects/gmx-admin/backend/src/modules/post/dto/get-posts-dto.ts
import { IsNotEmpty } from 'class-validator'; export class GetPostDto { @IsNotEmpty() type: string; @IsNotEmpty() slug: string; @IsNotEmpty() page: string; @IsNotEmpty() limit: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/contact-us/contact-us.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { ContactUsService } from './contact-us.service'; describe('ContactUsService', () => { let service: ContactUsService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ContactUsService], }).compile(); service = module.get<ContactUsService>(ContactUsService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/contact-us/contact-us.service.ts
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import sequelize from 'sequelize'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Settings } from 'src/models/settings.model'; import { HelperService } from 'src/services/Helper.service'; import { ContactUsDTO } from './dto/contactUs.dto'; @Injectable() export class ContactUsService { constructor( @InjectModel(Settings) private settingsModel: typeof Settings, private mailService?: MailServiceService, ) {} async postContactUs(contactUsDTO: ContactUsDTO) { const helperService = await new HelperService(); const userData = { NAME: contactUsDTO.firstName, }; const retailerEmailContent = await helperService.emailTemplateContent( 4, userData, ); this.mailService.sendMail( contactUsDTO.email, retailerEmailContent.subject, retailerEmailContent.body, ); const adminData = { FIRST_NAME: contactUsDTO.firstName, LAST_NAME: contactUsDTO.lastName, EMAIL: contactUsDTO.email, PHONE_NUMBER: contactUsDTO.phoneNumber, MESSAGE: contactUsDTO.message, }; const adminEmailContent = await helperService.emailTemplateContent( 3, adminData, ); const adminEmail = await helperService.getSettings( this.settingsModel, 'info_email', ); this.mailService.sendMail( adminEmail.description, adminEmailContent.subject, adminEmailContent.body, ); return adminEmail; } async findAll() { const settings = await this.settingsModel.findAll({ where: { name: { [sequelize.Op.not]: 'stripe_secret_key' } }, }); return settings; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/contact-us/contact-us.controller.ts
import { Body, Controller, Post } from '@nestjs/common'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { IResponse } from 'src/common/interfaces/response.interface'; import { ContactUsService } from './contact-us.service'; import { ContactUsDTO } from './dto/contactUs.dto'; @Controller() export class ContactUsController { constructor(private readonly contactUsService: ContactUsService) {} @Post() async postContactUs(@Body() contactUs: ContactUsDTO): Promise<IResponse> { const isLinkSend = await this.contactUsService.postContactUs(contactUs); return new ResponseSuccess( 'We will review your message and come back to you shortly. Thank you for reaching out to String. We look forward to connecting soon.', isLinkSend, ); } @Post('/settings') async findAll() { const settings = await this.contactUsService.findAll(); return new ResponseSuccess('Setting details', settings); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/contact-us/contact-us.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Settings } from 'src/models/settings.model'; import { ContactUsController } from './contact-us.controller'; import { ContactUsService } from './contact-us.service'; @Module({ imports: [SequelizeModule.forFeature([Settings])], controllers: [ContactUsController], providers: [ContactUsService, MailServiceService], }) export class ContactUsModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/contact-us/contact-us.controller.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { ContactUsController } from './contact-us.controller'; import { ContactUsService } from './contact-us.service'; describe('ContactUsController', () => { let controller: ContactUsController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [ContactUsController], providers: [ContactUsService], }).compile(); controller = module.get<ContactUsController>(ContactUsController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); });
0
/content/gmx-projects/gmx-admin/backend/src/modules/contact-us
/content/gmx-projects/gmx-admin/backend/src/modules/contact-us/dto/contactUs.dto.ts
import { IsEmail, IsNotEmpty, IsString, Length } from 'class-validator'; export class ContactUsDTO { @IsNotEmpty() @IsString() @Length(1, 255) firstName: string; @IsNotEmpty() @IsString() @Length(1, 255) lastName: string; @IsNotEmpty() @IsEmail() @Length(1, 255) email: string; @IsNotEmpty() phoneNumber: number; @IsNotEmpty() @IsString() message: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/drivers/drivers.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { Drivers } from 'src/models/drivers.model'; import { DriversController } from './drivers.controller'; import { DriversService } from './drivers.service'; @Module({ imports: [SequelizeModule.forFeature([Drivers])], controllers: [DriversController], providers: [DriversService], }) export class DriversModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/drivers/drivers.service.ts
import { Injectable, NotFoundException, UnprocessableEntityException, } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Drivers } from 'src/models/drivers.model'; import { JwtUserDTO } from '../auth/dto/JwtUser.dto'; import { CreateDriverDto } from './dto/create-driver.dto'; import { UpdateDriverDto } from './dto/update-driver.dto'; @Injectable() export class DriversService { constructor( @InjectModel(Drivers) private driversModel: typeof Drivers, ) {} async getAllDrivers( jwtUserDTO: JwtUserDTO, offset = 0, limit = 10, status = 0, ) { let condition = {}; if (status) { condition = { isActive: '1' }; } const { count, rows: drivers } = await this.driversModel.findAndCountAll({ where: { userId: jwtUserDTO.id, ...condition }, order: [['createdAt', 'desc']], }); return { count: count, currentPage: offset ? +offset : 0, totalPages: Math.ceil(count / limit), drivers: drivers, }; } async createDriver(jwtUserDTO: JwtUserDTO, createDriverDto: CreateDriverDto) { const emailExist = await this.driversModel.findOne({ where: { email: createDriverDto.email, }, }); if (emailExist) { throw new UnprocessableEntityException( 'Email already exist, Please try another.', ); } const drivers = await this.driversModel.create({ userId: jwtUserDTO.id, transporterName: createDriverDto.transporterName, driversName: createDriverDto.driversName, cannabisIndustryLicense: createDriverDto.cannabisIndustryLicense, phoneNumber: createDriverDto.phoneNumber, email: createDriverDto.email, }); return drivers; } async findOne(jwtUserDTO: JwtUserDTO, id: string) { const driver = await this.driversModel.findOne({ where: { id, userId: jwtUserDTO.id }, }); if (!driver) throw new NotFoundException(); return driver; } async updateDriver( jwtUserDTO: JwtUserDTO, id: string, updateDriverDto: UpdateDriverDto, ) { const driver = await this.driversModel.findOne({ where: { id, userId: jwtUserDTO.id }, }); if (!driver) throw new NotFoundException(); driver.update({ transporterName: updateDriverDto.transporterName, driversName: updateDriverDto.driversName, cannabisIndustryLicense: updateDriverDto.cannabisIndustryLicense, phoneNumber: updateDriverDto.phoneNumber, email: updateDriverDto.email, }); return driver; } async changeDriverStatus(id: number) { const driver = await this.driversModel.findOne({ where: { id: id }, }); if (!driver) throw new NotFoundException('Driver Not Found'); const updatedDriver = await driver.update({ isActive: +driver.isActive === 1 ? '2' : '1', }); return updatedDriver; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/drivers/drivers.controller.ts
import { Body, Controller, Get, Param, Post, Put, Query, Request, UseGuards, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { IResponse } from 'src/common/interfaces/response.interface'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { DriversService } from './drivers.service'; import { CreateDriverDto } from './dto/create-driver.dto'; import { UpdateDriverDto } from './dto/update-driver.dto'; @UseGuards(JwtAuthGuard) @Controller() export class DriversController { constructor(private readonly driversService: DriversService) {} @UseGuards(AuthGuard('jwt')) @Get() async getAllDrivers( @Request() req, @Query('offset') offset: string, @Query('limit') limit: string, @Query('status') status: string, ): Promise<IResponse> { const drivers = await this.driversService.getAllDrivers( req.user, +offset, +limit, +status, ); return new ResponseSuccess('Drivers', drivers); } @UseGuards(AuthGuard('jwt')) @Post() async createDriver( @Request() req, @Body() createdriverDto: CreateDriverDto, ): Promise<IResponse> { const driver = await this.driversService.createDriver( req.user, createdriverDto, ); return new ResponseSuccess('Driver added successfully.', driver); } @UseGuards(AuthGuard('jwt')) @Get(':id') async findOne(@Request() req, @Param('id') id: string) { const product = await this.driversService.findOne(req.user, id); return new ResponseSuccess('Driver.', product); } @UseGuards(AuthGuard('jwt')) @Put(':id') async updateProduct( @Param('id') id: string, @Body() updateDriverDto: UpdateDriverDto, @Request() req, ): Promise<IResponse> { const driver = await this.driversService.updateDriver( req.user, id, updateDriverDto, ); return new ResponseSuccess('Driver updated successfully.', driver); } @UseGuards(AuthGuard('jwt')) @Post('change/status/:id') async changeDriverStatus(@Param('id') id: number): Promise<IResponse> { const updatedDriver = await this.driversService.changeDriverStatus(id); if (+updatedDriver.isActive === 1) { return new ResponseSuccess('Driver has been enabled', updatedDriver); } else { return new ResponseSuccess('Driver has been disabled', updatedDriver); } } }
0
/content/gmx-projects/gmx-admin/backend/src/modules/drivers
/content/gmx-projects/gmx-admin/backend/src/modules/drivers/dto/create-driver.dto.ts
import { IsNotEmpty } from 'class-validator'; export class CreateDriverDto { @IsNotEmpty() transporterName: string; @IsNotEmpty() driversName: string; @IsNotEmpty() cannabisIndustryLicense: string; @IsNotEmpty() phoneNumber: string; @IsNotEmpty() email: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/drivers
/content/gmx-projects/gmx-admin/backend/src/modules/drivers/dto/update-driver.dto.ts
import { IsNotEmpty, IsString } from 'class-validator'; export class UpdateDriverDto { @IsNotEmpty() @IsString() transporterName: string; @IsNotEmpty() driversName: string; @IsNotEmpty() cannabisIndustryLicense: string; @IsNotEmpty() phoneNumber: string; @IsNotEmpty() email: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/cart/cart.service.ts
import { ForbiddenException, Injectable, NotFoundException, } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Op } from 'sequelize'; import { Sequelize } from 'sequelize-typescript'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Cart } from 'src/models/cart.model'; import { Category } from 'src/models/category.model'; import { Offers } from 'src/models/offers.model'; import { Order } from 'src/models/order.model'; import { OrderInvoice } from 'src/models/orderInvoice.model'; import { Product } from 'src/models/product.model'; import { HelperService } from 'src/services/Helper.service'; import { JwtUserDTO } from '../auth/dto/JwtUser.dto'; import { Brand } from './../../models/brand.model'; import { User } from './../../models/user.model'; import { OrderInvoiceItems } from 'src/models/orderInvoiceItems.model'; import { Stores } from 'src/models/stores.model'; import { Retailer } from 'src/models/retailer.model'; const moment = require('moment'); const { FRONEND_BASE_URL } = process.env; @Injectable() export class CartService { constructor( @InjectModel(Cart) private cartModel: typeof Cart, @InjectModel(Product) private productModel: typeof Product, @InjectModel(Order) private orderModel: typeof Order, @InjectModel(OrderInvoice) private orderInvoiceModel: typeof OrderInvoice, @InjectModel(OrderInvoiceItems) private orderInvoiceItemsModel: typeof OrderInvoiceItems, @InjectModel(Stores) private StoresModel: typeof Stores, @InjectModel(Offers) private offersModel: typeof Offers, private mailService?: MailServiceService, ) {} async getCartItems(jwtUserDTO: JwtUserDTO) { const helperService = new HelperService(); const cartItems = []; let deal: any = {}; let orderTotal = 0; let discountTotal = 0; let finalOrderTotal = 0; const cart = await this.cartModel.findAll({ include: [ { model: Product, include: [ { model: Brand, attributes: ['id', 'brandName'], }, { model: Category, attributes: ['id', 'title'], }, ], attributes: [ 'id', 'title', 'unitPerPackage', 'price', 'productPrice', 'userId', 'brandCompanyId', 'brandId', 'strainId', ], }, ], where: { retailerId: jwtUserDTO.id, }, attributes: [ 'id', 'retailerId', 'brandCompanyId', 'brandId', 'productId', 'categoryId', 'quantity', ], }); const offerCondition = { retailerId: null, brandCompanyId: null, brandId: null, categories: [], products: [], totalQty: 0, }; if (cart.length > 0) { cart.map(async (item) => { offerCondition.brandCompanyId = item.brandCompanyId; offerCondition.brandId = item.brandId; offerCondition.retailerId = item.retailerId; offerCondition.categories.push(item.categoryId); offerCondition.products.push(item.productId); offerCondition.totalQty += item?.quantity; }); // // START OFFER // const discountDeal = await this.offersModel.findOne({ // //logging: console.log, // attributes: [ // 'id', // 'userId', // 'businessId', // 'title', // 'displayPrice', // 'price', // 'offerType', // 'orderType', // 'categories', // 'products', // 'retailers', // 'startDate', // 'endDate', // 'isInfinite', // ], // where: { // businessId: offerCondition.businessId, // offerType: 1, // categories: { // [Op.overlap]: offerCondition?.categories // ? offerCondition?.categories?.join(',') // : null, // }, // products: { // [Op.overlap]: offerCondition?.products // ? offerCondition?.products?.join(',') // : null, // }, // [Op.and]: Sequelize.literal( // `FIND_IN_SET(${offerCondition?.retailerId}, Offers.retailers) > 0`, // ), // [Op.or]: [ // { // isInfinite: 1, // startDate: { // [Op.lte]: moment().toISOString(), // }, // }, // { // isInfinite: null, // startDate: { // [Op.lte]: moment().toISOString(), // }, // endDate: { // [Op.gte]: moment().toISOString(), // }, // }, // ], // }, // order: [['price', 'desc']], // }); // const bulkOrderDeal = await this.offersModel.findOne({ // //logging: console.log, // attributes: [ // 'id', // 'userId', // 'businessId', // 'title', // 'displayPrice', // 'price', // 'offerType', // 'orderType', // 'minQty', // 'maxQty', // 'categories', // 'products', // 'retailers', // 'startDate', // 'endDate', // 'isInfinite', // ], // where: { // businessId: offerCondition.businessId, // offerType: 2, // categories: { // [Op.overlap]: offerCondition?.categories // ? offerCondition?.categories?.join(',') // : null, // }, // products: { // [Op.overlap]: offerCondition?.products // ? offerCondition?.products?.join(',') // : null, // }, // [Op.and]: Sequelize.literal( // `FIND_IN_SET(${offerCondition?.retailerId}, Offers.retailers) > 0`, // ), // minQty: { // [Op.lte]: offerCondition.totalQty, // }, // maxQty: { // [Op.gte]: offerCondition.totalQty, // }, // [Op.or]: [ // { // isInfinite: 1, // startDate: { // [Op.lte]: moment().toISOString(), // }, // }, // { // isInfinite: null, // startDate: { // [Op.lte]: moment().toISOString(), // }, // endDate: { // [Op.gte]: moment().toISOString(), // }, // }, // ], // }, // order: [['price', 'desc']], // }); // deal = discountDeal; // if (bulkOrderDeal?.price || 0 > discountDeal?.price || 0) { // let isDiscountDealHigher = // offerCondition.totalQty * discountDeal?.price || 0; // let isBulkOrderDealHigher = // offerCondition.totalQty * bulkOrderDeal?.price || 0; // if (discountDeal?.orderType == 2) { // isDiscountDealHigher = discountDeal?.price || 0; // } // if (bulkOrderDeal?.orderType == 2) { // isBulkOrderDealHigher = bulkOrderDeal?.price || 0; // } // if (isBulkOrderDealHigher > isDiscountDealHigher) { // deal = bulkOrderDeal; // } // } // // END OFFER } if (cart.length > 0) { cart.map(async (item) => { // const getCategory = // await helperService.commaSeparatedStringWithIncludes( // deal?.categories, // item.categoryId, // ); // const getProduct = await helperService.commaSeparatedStringWithIncludes( // deal?.products, // item.productId, // ); let discountAmount = 0; // if (deal?.orderType == 1 && getCategory && getProduct) { // discountAmount = item?.quantity * deal?.price || 0; // } const cartItem = { id: item?.id, retailerId: item?.retailerId, brandCompanyId: item?.brandCompanyId, brandId: item?.brandId, product: { id: item?.product?.id, title: item?.product?.title, unitPerPackage: item?.product?.unitPerPackage, price: item?.product?.price, productPrice: item?.product?.productPrice, category: { id: item?.product?.category?.id, title: item?.product?.category?.title, }, brand: { id: item?.product?.brand?.id, brandName: item?.product?.brand?.brandName, }, strainId: item?.product?.strainId, }, quantity: item.quantity, // ...(deal?.orderType == 1 && // getCategory && // getProduct && { deal: deal ? deal : null }), total: item?.product?.price * item.quantity, discountAmount: discountAmount, lineTotal: item?.product?.price * item.quantity - discountAmount, }; orderTotal += cartItem?.total; // START if the offer is not active finalOrderTotal = orderTotal; // END if the offer is not active // if (!deal) { // finalOrderTotal = orderTotal; // } // if (deal?.orderType == 1) { // discountTotal += discountAmount; // finalOrderTotal += cartItem.lineTotal; // } // if (deal?.orderType == 2) { // discountTotal = deal?.price; // finalOrderTotal += cartItem.lineTotal - discountTotal; // } cartItems.push(cartItem); }); } const cartData: any = await this.cartModel.findOne({ attributes: [ 'retailerId', 'brandCompanyId', 'brandId', [Sequelize.fn('sum', Sequelize.col('quantity')), 'totalItems'], ], where: { retailerId: jwtUserDTO.id, }, raw: true, }); // const businessId = // cartData.length && cartData[0].businessId ? cartData[0].businessId : ''; // const brand = await Brand.findOne({ // where: { id: businessId }, // attributes: ['id', 'orderAmount'], // }); const totalItems = cartData?.totalItems ? cartData?.totalItems : 0; // const brand = await Brand.findOne({ // where: { id: businessId }, // attributes: ['id', 'orderAmount'], // }); return { // brand: brand, // businessId: businessId, totalItems: totalItems, orderTotal: orderTotal, discountTotal: discountTotal, finalOrderTotal: finalOrderTotal, cartItems: cartItems, deal: deal, }; } async addItem(jwtUserDTO: JwtUserDTO, productSlug: string, quantity: number) { const product = await this.productModel.findOne({ where: { slug: productSlug }, }); if (!product) throw new NotFoundException('Product Not Found'); const existingItemInCart = await this.cartModel.findOne({ where: { retailerId: jwtUserDTO.id, productId: product.id, }, }); if (existingItemInCart) { let updatedQuantity; if (existingItemInCart.quantity === 99999) { throw new ForbiddenException( 'You have added maximum number of quantity of product, can not add more quantity now', ); } else if (existingItemInCart.quantity + quantity > 99999) { updatedQuantity = 99999; } else { updatedQuantity = existingItemInCart.quantity + quantity; } await existingItemInCart.update({ quantity: updatedQuantity, }); } else { await this.cartModel.create({ retailerId: jwtUserDTO.id, brandCompanyId: product.brandCompanyId, brandId: product.brandId, productId: product.id, categoryId: product.categoryId, quantity, }); } return this.getCartItems(jwtUserDTO); } async removeItem(jwtUserDTO: JwtUserDTO, cartId: number) { const item = await this.cartModel.findOne({ where: { id: cartId, retailerId: jwtUserDTO.id, }, }); if (!item) throw new NotFoundException(); await item.destroy(); return this.getCartItems(jwtUserDTO); } async orderRequest(jwtUserDTO: JwtUserDTO, orderData: any) { const helperService = new HelperService(); const cartItems = await this.cartModel.findAll({ include: [{ model: Product }], where: { retailerId: jwtUserDTO.id, }, }); const retailer = await User.findOne({ include: [ { model: Retailer, include: [ { model: Stores, attributes: ['id', 'managerName'] }, ] } ], where: { id: jwtUserDTO.id }, attributes: ['name'], }); const brand = await Brand.findOne({ where: { id: cartItems[0].brandId }, include: [{ model: User }], }); const blockRetailer = await helperService.commaSeparatedStringWithIncludes( brand.blockedRetailers, jwtUserDTO.id, ); if (blockRetailer) { throw new NotFoundException( 'You are blocked as a request order, You can select other brand products.', ); } if (brand.orderAmount > orderData.finalOrderTotal) { throw new NotFoundException( `The minimum order amount to place an order is $ ${brand.orderAmount}`, ); } if (!cartItems.length) throw new NotFoundException('No items found in cart'); const order = await this.orderModel.create({ retailerId: jwtUserDTO.id, totalProducts: cartItems.length, total: orderData.orderTotal, finalTotal: orderData.finalOrderTotal, }); for await (const item of orderData.cartItems) { if (item.quantity > 0) { const orderInvoice = await this.orderInvoiceModel.findOne({ where: { orderId: order?.id, retailerId: jwtUserDTO.id, brandCompanyId: item?.brandCompanyId}, }); if(!orderInvoice) { let store; if(orderData.storeId) { store = await this.StoresModel.findOne({ where: { id: orderData?.storeId, userId: jwtUserDTO?.id }, }); } else { store = await this.StoresModel.findOne({ where: { userId: jwtUserDTO?.id, isDefault: true }, }); } if(!store) { throw new NotFoundException( 'Delivery address not found.', ); } await this.orderInvoiceModel.create({ orderId: order.id, retailerId: item?.retailerId, brandCompanyId: item?.brandCompanyId, brandId: item?.brandId, paymentStatus: 2, storeId: store?.id, managerName: store?.managerName, phoneNumber: store?.phoneNumber, address: store?.address, stateId: store?.stateId, zipCode: store?.zipCode, licenseNumber: store?.licenseNumber, }); //invoiceId: order.id, // totalProducts // total } const orderInvoiceLatest = await this.orderInvoiceModel.findOne({ where: { orderId: order?.id, retailerId: jwtUserDTO.id, brandCompanyId: item?.brandCompanyId}, }); if(orderInvoiceLatest) { await this.orderInvoiceItemsModel.create({ orderId: order.id, orderInvoiceId: orderInvoiceLatest?.id, retailerId: item?.retailerId, brandCompanyId: item?.brandCompanyId, brandId: item?.brandId, productId: item?.product?.id, categoryId: item?.product?.category?.id, strainId: item?.product?.strainId, unitPerPackage: item?.product?.unitPerPackage, price: item?.product?.price, quantity: item.quantity, total: item?.total, finalTotal: item.lineTotal, status: 1, }); } } const cartItem = await this.cartModel.findOne({ where: { id: item?.id }, }); await cartItem.destroy(); } // Update order details await order.update({ orderId: 'ORD' + String(order.id).padStart(8, '0') }); // Update order invoice details const updateOrderInvoice = await this.orderInvoiceModel.findAll({ include: [ { model: OrderInvoiceItems, where: { status: 1 }, } ], where: { orderId: order?.id, retailerId: jwtUserDTO.id }, }); if(updateOrderInvoice) { for await (const itemInvoice of updateOrderInvoice) { let finalTotal = 0; for await (const itemInvoiceItems of itemInvoice?.orderInvoiceItems) { finalTotal += itemInvoiceItems.finalTotal; } const invoiceId = `INV${String(`${itemInvoice?.orderId}${itemInvoice?.id}`).padStart(8, '0')}`; await this.orderInvoiceModel.update( { invoiceId: invoiceId, totalProducts: `${itemInvoice?.orderInvoiceItems?.length}`, total: finalTotal, finalTotal: finalTotal, }, { where: { id:itemInvoice?.id, orderId: itemInvoice?.orderId, retailerId: jwtUserDTO.id }, }, ); // Invoice Received const brandEmail = await Brand.findOne({ include: [{ model: User }], where: { id: itemInvoice?.brandId } }); if(brandEmail) { const brandData = { INVOICE_ID: '#' + invoiceId, TITLE: 'You have received new Order', CUSTOMER: retailer?.retailerCompany?.store?.managerName, TOTAL: `$ ${finalTotal}`, LINK: FRONEND_BASE_URL + '/orders', }; const brandEmailContent = await helperService.emailTemplateContent( 8, brandData, ); this.mailService.sendMail( brandEmail?.user?.email, brandEmailContent.subject, brandEmailContent.body, ); } } } return true; } async updateItemQuantity( jwtUserDTO: JwtUserDTO, action: string, cartId: number, quantity: number, ) { const existCart = await this.cartModel.findOne({ where: { id: cartId, }, }); if (!existCart) throw new NotFoundException(); let updatedQuantity; if ( (action === 'decrement' && existCart.quantity > 1) || (action === 'increment' && existCart.quantity < 99999) || (action === 'manual' && existCart.quantity <= 99999) ) { if (action === 'manual') { updatedQuantity = quantity; } else { updatedQuantity = existCart.quantity + quantity; } await existCart.update({ quantity: updatedQuantity, }); } return { action, cartId, quantity: existCart.quantity }; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/cart/cart.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Cart } from 'src/models/cart.model'; import { Offers } from 'src/models/offers.model'; import { Order } from 'src/models/order.model'; import { OrderInvoice } from 'src/models/orderInvoice.model'; import { OrderInvoiceItems } from 'src/models/orderInvoiceItems.model'; import { Product } from 'src/models/product.model'; import { CartController } from './cart.controller'; import { CartService } from './cart.service'; import { Stores } from 'src/models/stores.model'; @Module({ imports: [ SequelizeModule.forFeature([Cart, Product, Order, OrderInvoice, OrderInvoiceItems, Offers, Stores]), ], controllers: [CartController], providers: [CartService, MailServiceService], }) export class CartModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/cart/cart.controller.ts
import { Body, Controller, Delete, Get, Post, Put, Request, UseGuards, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { CartService } from './cart.service'; @Controller() @UseGuards(AuthGuard('jwt')) export class CartController { constructor(private readonly cartService: CartService) {} @Get('/get-items') async getCartItems(@Request() req) { // await new Promise(f => setTimeout(f, 2000)); // for add delay in output const cartItems = await this.cartService.getCartItems(req.user); return new ResponseSuccess('cart items', cartItems); } @Post('/add-item') async addItem( @Request() req, @Body('productSlug') productSlug: string, @Body('quantity') quantity: string, ) { const addedItem = await this.cartService.addItem( req.user, productSlug, +quantity, ); return new ResponseSuccess('added item', addedItem); } @Delete('/remove-item') async removeItem(@Request() req, @Body('cartId') cartId: string) { const removedItemId = await this.cartService.removeItem(req.user, +cartId); return new ResponseSuccess('removed item', removedItemId); } @Post('/order-request') async orderRequest(@Request() req, @Body('order') order: any) { const requestedOrder = await this.cartService.orderRequest(req.user, order); return new ResponseSuccess('Requested Order', requestedOrder); } @Put('/update-quantity') async updateItemQuantity( @Request() req, @Body('action') action: string, @Body('cartId') cartId: string, @Body('quantity') quantity: string, ) { const updatedItems = await this.cartService.updateItemQuantity( req.user, action, +cartId, +quantity, ); return new ResponseSuccess('Updated Items', updatedItems); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules/cart
/content/gmx-projects/gmx-admin/backend/src/modules/cart/dto/product-quotes.dto.ts
import { IsNotEmpty, IsString } from 'class-validator'; export class CreateProductDto { @IsNotEmpty() @IsString() title: string; @IsNotEmpty() categoryId: string; @IsNotEmpty() medRecId: string; @IsNotEmpty() // @IsNumber() price: string; @IsNotEmpty() // @IsNumber() strainId: string; @IsNotEmpty() @IsString() dominant: string; @IsNotEmpty() // @IsNumber() iOId: string; @IsNotEmpty() harvested: Date; @IsNotEmpty() // @IsNumber() thc: string; @IsNotEmpty() @IsString() description: string; @IsNotEmpty() productImages: string[]; }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/medrec/medrec.controller.ts
import { Controller, Get } from '@nestjs/common'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { MedRecService } from './medrec.service'; @Controller() export class MedRecController { constructor(private readonly medRecService: MedRecService) {} @Get() async getAllMedRec() { const medrec = await this.medRecService.getAllMedRec(); return new ResponseSuccess('MedRec', medrec); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/medrec/medrec.service.ts
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { MedRec } from 'src/models/medRec.model'; @Injectable() export class MedRecService { constructor( @InjectModel(MedRec) private medRecModel: typeof MedRec, ) {} async getAllMedRec() { const medrec = await this.medRecModel.findAll({ where: { isActive: '1' }, }); return medrec; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/medrec/medrec.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { MedRec } from 'src/models/medRec.model'; import { MedRecController } from './medrec.controller'; import { MedRecService } from './medrec.service'; @Module({ imports: [SequelizeModule.forFeature([MedRec])], controllers: [MedRecController], providers: [MedRecService], }) export class MedRecModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/brand/brand.service.ts
import { BadRequestException, ForbiddenException, Injectable, NotFoundException, UnprocessableEntityException, } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Op } from 'sequelize'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Brand } from 'src/models/brand.model'; import { BrandCompany } from 'src/models/brandCompany.model'; import { Category } from 'src/models/category.model'; import { Follower } from 'src/models/follower.model'; import { MedRec } from 'src/models/medRec.model'; import { Organizations } from 'src/models/organizations.model'; import { Plans } from 'src/models/plans.model'; import { Product } from 'src/models/product.model'; import { ProductFavourite } from 'src/models/productFavourite.model'; import { Review } from 'src/models/review.model'; import { Settings } from 'src/models/settings.model'; import { State } from 'src/models/state.model'; import { SubCategory } from 'src/models/subCategory.model'; import { User } from 'src/models/user.model'; import { UserSubscription } from 'src/models/userSubscription.model'; import { HelperService } from 'src/services/Helper.service'; import { invoiceTemplate } from '../../mail-service/templates/invoice.mail'; import { JwtUserDTO } from '../auth/dto/JwtUser.dto'; import { Strain } from './../../models/strain.model'; import { CreateBrandDto } from './dto/create-brand.dto'; import { UpgradeSubscriptionDto } from './dto/upgrade-subscription.dto'; const fs = require('fs'); const pdf = require('pdf-creator-node'); const bcrypt = require('bcryptjs'); const moment = require('moment'); const { FRONEND_BASE_URL, ADMIN_BASE_URL } = process.env; require('dotenv').config(); const { SITE_NAME } = process.env; @Injectable() export class BrandService { constructor( @InjectModel(User) private userModel: typeof User, @InjectModel(Organizations) private organizationsModel: typeof Organizations, @InjectModel(BrandCompany) private brandCompanyModel: typeof BrandCompany, @InjectModel(Brand) private brandModel: typeof Brand, @InjectModel(UserSubscription) private userSubscriptionModel: typeof UserSubscription, @InjectModel(Settings) private settingsModel: typeof Settings, @InjectModel(Plans) private plansModel: typeof Plans, @InjectModel(State) private stateModel: typeof State, private mailService?: MailServiceService, ) {} async createBrand(createBrandDto: CreateBrandDto, file) { if (createBrandDto.password !== createBrandDto.confirmPassword) { throw new ForbiddenException( 'Password and confirm password does not match.', ); } const helperService = await new HelperService(); const stripeKey = await helperService.getSettings( this.settingsModel, 'stripe_secret_key', ); let token: any; let stripe: any; let customer, plan, subscription; plan = await this.plansModel.findOne({ where: { id: createBrandDto.planId }, }); if (createBrandDto.planId != '1') { try { stripe = require('stripe')(stripeKey.description); token = await stripe.tokens.create({ card: { number: createBrandDto.cardNumber, exp_month: parseInt(createBrandDto.cardExpiry.slice(0, -3)), exp_year: parseInt(createBrandDto.cardExpiry.slice(-2)), cvc: createBrandDto.cardCvc, name: createBrandDto.cardHolder, }, }); customer = await stripe.customers.create({ email: createBrandDto.email, source: token.id, }); subscription = await stripe.subscriptions.create({ customer: customer.id, items: [{ plan: plan.id }], }); } catch (err) { switch (err.type) { case 'StripeCardError': // A declined card error throw new BadRequestException(err.message); // => e.g. "Your card's expiration year is invalid." break; case 'StripeRateLimitError': // Too many requests made to the API too quickly throw new BadRequestException(err.message); break; case 'StripeInvalidRequestError': // Invalid parameters were supplied to Stripe's API throw new BadRequestException(err.message); break; case 'StripeAPIError': throw new BadRequestException(err.message); // An error occurred internally with Stripe's API break; case 'StripeConnectionError': throw new BadRequestException(err.message); // Some kind of error occurred during the HTTPS communication break; case 'StripeAuthenticationError': throw new BadRequestException(err.message); // You probably used an incorrect API key break; default: throw new BadRequestException('Something went wrong'); // Handle any other types of unexpected errors break; } } } const checkEmail = await this.checkEmail(createBrandDto.email); const medRecCertificatePath = (await file.medRecCertificatePath) ? file?.medRecCertificatePath[0]?.filename : null; const resaleLicensePath = (await file) ? file.resaleLicensePath ? file?.resaleLicensePath[0]?.filename : null : null; const profileDocumentPath = (await file) ? file?.profileDocument ? file.profileDocument[0]?.filename : null : null; const hash = bcrypt.hashSync(createBrandDto.password, 10); let slug = createBrandDto.name .toLowerCase() .replace(/ /g, '') .replace(/[^\w-]+/g, ''); const existUserWithSlug = await this.userModel.findAndCountAll({ where: { slug: { [Op.like]: `%${slug}%`, }, }, }); if (existUserWithSlug.count) { slug = slug + '-' + existUserWithSlug.count; } const user = await this.userModel.create({ isApproved: 2, name: createBrandDto.name, slug: slug, email: createBrandDto.email, password: hash, planId: createBrandDto.planId, }); const organization = await this.organizationsModel.create({ isApproved: 2, userId: user.id, role: createBrandDto.role, }); let companySlug = createBrandDto.companyName .toLowerCase() .replace(/ /g, '-') .replace(/[^\w-]+/g, ''); const existCompanyWithSlug = await this.brandCompanyModel.findAndCountAll({ where: { slug: { [Op.like]: `%${slug}%`, }, }, }); if (existCompanyWithSlug.count) { slug = slug + '-' + existCompanyWithSlug.count; } const brandCompany = await this.brandCompanyModel.create({ isApproved: 2, userId: user.id, organizationId: organization?.id, companyName: createBrandDto.companyName, slug: companySlug, medRecId: createBrandDto.medRecId, licenseNumber: createBrandDto.licenseNumber, licenseExpirationDate: createBrandDto.licenseExpirationDate, certificatePath: medRecCertificatePath, resaleLicensePath: resaleLicensePath, address: createBrandDto.address !== '' && createBrandDto.address !== null ? createBrandDto.address : null, stateId: createBrandDto.selectedState, zipCode: createBrandDto.zipCode, phoneNumber: createBrandDto.phoneNumber, }); let brandSlug = createBrandDto.brandName .toLowerCase() .replace(/ /g, '-') .replace(/[^\w-]+/g, ''); const existBrandWithSlug = await this.brandModel.findAndCountAll({ where: { slug: { [Op.like]: `%${slug}%`, }, }, }); if (existBrandWithSlug.count) { slug = slug + '-' + existBrandWithSlug.count; } const brand = await this.brandModel.create({ isApproved: 2, userId: user.id, brandCompanyId: brandCompany?.id, brandName: createBrandDto.brandName, slug: brandSlug, year: createBrandDto.year !== '' && createBrandDto.year !== null ? createBrandDto.year : null, website: createBrandDto.website !== '' && createBrandDto.website !== null ? createBrandDto.website : null, profilePath: profileDocumentPath, // address: // createBrandDto.brandAddress !== '' && createBrandDto.brandAddress !== null // ? createBrandDto.brandAddress // : null, description: createBrandDto.description, avgProductRating: createBrandDto.avgProductRating, reviewsProductCount: createBrandDto.reviewsProductCount, avgDOTRating: createBrandDto.avgDOTRating, reviewsDOTCount: createBrandDto.reviewsDOTCount, avgGeneralRating: createBrandDto.avgGeneralRating, reviewsGeneralCount: createBrandDto.reviewsGeneralCount, avgRating: createBrandDto.avgRating, }); await user.update({ organizationId: organization?.id, currentBrandCompanyId: brandCompany?.id, currentBrandId: brand?.id }); if (createBrandDto.planId != '1') { const startDate = await moment().format('YYYY-MM-DD'); //current Date const endDate = await moment().add(1, 'month').format('YYYY-MM-DD'); //end date const planSubscription = await this.userSubscriptionModel.create({ userId: user.id, planId: plan.id, customerId: customer.id, subscriptionToken: token.id, subscriptionId: subscription.id, status: subscription.status, amount: plan.price, responseJson: JSON.stringify(subscription), startDate: startDate, endDate: endDate, planCancelDate: '', }); user.update({ planExpiryDate: endDate, subscriptionId: planSubscription.id, }); } await Product.update( { productVisibility: plan.id != '1' ? '1' : '2', }, { where: { userId: user.id }, }, ); const userData = { // 'NAME': user.firstName, NAME: user.name, LINK: FRONEND_BASE_URL + '/sign-in', }; const brandEmailContent = await helperService.emailTemplateContent( 1, userData, ); this.mailService.sendMail( user.email, brandEmailContent.subject, brandEmailContent.body, ); const adminData = { // 'NAME': user.firstName, NAME: user.name, EMAIL: user.email, ROLE: 'Brand', LINK: ADMIN_BASE_URL + 'brands/edit/' + user.id, PLAN: plan.title, }; const adminEmailContent = await helperService.emailTemplateContent( 6, adminData, ); const adminEmail = await helperService.getSettings( this.settingsModel, 'info_email', ); this.mailService.sendMail( adminEmail.description, adminEmailContent.subject, adminEmailContent.body, ); return user; } async findAll() { const brands = await this.brandModel.findAll(); return brands; } async upgradeSubscription( slug: string, jwtUserDTO: JwtUserDTO, upgradeSubscription: UpgradeSubscriptionDto, ) { const plan = await this.plansModel.findOne({ where: { slug: slug }, }); if (!plan) throw new NotFoundException('Plan not found'); const user = await this.userModel.findOne({ where: { id: jwtUserDTO.id }, }); if (!user) throw new NotFoundException('User not found'); const helperService = await new HelperService(); const stripeKey = await helperService.getSettings( this.settingsModel, 'stripe_secret_key', ); if (plan.price > 0) { let token: any; let stripe: any; let customer, subscription; try { stripe = require('stripe')(stripeKey.description); token = await stripe.tokens.create({ card: { number: upgradeSubscription.cardNumber, exp_month: parseInt(upgradeSubscription.cardExpiry.slice(0, -3)), exp_year: parseInt(upgradeSubscription.cardExpiry.slice(-2)), cvc: upgradeSubscription.cardCvc, name: upgradeSubscription.cardHolder, }, }); customer = await stripe.customers.create({ email: user.email, source: token.id, }); subscription = await stripe.subscriptions.create({ customer: customer.id, items: [{ plan: plan.id }], }); } catch (err) { switch (err.type) { case 'StripeCardError': // A declined card error throw new BadRequestException(err.message); // => e.g. "Your card's expiration year is invalid." break; case 'StripeRateLimitError': // Too many requests made to the API too quickly throw new BadRequestException(err.message); break; case 'StripeInvalidRequestError': // Invalid parameters were supplied to Stripe's API throw new BadRequestException(err.message); break; case 'StripeAPIError': throw new BadRequestException(err.message); // An error occurred internally with Stripe's API break; case 'StripeConnectionError': throw new BadRequestException(err.message); // Some kind of error occurred during the HTTPS communication break; case 'StripeAuthenticationError': throw new BadRequestException(err.message); // You probably used an incorrect API key break; default: throw new BadRequestException('Something went wrong'); // Handle any other types of unexpected errors break; } } const startDate = await moment().format('YYYY-MM-DD'); //current Date const endDate = await moment().add(1, 'month').format('YYYY-MM-DD'); //end date const planSubscription = await this.userSubscriptionModel.create({ userId: user.id, planId: plan.id, customerId: customer.id, subscriptionToken: token.id, subscriptionId: subscription.id, status: subscription.status, amount: plan.price, responseJson: JSON.stringify(subscription), startDate: startDate, endDate: endDate, planCancelDate: '', }); await this.userModel.update( { planId: plan.id, planExpiryDate: endDate, subscriptionId: planSubscription.id, }, { where: { id: jwtUserDTO.id }, }, ); await this.userModel.update( { planId: plan.id, planExpiryDate: endDate, subscriptionId: planSubscription.id, }, { where: { id: jwtUserDTO.id }, }, ); await Product.update( { productVisibility: '1', }, { where: { userId: user.id }, }, ); const userData = { NAME: user.name, PLAN: plan.title, PRICE: plan.price, LINK: FRONEND_BASE_URL + '/sign-in', }; const brandEmailContent = await helperService.emailTemplateContent( 24, userData, ); this.mailService.sendMail( user.email, brandEmailContent.subject, brandEmailContent.body, ); } return user; } async downgradeSubscription(jwtUserDTO: JwtUserDTO) { const user = await this.userModel.findOne({ where: { id: jwtUserDTO.id }, }); const subscription = await this.userSubscriptionModel.findOne({ where: { id: user.subscriptionId, }, }); const plan = await this.plansModel.findOne({ where: { id: subscription.planId }, }); if (!plan) throw new NotFoundException('Plan not found'); const helperService = await new HelperService(); const stripeKey = await helperService.getSettings( this.settingsModel, 'stripe_secret_key', ); let stripe: any; stripe = require('stripe')(stripeKey.description); const subscriptionUpdate = await stripe.subscriptions.del( subscription.subscriptionId, ); const userSubscription = await this.userSubscriptionModel.update( { planCancelDate: await moment().format('YYYY-MM-DD HH:mm:ss'), status: subscriptionUpdate.status, responseJson: JSON.stringify(subscriptionUpdate), }, { where: { id: user.subscriptionId, }, }, ); await this.userModel.update( { planId: '1', }, { where: { id: jwtUserDTO.id }, }, ); await Product.update( { productVisibility: '2', }, { where: { userId: user.id }, }, ); const userData = { NAME: user.name, PLAN: plan.title, PRICE: plan.price, LINK: FRONEND_BASE_URL + '/sign-in', }; const brandEmailContent = await helperService.emailTemplateContent( 25, userData, ); this.mailService.sendMail( user.email, brandEmailContent.subject, brandEmailContent.body, ); return userSubscription; } async checkExist(id: number) { const user = await this.userModel.findOne({ where: { id: id }, }); if (!user) throw new NotFoundException(); return user; } async checkEmail(emailId) { const emailExist = await this.userModel.findOne({ where: { email: emailId, }, }); if (emailExist) { throw new UnprocessableEntityException( 'Email already exist, Please try another.', ); } } async findSingleBrand(brandSlug: string, jwtUserDTO?: JwtUserDTO) { const brand = await this.brandModel.findOne({ where: { slug: brandSlug, isApproved: 1, isActive: 1, }, include: [ { model: Follower, as: 'followers', where: { isActive: 1, //role: 2, }, required: false, }, { model: Follower, as: 'followings', where: { isActive: 1, //role: 3, }, required: false, }, { model: BrandCompany, include: [ { model: State, } ] }, //this.stateModel ], }); if (!brand) throw new NotFoundException('brand not found'); const brandData = brand.toJSON(); brandData.userFollowed = false; brandData.canMessage = false; const products = await Product.findAll({ where: { isActive: 1, productVisibility: 1, userId: brand?.userId, brandId: brand?.id, }, include: [ { model: ProductFavourite, where: { userId: jwtUserDTO?.id ? jwtUserDTO?.id : '' }, required: false, }, { model: Category }, { model: SubCategory }, { model: this.userModel, include: [this.brandModel], }, { model: MedRec }, { model: Strain }, ], order: [['id', 'DESC']], }); if (jwtUserDTO?.id) { const helperService = await new HelperService(); const { fromUser, role } = await helperService.getFromUser(jwtUserDTO.id); const user = await this.userModel.findOne({ where: { id: jwtUserDTO.id, }, }); if (!user) throw new NotFoundException('User not found'); // if (business?.stateId !== user.stateId) { // brandData.canMessage = false; // } else { brandData.canMessage = true; //} if (brand?.id !== fromUser) { const follower = await Follower.findOne({ where: { followingId: brand?.id, followingRole: role + "", followerRole: "2", followerId: fromUser, }, }); if (follower) { brandData.userFollowed = follower.isActive ? true : false; } } } return { brandData, products, }; } async subscriptionDetails(jwtUserDTO: JwtUserDTO) { const activePlan = await this.userModel.findOne({ where: { id: jwtUserDTO.id }, attributes: ['subscriptionId', 'planId'], }); const activePlanDetails = await this.plansModel.findOne({ where: { id: activePlan.planId }, }); const activeSubscription = await this.userModel.findOne({ where: { id: jwtUserDTO.id }, include: [ { model: this.userSubscriptionModel, where: { id: activePlan.subscriptionId, }, include: [this.plansModel], }, ], }); const pastSubscriptionsList = await this.userModel.findOne({ where: { id: jwtUserDTO.id }, include: [ { model: this.userSubscriptionModel, // where: { id: { [Op.ne]: activePlan.subscriptionId } }, include: [this.plansModel], }, ], }); return { activeSubscription, activePlanDetails, pastSubscriptionsList, }; } /* Generate invoice start */ async generateInvoice(jwtUserDTO: JwtUserDTO, invoiceId: number) { const subscriptionPlan = await this.userSubscriptionModel.findOne({ where: { id: invoiceId }, include: [ { model: this.userModel, //include: [{ model: this.stateModel }, { model: this.brandModel }], }, { model: this.plansModel, }, ], }); if (!subscriptionPlan) throw new NotFoundException(); // const filePath = 'src/mail-service/templates/invoice.html' const filePath = invoiceTemplate; // const htmlFile = fs.readFileSync(filePath, 'utf-8') // const helperService = await new HelperService(); // const invoiceHtml = await EmailTemplate.findOne({ // where: { id: 19 }, // attributes: ['body'] // }); // console.log(invoiceHtml); const filename = 'invoice_' + Math.random() + '.pdf'; const document = { html: invoiceTemplate, data: { //products: obj, // userName: subscriptionPlan.user.firstName ?? '', userName: subscriptionPlan.user.name ?? '', date: moment(subscriptionPlan.startDate).format("DD MMM 'YY"), // invoiceNo: 'GMX-025', siteName: SITE_NAME ?? '', // toAddress: subscriptionPlan.user.brand.address ?? '', //toState: subscriptionPlan.user?.states.name ?? '', // zipCode: subscriptionPlan.user.zipCode ?? '', productDetails: subscriptionPlan.plans.description ?? '', productTitle: subscriptionPlan.plans.title ?? '', productPrice: subscriptionPlan.plans.planPrice ?? '', totalPrice: subscriptionPlan.plans.planPrice ?? '', year: new Date().getFullYear(), // grandTotal: subscriptionPlan.plans.planPrice, }, path: '../assets/invoice/' + filename, }; await pdf .create(document) .then((res) => { // console.log("res", res); }) .catch((error) => { // console.log("error", error); }); // const filepath = 'uploads/invoice/' + filename; return '/invoice/' + filename; } /* Download invoice end */ /* seller/brand review */ async brandReview(slug?: string, page?: string, perPage?: string) { const response = { 1: '', 2: '', 3: '' }; for await (const type of [1, 2, 3]) { const { count, rows: reviews } = await Review.findAndCountAll({ where: { type: type }, order: [['id', 'desc']], offset: page ? parseInt(page) * parseInt(perPage) : 0, limit: parseInt(perPage), include: [ this.userModel, { model: this.brandModel, where: { slug: slug } }, ], }); response[type] = { count, reviews }; } return response; } async getProfile(jwtUserDTO: JwtUserDTO) { const brand = await this.brandModel.findOne({ where: { userId: jwtUserDTO.id, isApproved: 1, isActive: 1, }, include: [ { model: this.userModel, include: [{ model: this.stateModel }], }, ], }); const products = await Product.findAll({ where: { isActive: 1, userId: brand.user.id, }, include: [{ model: Category }, { model: MedRec }, { model: Strain }], order: [['id', 'DESC']], }); if (!brand) throw new NotFoundException('Brand not found'); const brandData = brand.toJSON(); return { brandData, products, }; } async updateBlockRetailers(jwtUserDTO: JwtUserDTO, retailerIds: any) { const brand = await this.brandModel.findOne({ where: { userId: jwtUserDTO.id, }, }); if (!brand) throw new BadRequestException('Something went wrong'); brand.update({ retailers: retailerIds?.retailerIds.length > 0 ? Array.isArray(retailerIds?.retailerIds) ? retailerIds?.retailerIds?.join(',') : retailerIds?.retailerIds : null, }); return brand; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/brand/brand.controller.ts
import { Body, Controller, Get, Param, Post, Put, Query, Request, UploadedFiles, UseGuards, UseInterceptors, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { FileFieldsInterceptor } from '@nestjs/platform-express'; import { diskStorage } from 'multer'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { IResponse } from 'src/common/interfaces/response.interface'; import { FileHelper } from 'src/services/FileHelper.service'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { BrandService } from './brand.service'; import { CreateBrandDto } from './dto/create-brand.dto'; import { UpgradeSubscriptionDto } from './dto/upgrade-subscription.dto'; import path = require('path'); export const productInvoiceStorage = { storage: diskStorage({ destination: '../assets/invoice', }), }; @Controller() export class BrandController { constructor(private readonly brandService: BrandService) {} // @Post() // create(@Body() createBrandDto: CreateBrandDto) { // return this.brandService.create(createBrandDto); // } //@UseGuards(AuthGuard('jwt')) @Post('/register') @UseInterceptors( FileFieldsInterceptor( [ { name: 'medRecCertificatePath', maxCount: 1, }, { name: 'resaleLicensePath', maxCount: 1, }, { name: 'profileDocument', maxCount: 1, }, ], { storage: diskStorage({ // destination: FileHelper.destinationPath, destination: '../assets', filename: FileHelper.customFileName, }), }, ), ) /* async createBrand( @Body() createBrand: CreateBrandDto //@Body() ): Promise<IResponse> { */ async createBrand( @Body() createBrandDto: CreateBrandDto, @UploadedFiles() file: { avatar?: []; background?: [] }, ): Promise<IResponse> { const isCreated = await this.brandService.createBrand(createBrandDto, file); return new ResponseSuccess('Brand added successfully.', isCreated); } //@UseGuards(AuthGuard('jwt')) @Get() async brand(): Promise<IResponse> { const brand = await this.brandService.findAll(); return new ResponseSuccess('Brand', brand); } @UseGuards(AuthGuard('jwt')) @Get('subscription') async subscriptionDetails(@Request() req) { const subscription = await this.brandService.subscriptionDetails(req.user); return new ResponseSuccess('subscription', subscription); } @UseGuards(AuthGuard('jwt')) @Get('invoice/:invoiceId') async generateInvoice(@Param('invoiceId') invoiceId: string, @Request() req) { const invoice = await this.brandService.generateInvoice( req.user, +invoiceId, ); return new ResponseSuccess('Invoice', invoice); } /* seller/brand review */ @Get('review') async brandReview( @Query('slug') slug: string, @Query('page') page: string, @Query('limit') limit: string, ): Promise<IResponse> { const brandReview = await this.brandService.brandReview(slug, page, limit); return new ResponseSuccess('reviews', brandReview); } @UseGuards(AuthGuard('jwt')) @Get('/profile') async getProfile(@Request() req) { const brand = await this.brandService.getProfile(req.user); return new ResponseSuccess('Brand', brand); } @UseGuards(JwtAuthGuard) @Get('/:slug') async findSingleBrand(@Request() req, @Param('slug') slug: string) { const brand = await this.brandService.findSingleBrand(slug, req.user); return new ResponseSuccess('Brand', brand); } @UseGuards(AuthGuard('jwt')) @Post('upgrade-subscription/:slug') async upgradeSubscription( @Request() req, @Param('slug') slug: string, @Body() upgradeSubscriptionDto: UpgradeSubscriptionDto, ): Promise<IResponse> { const planSubscription = await this.brandService.upgradeSubscription( slug, req.user, upgradeSubscriptionDto, ); return new ResponseSuccess( 'Subscription upgraded successfully.', planSubscription, ); } @UseGuards(AuthGuard('jwt')) @Post('downgrade-subscription') async downgradeSubscription(@Request() req): Promise<IResponse> { const planSubscription = await this.brandService.downgradeSubscription( req.user, ); return new ResponseSuccess( 'Subscription downgraded successfully.', planSubscription, ); } @UseGuards(AuthGuard('jwt')) @Put('block-retailers') async updateBulkOrder( @Request() req, @Body() retailerIds: any, ): Promise<IResponse> { const data = await this.brandService.updateBlockRetailers( req.user, retailerIds, ); return new ResponseSuccess('Order setting updated successfully.', data); } /*@Put(':id') update(@Param('id') id: string, @Body() updateBrandDto: UpdateBrandDto) { return this.brandService.update(+id, updateBrandDto); } @Delete(':id') remove(@Param('id') id: string) { return this.brandService.remove(+id); } */ }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/brand/brand.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { BrandService } from './brand.service'; describe('BrandService', () => { let service: BrandService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [BrandService], }).compile(); service = module.get<BrandService>(BrandService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/brand/brand.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { BrandCompany } from 'src/models/brandCompany.model'; import { Follower } from 'src/models/follower.model'; import { Organizations } from 'src/models/organizations.model'; import { Plans } from 'src/models/plans.model'; import { Settings } from 'src/models/settings.model'; import { State } from 'src/models/state.model'; import { User } from 'src/models/user.model'; import { UserSubscription } from 'src/models/userSubscription.model'; import { Brand } from './../../models/brand.model'; import { BrandController } from './brand.controller'; import { BrandService } from './brand.service'; @Module({ imports: [ SequelizeModule.forFeature([ User, Organizations, BrandCompany, Brand, UserSubscription, Settings, Plans, State, Follower, ]), ], controllers: [BrandController], providers: [BrandService, MailServiceService], }) export class BrandModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/brand/brand.controller.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { BrandController } from './brand.controller'; import { BrandService } from './brand.service'; describe('BrandController', () => { let controller: BrandController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [BrandController], providers: [BrandService], }).compile(); controller = module.get<BrandController>(BrandController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); });
0
/content/gmx-projects/gmx-admin/backend/src/modules/brand
/content/gmx-projects/gmx-admin/backend/src/modules/brand/dto/upgrade-subscription.dto.ts
import { IsNotEmpty } from 'class-validator'; export class UpgradeSubscriptionDto { @IsNotEmpty() cardNumber: string; @IsNotEmpty() cardExpiry: string; @IsNotEmpty() cardCvc: string; @IsNotEmpty() cardHolder: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/brand
/content/gmx-projects/gmx-admin/backend/src/modules/brand/dto/update-brand.dto.ts
import { PartialType } from '@nestjs/mapped-types'; import { CreateBrandDto } from './create-brand.dto'; export class UpdateBrandDto extends PartialType(CreateBrandDto) {}
0
/content/gmx-projects/gmx-admin/backend/src/modules/brand
/content/gmx-projects/gmx-admin/backend/src/modules/brand/dto/create-brand.dto.ts
import { IsNotEmpty, IsOptional, IsString, Length } from 'class-validator'; import { UserRegisterDTO } from './../../auth/dto/userRegister.dto'; export class CreateBrandDto extends UserRegisterDTO { @IsNotEmpty() @IsString() @Length(1, 255) companyName: string; @IsNotEmpty() medRecId: number; @IsNotEmpty() licenseNumber: Date; @IsNotEmpty() licenseExpirationDate: Date; @IsOptional() address: string; @IsNotEmpty() selectedState: string; @IsNotEmpty() zipCode: number; @IsOptional() phoneNumber: number; @IsNotEmpty() @IsString() @Length(1, 255) brandName: string; @IsOptional() year: string; @IsOptional() website: string; @IsOptional() logoPath: string; // @IsOptional() // brandAddress: string; @IsOptional() description: string; @IsOptional() avgProductRating: number; @IsOptional() reviewsProductCount: number; @IsOptional() avgDOTRating: number; @IsOptional() reviewsDOTCount: number; @IsOptional() avgGeneralRating: number; @IsOptional() reviewsGeneralCount: number; @IsOptional() avgRating: number; @IsOptional() cardNumber: string; @IsOptional() cardExpiry: string; @IsOptional() cardCvc: string; @IsOptional() cardHolder: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/companies/companies.service.ts
import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Brand } from 'src/models/brand.model'; import { BrandCompany } from 'src/models/brandCompany.model'; import { JwtUserDTO } from '../auth/dto/JwtUser.dto'; import { AddCompanyDto } from './dto/add-company.dto'; import { Op } from 'sequelize'; import { HelperService } from 'src/services/Helper.service'; import { User } from 'src/models/user.model'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Settings } from 'src/models/settings.model'; import { SwitchAccountDto } from './dto/switch-account.dto'; import { AddBrandDto } from './dto/add-brand.dto'; require('dotenv').config(); const { ADMIN_BASE_URL } = process.env; @Injectable() export class CompaniesService { constructor( @InjectModel(User) private userModel: typeof User, @InjectModel(BrandCompany) private brandCompanyModel: typeof BrandCompany, @InjectModel(Brand) private brandModel: typeof Brand, @InjectModel(Settings) private settingsModel: typeof Settings, private mailService?: MailServiceService, ) {} async getAllCompanies(jwtUserDTO: JwtUserDTO) { const data = await this.brandCompanyModel.findAll({ include:[ { model:Brand, attributes:['id', 'brandName', 'slug', 'profilePath'], } ], attributes:['id', 'companyName', 'slug', 'isApproved'], where: { userId: jwtUserDTO.id, isActive: '1' }, }); return data; } async addCompany(jwtUserDTO: JwtUserDTO, addCompanyDto: AddCompanyDto, file) { const user = await this.userModel.findOne({ where: { id: jwtUserDTO.id }, }); if (!user) throw new NotFoundException('User not found'); const helperService = await new HelperService(); const medRecCertificatePath = (await file.medRecCertificatePath) ? file?.medRecCertificatePath[0]?.filename : null; const resaleLicensePath = (await file) ? file.resaleLicensePath ? file?.resaleLicensePath[0]?.filename : null : null; const profileDocumentPath = (await file) ? file?.profileDocument ? file.profileDocument[0]?.filename : null : null; let companySlug = addCompanyDto.companyName .toLowerCase() .replace(/ /g, '-') .replace(/[^\w-]+/g, ''); const existCompanyWithSlug = await this.brandCompanyModel.findAndCountAll({ where: { slug: { [Op.like]: `%${companySlug}%`, }, }, }); if (existCompanyWithSlug.count) { companySlug = companySlug + '-' + existCompanyWithSlug.count; } const brandCompany = await this.brandCompanyModel.create({ isApproved: 2, userId: user.id, organizationId: user?.organizationId, companyName: addCompanyDto.companyName, slug: companySlug, medRecId: addCompanyDto.medRecId, licenseNumber: addCompanyDto.licenseNumber, licenseExpirationDate: addCompanyDto.licenseExpirationDate, certificatePath: medRecCertificatePath, resaleLicensePath: resaleLicensePath, address: addCompanyDto.address !== '' && addCompanyDto.address !== null ? addCompanyDto.address : null, stateId: addCompanyDto.selectedState, zipCode: addCompanyDto.zipCode, phoneNumber: addCompanyDto.phoneNumber, }); let brandSlug = addCompanyDto.brandName .toLowerCase() .replace(/ /g, '-') .replace(/[^\w-]+/g, ''); const existBrandWithSlug = await this.brandModel.findAndCountAll({ where: { slug: { [Op.like]: `%${brandSlug}%`, }, }, }); if (existBrandWithSlug.count) { brandSlug = brandSlug + '-' + existBrandWithSlug.count; } const brand = await this.brandModel.create({ isApproved: 2, userId: user.id, brandCompanyId: brandCompany?.id, brandName: addCompanyDto.brandName, slug: brandSlug, year: addCompanyDto.year !== '' && addCompanyDto.year !== null ? addCompanyDto.year : null, website: addCompanyDto.website !== '' && addCompanyDto.website !== null ? addCompanyDto.website : null, profilePath: profileDocumentPath, address: addCompanyDto.brandAddress !== '' && addCompanyDto.brandAddress !== null ? addCompanyDto.brandAddress : null, description: addCompanyDto.description, avgProductRating: addCompanyDto.avgProductRating, reviewsProductCount: addCompanyDto.reviewsProductCount, avgDOTRating: addCompanyDto.avgDOTRating, reviewsDOTCount: addCompanyDto.reviewsDOTCount, avgGeneralRating: addCompanyDto.avgGeneralRating, reviewsGeneralCount: addCompanyDto.reviewsGeneralCount, avgRating: addCompanyDto.avgRating, }); const adminData = { NAME: user?.name, EMAIL: user?.email, ROLE: 'Brand', LINK: ADMIN_BASE_URL + 'brands/edit/' + user?.id, PLAN: user?.plans?.title, }; const adminEmailContent = await helperService.emailTemplateContent( 6, adminData, ); const adminEmail = await helperService.getSettings( this.settingsModel, 'info_email', ); this.mailService.sendMail( adminEmail.description, adminEmailContent.subject, adminEmailContent.body, ); return brandCompany; } async addBrand(jwtUserDTO: JwtUserDTO, addBrandDto: AddBrandDto, file) { const user = await this.userModel.findOne({ where: { id: jwtUserDTO.id }, }); if (!user) throw new NotFoundException('User not found'); const company = await this.brandCompanyModel.findOne({ where: { slug: addBrandDto.company }, }); if (!company) throw new NotFoundException('Company not found'); const helperService = await new HelperService(); const profileDocumentPath = (await file) ? file?.profileDocument ? file.profileDocument[0]?.filename : null : null; let brandSlug = addBrandDto.brandName .toLowerCase() .replace(/ /g, '-') .replace(/[^\w-]+/g, ''); const existBrandWithSlug = await this.brandModel.findAndCountAll({ where: { slug: { [Op.like]: `%${brandSlug}%`, }, }, }); if (existBrandWithSlug.count) { brandSlug = brandSlug + '-' + existBrandWithSlug.count; } const brand = await this.brandModel.create({ isApproved: 1, userId: user.id, brandCompanyId: company?.id, brandName: addBrandDto.brandName, slug: brandSlug, year: addBrandDto.year !== '' && addBrandDto.year !== null ? addBrandDto.year : null, website: addBrandDto.website !== '' && addBrandDto.website !== null ? addBrandDto.website : null, profilePath: profileDocumentPath, address: addBrandDto.brandAddress !== '' && addBrandDto.brandAddress !== null ? addBrandDto.brandAddress : null, description: addBrandDto.description, avgProductRating: addBrandDto.avgProductRating, reviewsProductCount: addBrandDto.reviewsProductCount, avgDOTRating: addBrandDto.avgDOTRating, reviewsDOTCount: addBrandDto.reviewsDOTCount, avgGeneralRating: addBrandDto.avgGeneralRating, reviewsGeneralCount: addBrandDto.reviewsGeneralCount, avgRating: addBrandDto.avgRating, }); // const adminData = { // NAME: user?.name, // EMAIL: user?.email, // ROLE: 'Brand', // LINK: ADMIN_BASE_URL + 'brands/edit/' + user?.id, // PLAN: user?.plans?.title, // }; // const adminEmailContent = await helperService.emailTemplateContent( // 6, // adminData, // ); // const adminEmail = await helperService.getSettings( // this.settingsModel, // 'info_email', // ); // this.mailService.sendMail( // adminEmail.description, // adminEmailContent.subject, // adminEmailContent.body, // ); return brand; } async switchAccount(jwtUserDTO: JwtUserDTO, switchAccountDto: SwitchAccountDto) { const brand = await this.brandModel.findOne({ where: { userId: jwtUserDTO?.id, slug: switchAccountDto?.slug }, }); if (!brand) throw new NotFoundException('Brand Not Found'); await this.userModel.update( { currentBrandCompanyId: brand?.brandCompanyId, currentBrandId: brand?.id }, { where: { id: jwtUserDTO?.id} }, ); const user = await this.userModel.findOne({ include: [ { model: BrandCompany, attributes: [ 'id', 'companyName', 'slug', 'medRecId', ] }, { model: Brand, attributes: [ 'id', 'brandName', 'slug', 'profilePath', ], }, ], attributes: [ 'id', 'name', 'slug', 'email', 'password', 'isActive', ], where: { id: jwtUserDTO?.id }, }); if (!user) { return false; } if (+user.isActive !== 1) { throw new ForbiddenException('Your account has been deactivated'); } return user; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/companies/companies.controller.ts
import { Body, Controller, Get, Patch, Post, Request, UploadedFiles, UseGuards, UseInterceptors } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { CompaniesService } from './companies.service'; import { FileFieldsInterceptor } from '@nestjs/platform-express'; import { diskStorage } from 'multer'; import { FileHelper } from 'src/services/FileHelper.service'; import { IResponse } from 'src/common/interfaces/response.interface'; import { AddCompanyDto } from './dto/add-company.dto'; import { SwitchAccountDto } from './dto/switch-account.dto'; import { AddBrandDto } from './dto/add-brand.dto'; @Controller() export class CompaniesController { constructor(private readonly companiesService: CompaniesService) {} @UseGuards(AuthGuard('jwt')) @Get() async getAllCompanies(@Request() req) { const medrec = await this.companiesService.getAllCompanies(req.user); return new ResponseSuccess('Companies', medrec); } @UseGuards(AuthGuard('jwt')) @Post() @UseInterceptors( FileFieldsInterceptor( [ { name: 'medRecCertificatePath', maxCount: 1, }, { name: 'resaleLicensePath', maxCount: 1, }, { name: 'profileDocument', maxCount: 1, }, ], { storage: diskStorage({ destination: '../assets', filename: FileHelper.customFileName, }), }, ), ) async addCompany( @Request() req, @Body() addCompanyDto: AddCompanyDto, @UploadedFiles() file: { avatar?: []; background?: [] }, ): Promise<IResponse> { const isCreated = await this.companiesService.addCompany(req.user, addCompanyDto, file); return new ResponseSuccess('Company added successfully.', isCreated); } @UseGuards(AuthGuard('jwt')) @Post('add-brand') @UseInterceptors( FileFieldsInterceptor( [ { name: 'profileDocument', maxCount: 1, }, ], { storage: diskStorage({ destination: '../assets', filename: FileHelper.customFileName, }), }, ), ) async addBrand( @Request() req, @Body() addBrandDto: AddBrandDto, @UploadedFiles() file: { avatar?: []; background?: [] }, ): Promise<IResponse> { const isCreated = await this.companiesService.addBrand(req.user, addBrandDto, file); return new ResponseSuccess('Brand has been successfully added.', isCreated); } @UseGuards(AuthGuard('jwt')) @Patch('switch-account') async switchAccount( @Request() req, @Body() switchAccountDto: SwitchAccountDto, ): Promise<IResponse> { const data = await this.companiesService.switchAccount(req.user, switchAccountDto); return new ResponseSuccess('Switch account successfully.', data); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/companies/companies.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Brand } from 'src/models/brand.model'; import { BrandCompany } from 'src/models/brandCompany.model'; import { Settings } from 'src/models/settings.model'; import { User } from 'src/models/user.model'; import { CompaniesController } from './companies.controller'; import { CompaniesService } from './companies.service'; @Module({ imports: [SequelizeModule.forFeature([User, BrandCompany, Brand, Settings])], controllers: [CompaniesController], providers: [CompaniesService, MailServiceService], }) export class CompaniesModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules/companies
/content/gmx-projects/gmx-admin/backend/src/modules/companies/dto/switch-account.dto.ts
import { IsNotEmpty } from 'class-validator'; export class SwitchAccountDto { @IsNotEmpty() slug: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/companies
/content/gmx-projects/gmx-admin/backend/src/modules/companies/dto/add-company.dto.ts
import { IsNotEmpty, IsOptional, IsString, Length } from 'class-validator'; export class AddCompanyDto { @IsNotEmpty() @IsString() @Length(1, 255) companyName: string; @IsNotEmpty() medRecId: number; @IsNotEmpty() licenseNumber: Date; @IsNotEmpty() licenseExpirationDate: Date; @IsOptional() address: string; @IsNotEmpty() selectedState: string; @IsNotEmpty() zipCode: number; @IsOptional() phoneNumber: number; @IsNotEmpty() @IsString() @Length(1, 255) brandName: string; @IsOptional() year: string; @IsOptional() website: string; @IsOptional() logoPath: string; @IsOptional() brandAddress: string; @IsOptional() description: string; @IsOptional() avgProductRating: number; @IsOptional() reviewsProductCount: number; @IsOptional() avgDOTRating: number; @IsOptional() reviewsDOTCount: number; @IsOptional() avgGeneralRating: number; @IsOptional() reviewsGeneralCount: number; @IsOptional() avgRating: number; @IsOptional() cardNumber: string; @IsOptional() cardExpiry: string; @IsOptional() cardCvc: string; @IsOptional() cardHolder: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/companies
/content/gmx-projects/gmx-admin/backend/src/modules/companies/dto/add-brand.dto.ts
import { IsNotEmpty, IsOptional, IsString, Length } from 'class-validator'; export class AddBrandDto { @IsNotEmpty() @IsString() company: string; @IsNotEmpty() @IsString() @Length(1, 255) brandName: string; @IsOptional() year: string; @IsOptional() website: string; @IsOptional() logoPath: string; @IsOptional() brandAddress: string; @IsOptional() description: string; @IsOptional() avgProductRating: number; @IsOptional() reviewsProductCount: number; @IsOptional() avgDOTRating: number; @IsOptional() reviewsDOTCount: number; @IsOptional() avgGeneralRating: number; @IsOptional() reviewsGeneralCount: number; @IsOptional() avgRating: number; @IsOptional() cardNumber: string; @IsOptional() cardExpiry: string; @IsOptional() cardCvc: string; @IsOptional() cardHolder: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/products/products.service.ts
import { BadRequestException, Injectable, NotFoundException, } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Op } from 'sequelize'; import { Sequelize } from 'sequelize-typescript'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Brand } from 'src/models/brand.model'; import { BrandCompany } from 'src/models/brandCompany.model'; import { Category } from 'src/models/category.model'; import { MedRec } from 'src/models/medRec.model'; import { Order } from 'src/models/order.model'; import { Organizations } from 'src/models/organizations.model'; import { Product } from 'src/models/product.model'; import { ProductFavourite } from 'src/models/productFavourite.model'; import { ProductImages } from 'src/models/productImages.model'; import { ProductPriceHistory } from 'src/models/productPriceHistory.model'; import { Retailer } from 'src/models/retailer.model'; import { Review } from 'src/models/review.model'; import { Strain } from 'src/models/strain.model'; import { SubCategory } from 'src/models/subCategory.model'; import { User } from 'src/models/user.model'; import { JwtUserDTO } from '../auth/dto/JwtUser.dto'; import { CreateProductDto } from './dto/create-product.dto'; import { QuickUpdateProductDto } from './dto/quick-update-product.dto'; import { UpdateProductDto } from './dto/update-product.dto'; const fs = require('fs'); const { FRONEND_BASE_URL } = process.env; const moment = require('moment'); @Injectable() export class ProductsService { constructor( @InjectModel(Product) private productModel: typeof Product, @InjectModel(ProductImages) private productImagesModel: typeof ProductImages, // @InjectModel(ProductPriceHistory) // private productPriceHistoryModel: typeof ProductPriceHistory, @InjectModel(User) private userModel: typeof User, @InjectModel(BrandCompany) private brandCompanyModel: typeof BrandCompany, @InjectModel(Brand) private brandModel: typeof Brand, @InjectModel(Retailer) private retailerModel: typeof Retailer, @InjectModel(Order) private orderModel: typeof Order, private mailService?: MailServiceService, ) {} async addProductImages(createArray: any) { await this.productImagesModel.create(createArray); } async addProduct( createProductDto: CreateProductDto, jwtUserDTO: JwtUserDTO, labResults, ) { let slug = createProductDto.title .toLowerCase() .replace(/ /g, '-') .replace(/[^\w-]+/g, ''); const existProductWithSlug = await this.productModel.findAndCountAll({ where: { slug: { [Op.like]: `%${slug}%`, }, }, }); if (existProductWithSlug.count) { slug = slug + '-' + existProductWithSlug.count; } const brand = await this.brandModel.findOne({ where: { userId: jwtUserDTO.id, brandCompanyId: createProductDto.brandCompanyId, id: createProductDto.brandId, }, }); if (!brand) throw new BadRequestException('Something went wrong'); const user = await this.userModel.findOne({ where: { id: jwtUserDTO.id }, }); const product = await this.productModel.create({ userId: jwtUserDTO.id, brandCompanyId: brand.brandCompanyId, brandId: brand.id, title: createProductDto.title, slug: slug, categoryId: createProductDto.categoryId, subCategoryId: createProductDto?.subCategoryId ? createProductDto?.subCategoryId : null, medRecId: createProductDto.medRecId, unitWeight: createProductDto.unitWeight, unitPerPackage: createProductDto.unitPerPackage, price: createProductDto.price, packagesInStock: createProductDto.packagesInStock, isShowStock: createProductDto.isShowStock, strainId: createProductDto?.strainId ? createProductDto?.strainId : null, dominant: createProductDto.dominant, harvested: createProductDto.harvested, thc: createProductDto.thc, flavor: createProductDto.flavor, description: createProductDto.description, labResultsPath: labResults?.filename, productVisibility: user.planId != 1 ? 1 : 2, }); if (createProductDto.productImages) { const productImages = createProductDto.productImages; if (typeof productImages === 'string') { await this.addProductImages({ productId: product.id, image: JSON.parse(productImages), }); } else { Promise.all( productImages.map(async (imagePath) => { if (imagePath) { await this.addProductImages({ productId: product.id, image: JSON.parse(imagePath), }); } }), ); } } // await this.productPriceHistoryModel.create({ // productId: product.id, // price: createProductDto.price, // }); return product != null; } async uploadProductImage(file) { return file.filename; } async removeProductImage(filePath: any) { const image = await this.productImagesModel.findOne({ where: { image: filePath }, }); if (image) { await this.productImagesModel.destroy({ where: { image: filePath }, }); } if (fs.existsSync('../assets' + filePath)) { return fs.unlinkSync('../assets' + filePath); } else { throw new NotFoundException(); } } async updateProduct( slug: string, updateProductDto: UpdateProductDto, jwtUserDTO: JwtUserDTO, labResults, ) { const product = await this.checkExist(slug); const labResultDocumentPath = (await labResults) ? labResults.filename : updateProductDto.labResultsPath ? updateProductDto.labResultsPath : null; if (labResults && fs.existsSync('../assets' + product.labResultsPath)) { fs.unlink('../assets' + product.labResultsPath, (err) => { if (err) { return; } }); } // if (+product.price !== +updateProductDto.price) { // const date = await moment().format("YYYY-MM-DD"); // const productPriceHistory = await this.productPriceHistoryModel.findOne({ // where: { // productId: product.id, // [Op.and]: [ // Sequelize.where(Sequelize.fn('date', Sequelize.col('createdAt')), '=', date) // ] // } // }); // if (!productPriceHistory) { // await this.productPriceHistoryModel.create({ // productId: product.id, // price: updateProductDto.price, // }); // } else { // productPriceHistory.update({ // price: updateProductDto.price, // }); // } // } const user = await this.userModel.findOne({ where: { id: jwtUserDTO.id }, }); product.update({ userId: jwtUserDTO.id, title: updateProductDto.title, categoryId: updateProductDto.categoryId, subCategoryId: Number(updateProductDto?.subCategoryId) ? updateProductDto?.subCategoryId : null, medRecId: updateProductDto.medRecId, unitWeight: updateProductDto.unitWeight, unitPerPackage: updateProductDto.unitPerPackage, price: updateProductDto.price, packagesInStock: updateProductDto.packagesInStock, isShowStock: updateProductDto.isShowStock, strainId: updateProductDto?.strainId ? updateProductDto?.strainId : null, dominant: updateProductDto.dominant, harvested: updateProductDto.harvested, thc: updateProductDto.thc, flavor: updateProductDto.flavor, description: updateProductDto.description, labResultsPath: labResultDocumentPath, productVisibility: user.planId != 1 ? 1 : 2, }); if (updateProductDto.productImages) { const productImages = updateProductDto.productImages; if (typeof productImages === 'string') { await this.addProductImages({ productId: product.id, image: JSON.parse(productImages), }); } else { Promise.all( productImages.map(async (imagePath) => { if (imagePath) { await this.addProductImages({ productId: product.id, image: JSON.parse(imagePath), }); } }), ); } } return product != null; } async quickUpdateProduct( slug: string, quickUpdateProductDto: QuickUpdateProductDto, jwtUserDTO: JwtUserDTO, ) { const product = await this.productModel.findOne({ include: [Category, SubCategory, Brand], where: { slug: slug }, }); if (!product) throw new NotFoundException('Product Not Found'); await product.update({ userId: jwtUserDTO.id, title: quickUpdateProductDto.title, categoryId: quickUpdateProductDto.categoryId, subCategoryId: quickUpdateProductDto?.subCategoryId ? quickUpdateProductDto?.subCategoryId : null, unitWeight: quickUpdateProductDto.unitWeight, unitPerPackage: quickUpdateProductDto.unitPerPackage, price: quickUpdateProductDto.price, packagesInStock: quickUpdateProductDto.packagesInStock, isShowStock: quickUpdateProductDto.isShowStock, }); await product.reload(); return product; } async findAllProduct() { const allProducts = await this.productModel.findAll(); return allProducts; } async findOne(jwtUserDTO: JwtUserDTO, slug: string) { const startedDate = await moment().subtract(1, 'month').toDate(); const endDate = await moment().add(1, 'day').toDate(); if (jwtUserDTO) { const user = await this.userModel.findOne({ include: [ { model: Organizations, attributes: [ 'id', 'role', 'isApproved', 'isActive', ], }, ], where: { id: jwtUserDTO.id, }, }); if (!user) throw new NotFoundException(); let whereCondition = {}; if (+user?.organization?.role === 3) { whereCondition = { ...whereCondition, isActive: 1, }; } const product = await this.productModel.findOne({ include: [ this.productImagesModel, MedRec, Strain, { model: ProductFavourite, where: { userId: jwtUserDTO.id }, required: false, }, Category, SubCategory, { model: this.userModel, attributes: ['id'], include: [ { model: this.brandCompanyModel, attributes: ['id', 'medRecId'], // model: this.brandModel, // attributes: ['id', 'brandName', 'slug', 'medRecId', 'profilePath', 'blockedRetailers'], // include: [ // { // model: this.businessModel, // attributes: ['id', 'businessName', 'slug', 'medRecId', 'profilePath'], // } // ] }, { model: this.brandModel, attributes: ['id', 'brandName', 'slug', 'profilePath', 'blockedRetailers'], } ], }, { model: ProductPriceHistory, where: { createdAt: { [Op.between]: [startedDate, endDate] }, }, attributes: ['price', 'createdAt'], required: false, }, ], where: { slug, ...whereCondition }, order: [ [ { model: ProductPriceHistory, as: 'productPriceHistory' }, 'createdAt', 'asc', ], ], }); if (!product) throw new NotFoundException('The product has been deactivated'); const productData = product.toJSON(); // const productOrder = await Order.findAll({ // attributes: [ // [Sequelize.fn('IFNULL', Sequelize.fn('sum', Sequelize.col('quantity')), 0), 'totalUnitSold'], // ], // where: { // status: 6, // isActive: 1, // productId:productData.id // }, // }); // let productOrderData = productOrder[0].toJSON(); // productData.totalUnitSold = productOrderData.totalUnitSold; // if (jwtUserDTO) { // if (product.user.stateId !== user.stateId) { // productData.canOrder = false // } else { // productData.canOrder = true // } // } return productData; } else { const product = await this.productModel.findOne({ include: [ this.productImagesModel, MedRec, Strain, Category, { model: this.userModel, attributes: ['id'], // include: [ // { // model: this.brandModel, // attributes: ['id', 'blockedRetailers'], // include: [ // { // model: this.businessModel, // attributes: ['id', 'businessName', 'slug', 'medRecId', 'profilePath'], // } // ] // } // ], }, { model: ProductPriceHistory, where: { createdAt: { [Op.between]: [startedDate, endDate] }, }, attributes: ['price', 'createdAt'], required: false, }, ], where: { slug, isActive: 1 }, order: [ [ { model: ProductPriceHistory, as: 'productPriceHistory' }, 'createdAt', 'asc', ], ], }); if (!product) throw new NotFoundException(); const productData = product.toJSON(); const productOrder = await Order.findAll({ attributes: [ [ Sequelize.fn( 'IFNULL', Sequelize.fn('sum', Sequelize.col('quantity')), 0, ), 'totalUnitSold', ], ], where: { status: 6, isActive: 1, productId: productData.id, }, }); const productOrderData = productOrder[0].toJSON(); productData.totalUnitSold = productOrderData.totalUnitSold; productData.canOrder = false; return productData; } } async findProduct(slug: string) { const startedDate = await moment().subtract(1, 'month').toDate(); const endDate = await moment().add(1, 'day').toDate(); const product = await this.productModel.findOne({ include: [ this.productImagesModel, MedRec, Strain, Category, SubCategory, { model: this.userModel, attributes: ['id'], // include: [ // { // model: this.brandModel, // attributes: ['id', 'blockedRetailers'], // include: [ // { // model: this.businessModel, // attributes: ['id', 'businessName', 'slug', 'medRecId', 'profilePath'], // } // ] // } // ], }, { model: ProductPriceHistory, where: { createdAt: { [Op.between]: [startedDate, endDate] }, }, attributes: ['price', 'createdAt'], required: false, }, ], where: { slug, isActive: 1 }, order: [ [ { model: ProductPriceHistory, as: 'productPriceHistory' }, 'createdAt', 'asc', ], ], }); if (!product) throw new NotFoundException(); const productData = product.toJSON(); // const productOrder = await Order.findAll({ // attributes: [ // [Sequelize.fn('IFNULL', Sequelize.fn('sum', Sequelize.col('quantity')), 0), 'totalUnitSold'], // ], // where: { // status: 6, // isActive: 1, // productId:productData.id // }, // }); // let productOrderData = productOrder[0].toJSON(); // productData.totalUnitSold = productOrderData.totalUnitSold; productData.canOrder = false; return productData; } async deleteProduct(slug: string) { const existProduct = await this.checkExist(slug); const product = await this.productModel.destroy({ where: { id: existProduct.id }, cascade: true, }); await this.productImagesModel.destroy({ where: { productId: existProduct.id }, }); return product; } async checkExist(slug: string) { const product = await this.productModel.findOne({ include: [Category], where: { slug: slug }, }); if (!product) throw new NotFoundException('Product Not Found'); return product; } async getMyProducts( jwtUserDTO: JwtUserDTO, brand: string, category: string, sortBy: string, keyword: string, offset = 0, limit = 10, ) { const user = await this.userModel.findOne({ where: { id: jwtUserDTO?.id }, }); if (!user) throw new NotFoundException('User Not Found'); let optionalFilter = {}; let dynamicSort = 'desc'; if (sortBy && ['asc', 'desc'].includes(sortBy)) { dynamicSort = sortBy; } if (brand) { optionalFilter = { ...optionalFilter, brandId: brand }; } if (category) { optionalFilter = { ...optionalFilter, categoryId: category }; } if (keyword) { optionalFilter = { ...optionalFilter, title: { [Op.like]: `%${keyword}%` }, }; } const { count, rows: product } = await this.productModel.findAndCountAll({ include: [Category, SubCategory, Brand], where: { [Op.and]: [{ userId: user?.id, brandCompanyId: user?.currentBrandCompanyId }], ...optionalFilter, }, order: [['createdAt', dynamicSort]], offset: offset ? offset * limit : 0, limit: limit, }); return { count: count, currentPage: offset ? +offset : 0, totalPages: Math.ceil(count / limit), product: product, }; } async getCurrentBrands( jwtUserDTO: JwtUserDTO, ) { const user = await this.userModel.findOne({ where: { id: jwtUserDTO?.id }, }); if (!user) throw new NotFoundException('User Not Found'); const data = await this.brandModel.findAll({ attributes:['id', 'brandName', 'slug'], where: { brandCompanyId: user?.currentBrandCompanyId, userId: jwtUserDTO.id, isActive: '1' }, }); return data; } async getAllProduct( jwtUserDTO?: JwtUserDTO, offset = 0, limit = 10, orderBy?: string, keyword?: string, category?: string, medRec?: string, priceMin?: number, priceMax?: number, thcMin?: number, thcMax?: number, strain?: string, ) { let condition = {}; let userCondition = {}; let medRecCondition = {}; if (jwtUserDTO.id) { condition = { id: jwtUserDTO.id }; userCondition = { userId: jwtUserDTO.id }; } let orderByTitle = 'asc'; const orderByField = 'createdAt'; let optionalFilter = {}; if (orderBy) { orderByTitle = orderBy; } else { orderByTitle = 'desc'; } if (keyword) { optionalFilter = { ...optionalFilter, title: { [Op.like]: `%${keyword}%` }, }; } if (category) { optionalFilter = { ...optionalFilter, categoryId: category }; } // if (medRec) { // optionalFilter = { ...optionalFilter, medRecId: medRec } // } if (priceMax) { optionalFilter = { ...optionalFilter, price: { [Op.between]: [priceMin, priceMax], }, }; } if (thcMax) { optionalFilter = { ...optionalFilter, thc: { [Op.between]: [thcMin, thcMax], }, }; //optionalFilter = { ...optionalFilter, thc: thc } } if (strain) { optionalFilter = { ...optionalFilter, strainId: strain }; } const user = await this.userModel.findOne({ include: [ { model: this.retailerModel, attributes: ['id', 'medRecId'] }, { model: BrandCompany, attributes: [ 'id', 'medRecId', ] } ], where: condition, }); if (jwtUserDTO.id) { const medRecId = user?.retailerCompany?.medRecId ? user?.retailerCompany?.medRecId : user?.brandCompany?.medRecId; medRecCondition = await { medRecId: medRecId }; } const { count, rows: products } = await this.productModel.findAndCountAll({ include: [ { model: this.userModel, attributes: ['id'], }, { model: this.brandModel, attributes: ['id', 'brandName', 'slug', 'blockedRetailers'], }, Category, SubCategory, // MedRec, Strain, { model: ProductFavourite, where: userCondition, required: false }, ], where: { [Op.and]: [{ isActive: '1', productVisibility: '1' }], ...medRecCondition, ...optionalFilter, }, order: [[orderByField, orderByTitle]], offset: offset ? offset * limit : 0, limit: limit, }); const maxValue = await this.productModel.findOne({ attributes: [ [Sequelize.fn('max', Sequelize.col('price')), 'price'], [Sequelize.fn('max', Sequelize.col('thc')), 'thc'], ], where: { isActive: 1, }, }); // const thc = await this.productModel.findOne( // { // attributes: [[Sequelize.fn('max', Sequelize.col('price')), 'max']], // }) return { count: count, currentPage: offset ? +offset : 0, totalPages: Math.ceil(count / limit), maxValue, products: products, }; } async changeProductStatus(slug: string) { const existProduct = await this.checkExist(slug); const updatedProduct = await existProduct.update({ isActive: +existProduct.isActive === 1 ? '2' : '1', }); return updatedProduct; } async changeProductStock(slug: string) { const existProduct = await this.checkExist(slug); const updatedProduct = await existProduct.update({ isShowStock: +existProduct.isShowStock === 1 ? '0' : '1', }); return updatedProduct; } async productReview(slug?: string, page?: string, perPage?: string) { const { count, rows: productReviews } = await Review.findAndCountAll({ where: { type: 1 }, order: [['id', 'desc']], offset: page ? parseInt(page) * parseInt(perPage) : 0, limit: parseInt(perPage), include: [{ model: Product, where: { slug: slug } }, this.userModel], }); return { count, productReviews }; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/products/products.controller.ts
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Put, Query, Request, UploadedFile, UseGuards, UseInterceptors, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { FileInterceptor } from '@nestjs/platform-express'; import { diskStorage } from 'multer'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { IResponse } from 'src/common/interfaces/response.interface'; import { v4 as uuidv4 } from 'uuid'; import { JwtAuthGuard } from './../auth/guards/jwt-auth.guard'; import { CreateProductDto } from './dto/create-product.dto'; import { QuickUpdateProductDto } from './dto/quick-update-product.dto'; import { UpdateProductDto } from './dto/update-product.dto'; import { ProductsService } from './products.service'; import path = require('path'); export const productStorage = { storage: diskStorage({ destination: '../assets', filename: (req, file, cb) => { let filename: string = '/products/' + path .parse( file.fieldname === 'labResults' ? 'product-lab-results' : 'product-', ) .name.replace(/\s/g, '') + uuidv4(); filename = filename; const extension: string = path.parse(file.originalname).ext; cb(null, `${filename}${extension}`); }, }), }; @Controller() export class ProductsController { constructor(private readonly productsService: ProductsService) {} @UseGuards(AuthGuard('jwt')) @HttpCode(200) @Post() @UseInterceptors(FileInterceptor('labResults', productStorage)) async addProduct( @Body() createProductDto: CreateProductDto, @Request() req, @UploadedFile() labResults, ): Promise<IResponse> { const isCreated = await this.productsService.addProduct( createProductDto, req.user, labResults, ); return new ResponseSuccess('Product added successfully.', isCreated); } @UseGuards(AuthGuard('jwt')) @Post('/image-upload') @UseInterceptors(FileInterceptor('file', productStorage)) async uploadProductImage(@UploadedFile() file): Promise<IResponse> { const isUploaded = await this.productsService.uploadProductImage(file); return new ResponseSuccess( 'Product image uploaded successfully.', isUploaded, ); } @UseGuards(AuthGuard('jwt')) @Delete('/image-remove') async removeProductImage( @Body('filePath') filePath: string, ): Promise<IResponse> { const isRemoved = await this.productsService.removeProductImage(filePath); return new ResponseSuccess( 'Product image removed successfully.', isRemoved, ); } @UseGuards(AuthGuard('jwt')) @Put(':slug') @UseInterceptors(FileInterceptor('labResults', productStorage)) async updateProduct( @Param('slug') slug: string, @Body() updateProductDto: UpdateProductDto, @Request() req, @UploadedFile() labResults, ): Promise<IResponse> { const product = await this.productsService.updateProduct( slug, updateProductDto, req.user, labResults, ); return new ResponseSuccess('Product updated successfully.', product); } @UseGuards(AuthGuard('jwt')) @Put('quick-edit/:slug') async quickUpdateProduct( @Param('slug') slug: string, @Body() quickUpdateProductDto: QuickUpdateProductDto, @Request() req, ): Promise<IResponse> { const product = await this.productsService.quickUpdateProduct( slug, quickUpdateProductDto, req.user, ); return new ResponseSuccess('Product updated successfully.', product); } @UseGuards(AuthGuard('jwt')) @Get() async findAll() { const product = await this.productsService.findAllProduct(); return new ResponseSuccess('Products.', product); } @UseGuards(AuthGuard('jwt')) @Get('my') async getMyProducts( @Request() req, @Query('offset') offset: string, @Query('limit') limit: string, @Query('brand') brand: string, @Query('category') category: string, @Query('sortBy') sortBy: string, @Query('keyword') keyword: string, ) { const product = await this.productsService.getMyProducts( req.user, brand, category, sortBy, keyword, +offset, +limit, ); return new ResponseSuccess('Products.', product); } @UseGuards(AuthGuard('jwt')) @Get('brands') async getCurrentBrands( @Request() req, ) { const data = await this.productsService.getCurrentBrands( req.user ); return new ResponseSuccess('Brands.', data); } @UseGuards(JwtAuthGuard) @Get('retailer') async getAllProduct( @Request() req, @Query('offset') offset: string, @Query('limit') limit: string, @Query('sortBy') orderBy: string, @Query('keyword') keyword: string, @Query('category') category: string, @Query('medRec') medRec: string, @Query('priceMin') priceMin: string, @Query('priceMax') priceMax: string, @Query('thcMin') thcMin: string, @Query('thcMax') thcMax: string, @Query('strain') strain: string, ) { const product = await this.productsService.getAllProduct( req.user, +offset, +limit, orderBy, keyword, category, medRec, +priceMin, +priceMax, +thcMin, +thcMax, strain, ); return new ResponseSuccess('Products.', product); } @Get('review') async productReview( @Query('slug') slug: string, @Query('page') page: string, @Query('limit') limit: string, ): Promise<IResponse> { const productReview = await this.productsService.productReview( slug, page, limit, ); return new ResponseSuccess('reviews', productReview); } @UseGuards(AuthGuard('jwt')) @Get(':slug') async findOne(@Request() req, @Param('slug') slug: string) { const product = await this.productsService.findOne(req.user, slug); return new ResponseSuccess('Product.', product); } @Get(':slug/admin') async findProduct(@Param('slug') slug: string) { const product = await this.productsService.findProduct(slug); return new ResponseSuccess('Product.', product); } @UseGuards(AuthGuard('jwt')) @Delete(':slug') async deleteProduct(@Param('slug') slug: string) { const product = await this.productsService.deleteProduct(slug); return new ResponseSuccess('Product deleted successfully.', product); } @UseGuards(AuthGuard('jwt')) @Post('change/status/:slug') async changeProductStatus(@Param('slug') slug: string): Promise<IResponse> { const updatedProduct = await this.productsService.changeProductStatus(slug); if (+updatedProduct.isActive === 1) { return new ResponseSuccess('Product has been enabled', updatedProduct); } else { return new ResponseSuccess('Product has been disabled', updatedProduct); } } @UseGuards(AuthGuard('jwt')) @Post('change/stock/:slug') async changeProductStock(@Param('slug') slug: string): Promise<IResponse> { const updatedProduct = await this.productsService.changeProductStock(slug); if (+updatedProduct.isShowStock === 1) { return new ResponseSuccess( 'Show unit stock on marketplace', updatedProduct, ); } else { return new ResponseSuccess( 'Hide unit stock on marketplace', updatedProduct, ); } } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/products/products.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Brand } from 'src/models/brand.model'; import { BrandCompany } from 'src/models/brandCompany.model'; import { Order } from 'src/models/order.model'; import { Product } from 'src/models/product.model'; import { ProductImages } from 'src/models/productImages.model'; import { ProductPriceHistory } from 'src/models/productPriceHistory.model'; import { Retailer } from 'src/models/retailer.model'; import { User } from 'src/models/user.model'; import { ProductsController } from './products.controller'; import { ProductsService } from './products.service'; @Module({ imports: [ SequelizeModule.forFeature([ Product, ProductImages, User, BrandCompany, Brand, Retailer, Order, ProductPriceHistory, ]), ], controllers: [ProductsController], providers: [ProductsService, MailServiceService], }) export class ProductsModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules/products
/content/gmx-projects/gmx-admin/backend/src/modules/products/dto/create-product.dto.ts
import { IsNotEmpty, IsOptional, IsString } from 'class-validator'; export class CreateProductDto { @IsNotEmpty() brandCompanyId: string; @IsNotEmpty() brandId: string; @IsNotEmpty() @IsString() title: string; @IsNotEmpty() categoryId: string; @IsOptional() subCategoryId: string; @IsNotEmpty() medRecId: string; @IsNotEmpty() unitWeight: string; @IsNotEmpty() unitPerPackage: string; @IsNotEmpty() // @IsNumber() price: string; @IsOptional() packagesInStock: string; @IsOptional() isShowStock: boolean; @IsOptional() strainId: string; @IsOptional() dominant: string; @IsOptional() harvested: Date; @IsNotEmpty() // @IsNumber() thc: string; @IsOptional() flavor: string; @IsOptional() description: string; // @IsNotEmpty() @IsOptional() productImages: string[]; @IsOptional() labResultsPath: any; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/products
/content/gmx-projects/gmx-admin/backend/src/modules/products/dto/update-product.dto.ts
import { PartialType } from '@nestjs/mapped-types'; import { CreateProductDto } from './create-product.dto'; export class UpdateProductDto extends PartialType(CreateProductDto) {}
0
/content/gmx-projects/gmx-admin/backend/src/modules/products
/content/gmx-projects/gmx-admin/backend/src/modules/products/dto/quick-update-product.dto.ts
import { IsNotEmpty, IsOptional, IsString } from 'class-validator'; export class QuickUpdateProductDto { @IsNotEmpty() @IsString() title: string; @IsNotEmpty() categoryId: string; @IsOptional() subCategoryId: string; @IsNotEmpty() unitWeight: string; @IsNotEmpty() unitPerPackage: string; @IsNotEmpty() // @IsNumber() price: string; @IsOptional() packagesInStock: string; @IsOptional() isShowStock: boolean; }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/strains/strains.controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { StrainsService } from './strains.service'; @UseGuards(JwtAuthGuard) @Controller() export class StrainsController { constructor(private readonly strainsService: StrainsService) {} @Get() async getAllStrains() { const strains = await this.strainsService.getAllStrains(); return new ResponseSuccess('Strains', strains); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/strains/strains.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { Strain } from 'src/models/strain.model'; import { StrainsController } from './strains.controller'; import { StrainsService } from './strains.service'; @Module({ imports: [SequelizeModule.forFeature([Strain])], controllers: [StrainsController], providers: [StrainsService], }) export class StrainsModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/strains/strains.service.ts
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Strain } from 'src/models/strain.model'; @Injectable() export class StrainsService { constructor( @InjectModel(Strain) private strainModel: typeof Strain, ) {} async getAllStrains() { const strains = await this.strainModel.findAll({ where: { isActive: '1' }, }); return strains; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/categories/categories.controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { CategoriesService } from './categories.service'; @UseGuards(JwtAuthGuard) @Controller() export class CategoriesController { constructor(private readonly categoriesService: CategoriesService) {} @Get() async getAllCategories() { const categories = await this.categoriesService.getAllCategories(); return new ResponseSuccess('Categories', categories); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/categories/categories.service.ts
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Category } from 'src/models/category.model'; @Injectable() export class CategoriesService { constructor( @InjectModel(Category) private categoryModel: typeof Category, ) {} async getAllCategories() { const categories = await this.categoryModel.findAll({ where: { isActive: '1' }, }); return categories; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/categories/categories.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { Category } from 'src/models/category.model'; import { CategoriesController } from './categories.controller'; import { CategoriesService } from './categories.service'; @Module({ imports: [SequelizeModule.forFeature([Category])], controllers: [CategoriesController], providers: [CategoriesService], }) export class CategoriesModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/subscription/subscription.service.ts
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Settings } from 'src/models/settings.model'; import { User } from 'src/models/user.model'; import { UserSubscription } from 'src/models/userSubscription.model'; const moment = require('moment'); const fs = require('fs'); @Injectable() export class SubscriptionService { constructor( @InjectModel(Settings) private settingsModel: typeof Settings, @InjectModel(UserSubscription) private userSubscriptionModel: typeof UserSubscription, @InjectModel(User) private userModel: typeof User, ) {} async updateSubscription(res: any) { try { fs.appendFile( 'src/modules/subscription/response.txt', JSON.stringify(res), (fsErr) => { if (fsErr) { console.log('fsErr', fsErr); } }, ); switch (res.type) { case 'customer.subscription.updated': if (res.data?.object?.plan?.id) { const userSubscription = await this.userSubscriptionModel.findOne({ where: { subscriptionId: res.data?.object?.id, }, order: [['createdAt', 'desc']], }); if (userSubscription) { const subscribed = []; subscribed['userId'] = userSubscription.userId; subscribed['planId'] = userSubscription.planId; subscribed['customerId'] = userSubscription.customerId; subscribed['subscriptionToken'] = userSubscription.subscriptionToken; subscribed['subscriptionId'] = userSubscription.subscriptionId; subscribed['status'] = res.data?.object?.status; subscribed['amount'] = null; if (res.data?.object?.plan?.amount) { subscribed['amount'] = res.data?.object?.plan?.amount / 100; } subscribed['resJson'] = JSON.stringify(res); subscribed['startDate'] = await moment( res.data?.current_period_start, ).format('YYYY-MM-DD'); //current Date subscribed['endDate'] = await moment( res.data?.current_period_end, ).format('YYYY-MM-DD'); //end date const newSubscriptionId = await this.userSubscriptionModel.create( { ...subscribed }, ); const user = await this.userModel.findOne({ where: { id: userSubscription.userId, }, }); user.update({ planExpiryDate: subscribed['endDate'], subscriptionId: newSubscriptionId.id, }); return user; } } break; default: console.log(`Unhandled event type ${event.type}`); } } catch (err) { console.log(err); fs.appendFile( 'src/modules/subscription/error-logs.txt', JSON.stringify(err), (fsErr) => { if (fsErr) { console.log('fsErr', fsErr); } }, ); } } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/subscription/subscription.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { Settings } from 'src/models/settings.model'; import { User } from 'src/models/user.model'; import { UserSubscription } from 'src/models/userSubscription.model'; import { SubscriptionController } from './subscription.controller'; import { SubscriptionService } from './subscription.service'; @Module({ imports: [SequelizeModule.forFeature([Settings, UserSubscription, User])], controllers: [SubscriptionController], providers: [SubscriptionService], }) export class SubscriptionModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/subscription/subscription.controller.ts
import { All, Controller, Request } from '@nestjs/common'; import { SubscriptionService } from './subscription.service'; const fs = require('fs'); @Controller() export class SubscriptionController { constructor(private readonly subscriptionService: SubscriptionService) {} // @Get() @All() async updateSubscription(@Request() req) { // fs.appendFile('./response.txt', JSON.stringify(req.body), (err) => { // if (err) { // console.log(err); // } // }) // fs.writeFile('./response.txt', JSON.stringify(req.body),function (err) { // if (err) { // return console.log(err); // } // }) // req.body const response = await this.subscriptionService.updateSubscription( req.body, ); } } // http://192.168.1.152:3333/api/v1 // https://gmx.nyusoft.in:6002/api/v1/webhook-expired-plan
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/favourite/favourites.service.ts
import { BadRequestException, Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Brand } from 'src/models/brand.model'; import { Category } from 'src/models/category.model'; import { Product } from 'src/models/product.model'; import { ProductFavourite } from 'src/models/productFavourite.model'; import { SubCategory } from 'src/models/subCategory.model'; import { User } from 'src/models/user.model'; import { JwtUserDTO } from '../auth/dto/JwtUser.dto'; const fs = require('fs'); @Injectable() export class FavouritesService { constructor( @InjectModel(Product) private productModel: typeof Product, @InjectModel(ProductFavourite) private productFavouriteModel: typeof ProductFavourite, ) {} async handleFavourites(jwtUserDTO: JwtUserDTO, slug: string) { const product = await this.productModel.findOne({ where: { slug: slug }, }); if (!product) throw new BadRequestException('Product Not Found'); let response; const existingProduct = await this.productFavouriteModel.findOne({ where: { userId: jwtUserDTO.id, productId: product.id }, paranoid: false, }); if (!existingProduct) { const favourite = await this.productFavouriteModel .create({ userId: jwtUserDTO.id, productId: product.id, }) .then(async function (item) { response = { status: true, message: 'Product Added to Favourite', }; }) .catch(function (err) { response = { status: false, message: 'Something went wrong', }; }); } else { if (existingProduct.deletedAt) { existingProduct.restore(); response = { status: true, message: 'Product Added to Favourite', }; } else { existingProduct.destroy(); response = { status: true, message: 'Product Removed from Favourite', }; } } return response; } async myFavourites(jwtUserDTO: JwtUserDTO, offset = 0, limit = 10) { const { count, rows: favouriteProducts } = await this.productFavouriteModel.findAndCountAll({ include: [ { model: Product, include: [{ model: User, include: [Brand] }, Category, SubCategory], where: { isActive: 1 }, }, ], where: { userId: jwtUserDTO.id, }, offset: offset ? offset * limit : 0, limit: limit, }); return { count: count, currentPage: offset ? +offset : 0, totalPages: Math.ceil(count / limit), favouriteProducts: favouriteProducts, }; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/favourite/favourites.controller.ts
import { Controller, Get, Param, Post, Query, Request, UseGuards, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { ResponseError, ResponseSuccess } from 'src/common/dto/response.dto'; import { IResponse } from 'src/common/interfaces/response.interface'; import { FavouritesService } from './favourites.service'; @UseGuards(AuthGuard('jwt')) @Controller() export class FavouritesController { constructor(private readonly favouritesService: FavouritesService) {} @Post('handle/favourite/:slug') async handleFavourites( @Request() req, @Param('slug') slug: string, ): Promise<IResponse> { const favouriteProducts = await this.favouritesService.handleFavourites( req.user, slug, ); if (favouriteProducts.status) { return new ResponseSuccess(favouriteProducts.message, favouriteProducts); } else { return new ResponseError(favouriteProducts.message, favouriteProducts); } } @Get('') async myFavourites( @Request() req, @Query('offset') offset: string, @Query('limit') limit: string, ): Promise<IResponse> { const favouriteProducts = await this.favouritesService.myFavourites( req.user, +offset, +limit, ); return new ResponseSuccess('favouriteProducts', favouriteProducts); } // @Post(':orderId/:action') // async updateOrder( // @Param('orderId') orderId: string, // @Param('action') action: string, // @Request() req, // ){ // const orders = await this.favouritesService.updateOrders(req.user, orderId, action); // if(orders.status){ // return new ResponseSuccess(orders.message, orders.status) // } else { // return new ResponseError('Something went wrong', false) // } // } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/favourite/favourites.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { Product } from 'src/models/product.model'; import { ProductFavourite } from 'src/models/productFavourite.model'; import { User } from 'src/models/user.model'; import { FavouritesController } from './favourites.controller'; import { FavouritesService } from './favourites.service'; @Module({ imports: [SequelizeModule.forFeature([ProductFavourite, Product, User])], controllers: [FavouritesController], providers: [FavouritesService], }) export class FavouritesModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/states/states.controller.ts
import { Controller, Get } from '@nestjs/common'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { StatesService } from './states.service'; @Controller() export class StatesController { constructor(private readonly statesService: StatesService) {} @Get() async getAllStates() { const states = await this.statesService.getAllStates(); return new ResponseSuccess('States', states); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/states/states.service.ts
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { State } from 'src/models/state.model'; @Injectable() export class StatesService { constructor( @InjectModel(State) private stateModel: typeof State, ) {} async getAllStates() { const states = await this.stateModel.findAll({ where: { isActive: '1' }, }); return states; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/states/states.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { State } from 'src/models/state.model'; import { StatesController } from './states.controller'; import { StatesService } from './states.service'; @Module({ imports: [SequelizeModule.forFeature([State])], controllers: [StatesController], providers: [StatesService], }) export class StatesModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/sub-categories/sub-categories.controller.ts
import { Controller, Get, Param, UseGuards } from '@nestjs/common'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { SubCategoriesService } from './sub-categories.service'; @UseGuards(JwtAuthGuard) @Controller() export class SubCategoriesController { constructor(private readonly subCategoriesService: SubCategoriesService) {} @Get(':id') async getSubCategories(@Param('id') categoryId: string) { const subCategories = await this.subCategoriesService.getSubCategories( categoryId, ); return new ResponseSuccess('Sub Categories', subCategories); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/sub-categories/sub-categories.service.ts
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { SubCategory } from 'src/models/subCategory.model'; @Injectable() export class SubCategoriesService { constructor( @InjectModel(SubCategory) private subCategoryModel: typeof SubCategory, ) {} async getSubCategories(categoryId: string) { const subCategories = await this.subCategoryModel.findAll({ where: { categoryId: categoryId, isActive: '1' }, }); return subCategories; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/sub-categories/sub-categories.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { SubCategory } from 'src/models/subCategory.model'; import { SubCategoriesController } from './sub-categories.controller'; import { SubCategoriesService } from './sub-categories.service'; @Module({ imports: [SequelizeModule.forFeature([SubCategory])], controllers: [SubCategoriesController], providers: [SubCategoriesService], }) export class SubCategoriesModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/dashboard/dashboard.controller.ts
import { Body, Controller, Get, Post, Request, UseGuards, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { DashboardService } from './dashboard.service'; @UseGuards(AuthGuard('jwt')) @Controller() export class DashboardController { constructor(private readonly dashboardService: DashboardService) {} @Get('/orders/history') async getOrdersData(@Request() req) { const ordersHistoryData = await this.dashboardService.getOrdersData( req.user, ); return new ResponseSuccess('ordersHistoryData', ordersHistoryData); } @Post('/sold/by/strain') async getSoldByStrain( @Request() req, @Body('selectedMonth') selectedMonth: string, ) { const soldByStrainData = await this.dashboardService.getSoldByStrain( req.user, selectedMonth, ); return new ResponseSuccess('soldByStrainData', soldByStrainData); } @Post('/sold/by/category') async getSoldByCategory( @Request() req, @Body('selectedMonth') selectedMonth: string, ) { const soldByCategoryData = await this.dashboardService.getSoldByCategory( req.user, selectedMonth, ); return new ResponseSuccess('soldByCategoryData', soldByCategoryData); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/dashboard/dashboard.service.ts
import { Injectable, NotFoundException } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { Op, Sequelize } from 'sequelize'; import { Brand } from 'src/models/brand.model'; import { Category } from 'src/models/category.model'; import { Drivers } from 'src/models/drivers.model'; import { Order } from 'src/models/order.model'; // import { OrderItem } from 'src/models/orderInvoice.model'; import { Product } from 'src/models/product.model'; import { User } from 'src/models/user.model'; import { JwtUserDTO } from '../auth/dto/JwtUser.dto'; import { OrderInvoice } from 'src/models/orderInvoice.model'; import { OrderInvoiceItems } from 'src/models/orderInvoiceItems.model'; const moment = require('moment'); @Injectable() export class DashboardService { constructor( @InjectModel(Order) private order: typeof Order, @InjectModel(OrderInvoice) private orderInvoiceModal: typeof OrderInvoice, @InjectModel(OrderInvoiceItems) private orderInvoiceItemsModal: typeof OrderInvoiceItems, @InjectModel(Brand) private brandModel: typeof Brand, ) {} async getOrdersData(jwtUserDTO: JwtUserDTO) { const brand = await this.brandModel.findOne({ where: { userId: jwtUserDTO.id, }, }); if (!brand) { throw new NotFoundException(); } const ordersHistoryData = await this.order.findAll({ include: [ { model: User, }, Drivers, { //model: OrderItem, include: [ { model: Product, }, Category, ], }, ], where: { brandId: brand.id, }, order: [['id', 'desc']], limit: 5, }); return ordersHistoryData; } async getSoldByStrain(jwtUserDTO: JwtUserDTO, selectedMonth: string) { const brand = await this.brandModel.findOne({ where: { userId: jwtUserDTO.id, }, }); if (!brand) { throw new NotFoundException(); } const startDate = moment(selectedMonth) .startOf('month') .add(1, 'day') .toDate(); const endDate = moment(selectedMonth).endOf('month').toDate(); const soldByStrainData = await this.orderInvoiceModal.findAll({ // logging: console.log, include: [ { model: OrderInvoiceItems, include: [ { model: Product, attributes: ['id', 'strainId'], }, ], }, ], attributes: [ [ Sequelize.literal(`( SELECT title FROM strains WHERE strains.id = orderInvoiceItems.strainId )`), 'strainTitle', ], [Sequelize.literal('sum(orderInvoiceItems.quantity)'), 'totalLbSold'], ], where: { brandId: brand.id, status: { [Op.or]: [4, 5] }, updatedAt: { [Op.between]: [startDate, endDate] }, }, order: [[Sequelize.literal('strainTitle'), 'asc']], group: ['orderInvoiceItems.product.strainId'], }); return soldByStrainData; } async getSoldByCategory(jwtUserDTO: JwtUserDTO, selectedMonth: string) { const brand = await this.brandModel.findOne({ where: { userId: jwtUserDTO.id, }, }); if (!brand) { throw new NotFoundException(); } const startDate = moment(selectedMonth) .startOf('month') .add(1, 'day') .toDate(); const endDate = moment(selectedMonth).endOf('month').toDate(); const soldByStrainData = await this.orderInvoiceModal.findAll({ include: [ { model: OrderInvoiceItems, include: [ { model: Product, attributes: ['id', 'categoryId'], }, ], }, ], attributes: [ [ Sequelize.literal(`( SELECT title FROM categories WHERE categories.id = orderInvoiceItems.categoryId )`), 'categoryTitle', ], [Sequelize.literal('sum(orderInvoiceItems.quantity)'), 'totalLbSold'], ], where: { brandId: brand.id, status: { [Op.or]: [4, 5] }, updatedAt: { [Op.between]: [startDate, endDate] }, }, order: [[Sequelize.literal('categoryTitle'), 'asc']], group: ['orderInvoiceItems.product.categoryId'], }); return soldByStrainData; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/dashboard/dashboard.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { Brand } from 'src/models/brand.model'; import { Order } from 'src/models/order.model'; import { OrderInvoice } from 'src/models/orderInvoice.model'; import { OrderInvoiceItems } from 'src/models/orderInvoiceItems.model'; import { DashboardController } from './dashboard.controller'; import { DashboardService } from './dashboard.service'; @Module({ imports: [SequelizeModule.forFeature([Order, OrderInvoice, OrderInvoiceItems, Brand])], controllers: [DashboardController], providers: [DashboardService], }) export class DashboardModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/auth/auth.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { AuthService } from './auth.service'; describe('AuthService', () => { let service: AuthService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [AuthService], }).compile(); service = module.get<AuthService>(AuthService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/auth/auth.controller.ts
import { Body, Controller, Get, Post, Request as RequestDec, UploadedFiles, UseGuards, UseInterceptors, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { FileFieldsInterceptor } from '@nestjs/platform-express'; import { diskStorage } from 'multer'; import { ResponseError, ResponseSuccess } from 'src/common/dto/response.dto'; import { IResponse } from 'src/common/interfaces/response.interface'; import { FileHelper } from 'src/services/FileHelper.service'; import { v4 as uuidv4 } from 'uuid'; import { AuthService } from './auth.service'; import { ResetPasswordDTO } from './dto/ResetPassword.dto'; import { UserForgotPassword } from './dto/UserForgotPassword.dto'; import { RetailerRegisterDTO } from './dto/retailerRegister.dto'; import path = require('path'); const documentPath = '/uploads/documents'; //document file uploads export const documentStorage = { storage: diskStorage({ // destination: '.' + documentPath, destination: '../assets', filename: (req, file, cb) => { let filename: string = '/documents/' + path.parse('license-').name.replace(/\s/g, '') + uuidv4(); filename = filename; const extension: string = path.parse(file.originalname).ext; cb(null, `${filename}${extension}`); }, }), }; @Controller() export class AuthController { constructor(private readonly authService: AuthService) {} @UseGuards(AuthGuard('local')) @Post('login') async login(@RequestDec() req): Promise<IResponse> { const user: any = req.user; const access_token = await this.authService.signJWT(user); return new ResponseSuccess('Login', { access_token, user }); } // @Post('register') // @UseInterceptors(FileInterceptor('licenseDocument', documentStorage)) // async register(@Body() registerUser: UserRegisterDTO, @UploadedFile() file,): Promise<IResponse> { // const isRegistered = await this.authService.registerUser(registerUser, file); // return new ResponseSuccess('Register', isRegistered); // } @Post('register') @UseInterceptors( FileFieldsInterceptor( [ { name: 'medRecCertificatePath', maxCount: 1, }, { name: 'resaleLicensePath', maxCount: 1, }, { name: 'profileDocument', maxCount: 1, }, ], { storage: diskStorage({ destination: '../assets', filename: FileHelper.customFileName, }), }, ), ) async register( @Body() registerUser: RetailerRegisterDTO, @UploadedFiles() file: { avatar?: []; background?: [] }, ): Promise<IResponse> { const isRegistered = await this.authService.registerUser( registerUser, file, ); return new ResponseSuccess('Register', isRegistered); } @Get('getServerConfiguration') async getServerConfiguration(): Promise<IResponse> { // var date = moment(); // console.log(date); return new ResponseSuccess('Configuration ', { today: new Date() }); // return new ResponseSuccess("Configuration ", { "today": new Date("2021/11/03") }); } @Post('forgot-password') async forgotPassword( @Body() userForgotPassword: UserForgotPassword, ): Promise<IResponse> { const isLinkSend = await this.authService.forgotPassword( userForgotPassword, ); return new ResponseSuccess('Password rest link has been sent', isLinkSend); } @Post('reset-password') async resetPassword( @Body() resetPasswordDTO: ResetPasswordDTO, ): Promise<IResponse> { const isLinkSend = await this.authService.resetPassword( resetPasswordDTO.token, resetPasswordDTO.password, resetPasswordDTO.confirm_password, ); if (isLinkSend.status) { return new ResponseSuccess( 'Password has been reset successfully, you can log in now', isLinkSend, ); } else { return new ResponseError(isLinkSend.message, isLinkSend); } } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/auth/auth.controller.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { AuthController } from './auth.controller'; describe('AuthController', () => { let controller: AuthController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [AuthController], }).compile(); controller = module.get<AuthController>(AuthController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); });
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/auth/auth.service.ts
import { MailerService } from '@nestjs-modules/mailer'; import { ForbiddenException, Injectable, UnauthorizedException, UnprocessableEntityException, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { InjectModel } from '@nestjs/sequelize'; import { Op } from 'sequelize'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { Organizations } from 'src/models/organizations.model'; import { Retailer } from 'src/models/retailer.model'; import { Settings } from 'src/models/settings.model'; import { Stores } from 'src/models/stores.model'; import { User } from 'src/models/user.model'; import { HelperService } from 'src/services/Helper.service'; import { UserService } from '../user/user.service'; import { EmailTemplate } from './../../models/emailTemplate.model'; import { UserAuthenticateInterface } from './../user/interfaces/userAuthenticate.interface'; import { JwtUserDTO } from './dto/JwtUser.dto'; import { UserForgotPassword } from './dto/UserForgotPassword.dto'; import { UserLoginDTO } from './dto/UserLogin.dto'; import { RetailerRegisterDTO } from './dto/retailerRegister.dto'; const bcrypt = require('bcryptjs'); const { FRONEND_BASE_URL, ADMIN_BASE_URL } = process.env; @Injectable() export class AuthService { constructor( private readonly userService: UserService, private jwtService: JwtService, @InjectModel(User) private userModel: typeof User, @InjectModel(Organizations) private organizationsModel: typeof Organizations, @InjectModel(Retailer) private retailerModel: typeof Retailer, @InjectModel(Stores) private storesModel: typeof Stores, @InjectModel(EmailTemplate) private emailTemplateModel: typeof EmailTemplate, @InjectModel(Settings) private settingsModel: typeof Settings, private readonly mailerService: MailerService, private mailService?: MailServiceService, ) {} async login(userLoginDTO: UserLoginDTO) { const userAuthenticateInterface: UserAuthenticateInterface = { username: userLoginDTO.username, password: userLoginDTO.password, }; const user = await this.userService.authenticate(userAuthenticateInterface); if (!user) throw new UnauthorizedException(); return user; } async signJWT(user: JwtUserDTO) { const payload = { id: user.id, email: user.email, }; const token = this.jwtService.sign(payload); return token; } async registerUser(userRegisterDTO: RetailerRegisterDTO, file) { const checkEmail = await this.checkEmail(userRegisterDTO.email); if (userRegisterDTO.password !== userRegisterDTO.confirmPassword) { throw new ForbiddenException( 'Password and confirm password does not match.', ); } const profileDocumentPath = (await file) ? file?.profileDocument ? file.profileDocument[0]?.filename : null : null; const medRecCertificatePath = (await file) ? file.medRecCertificatePath ? file?.medRecCertificatePath[0]?.filename : null : null; const resaleLicensePath = (await file) ? file.resaleLicensePath ? file?.resaleLicensePath[0]?.filename : null : null; const hash = bcrypt.hashSync(userRegisterDTO.password, 10); // let slug = (userRegisterDTO.firstName+' '+userRegisterDTO.lastName).toLowerCase().replace(/ /g,'-').replace(/[^\w-]+/g,''); let slug = userRegisterDTO.name .toLowerCase() .replace(/ /g, '-') .replace(/[^\w-]+/g, ''); const existUserWithSlug = await this.userModel.findAndCountAll({ where: { slug: { [Op.like]: `%${slug}%`, }, }, }); if (existUserWithSlug.count) { slug = slug + '-' + existUserWithSlug.count; } const user = await this.userModel.create({ isApproved: 2, name: userRegisterDTO.name, slug: slug, email: userRegisterDTO.email, password: hash, phoneNumber: userRegisterDTO.phoneNumber, planExpiryDate: userRegisterDTO.planExpiryDate, subscriptionId: userRegisterDTO.subscriptionId, }); const organization = await this.organizationsModel.create({ isApproved: 2, userId: user.id, role: userRegisterDTO.role, }); let companySlug = userRegisterDTO.companyName .toLowerCase() .replace(/ /g, '-') .replace(/[^\w-]+/g, ''); const existCompanyWithSlug = await this.retailerModel.findAndCountAll({ where: { slug: { [Op.like]: `%${slug}%`, }, }, }); if (existCompanyWithSlug.count) { slug = slug + '-' + existCompanyWithSlug.count; } const retailer = await this.retailerModel.create({ userId: user.id, organizationId: organization?.id, companyName: userRegisterDTO.companyName, slug: companySlug, medRecId: userRegisterDTO.medRecId, website: userRegisterDTO.website !== '' && userRegisterDTO.website !== null ? userRegisterDTO.website : null, profilePath: profileDocumentPath, }); await user.update({ organizationId: organization?.id }); const store = await this.storesModel.create({ userId: user.id, retailerCompanyID: retailer?.id, type: 3, isDefault: true, managerName: userRegisterDTO.companyName, phoneNumber: userRegisterDTO.phoneNumber, address: userRegisterDTO.address !== '' && userRegisterDTO.address !== null ? userRegisterDTO.address : null, stateId: userRegisterDTO.selectedState, zipCode: userRegisterDTO.zipCode, licenseNumber: userRegisterDTO.licenseNumber, certificatePath: medRecCertificatePath, resaleLicensePath: resaleLicensePath, }); await retailer.update({ defaultStoreId: store?.id, }); const helperService = await new HelperService(); const userData = { NAME: user?.name, LINK: FRONEND_BASE_URL + '/sign-in', }; const retailerEmailContent = await helperService.emailTemplateContent( 1, userData, ); this.mailService.sendMail( user.email, retailerEmailContent.subject, retailerEmailContent.body, ); const adminData = { NAME: user?.name, EMAIL: user.email, ROLE: 'Retailer', LINK: ADMIN_BASE_URL + 'retailers/edit/' + user.id, }; const adminEmailContent = await helperService.emailTemplateContent( 5, adminData, ); const adminEmail = await helperService.getSettings( this.settingsModel, 'info_email', ); this.mailService.sendMail( adminEmail.description, adminEmailContent.subject, adminEmailContent.body, ); return user; } async forgotPassword(userForgotPassword: UserForgotPassword) { const user = await this.userModel.findOne({ where: { email: userForgotPassword.email }, }); if (!user) throw new UnprocessableEntityException('Invalid email.'); const verification_token = bcrypt.hashSync(`${user.email}-${user.id}`, 10); await user.update({ verification_token: verification_token, }); const helperService = await new HelperService(); const userData = { // 'NAME': user.firstName+(user.lastName ? ' '+user.lastName : ''), NAME: user?.name, LINK: FRONEND_BASE_URL + '/reset-password?token=' + verification_token, LINK_1: FRONEND_BASE_URL + '/contact-us', }; const emailContent = await helperService.emailTemplateContent(2, userData); this.mailService.sendMail( user.email, emailContent.subject, emailContent.body, ); return true; } async resetPassword( token: string, password: string, confirm_password: string, ) { const status = true; const message = ''; const user = await this.userModel.findOne({ attributes: ['password', 'id'], where: { verification_token: token, // deletedAt: null }, }); if (!user) { return { status: false, message: "User doesn't exist", }; // throw new BadRequestException(); } if (user.verification_token) { return { status: false, message: 'Password has already been reset, please login', }; } if (password !== confirm_password) { return { status: false, message: 'Password and confirm password mismatched', }; } const hash = bcrypt.hashSync(password, 10); const userExisted = await this.userModel.findOne({ where: { id: user.id, // deletedAt: null }, }); await user.update({ password: hash, verification_token: null, }); return { status, message }; } async checkEmail(emailId) { const emailExist = await this.userModel.findOne({ where: { email: emailId, }, }); if (emailExist) { throw new UnprocessableEntityException( 'Email already exist, Please try another.', ); } } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/auth/auth.module.ts
import { MailerModule } from '@nestjs-modules/mailer'; import { Module } from '@nestjs/common'; import { JwtModule } from '@nestjs/jwt'; import { PassportModule } from '@nestjs/passport'; import { SequelizeModule } from '@nestjs/sequelize'; import { AppConstants } from 'src/constants/app.constant'; import { MailServiceService } from 'src/mail-service/mail-service.service'; import { EmailTemplateFooter } from 'src/models/emailTemplateFooter.model'; import { EmailTemplateHeader } from 'src/models/emailTemplateHeader.model'; import { Organizations } from 'src/models/organizations.model'; import { Retailer } from 'src/models/retailer.model'; import { Settings } from 'src/models/settings.model'; import { Stores } from 'src/models/stores.model'; import { UserModule } from '../user/user.module'; import { EmailTemplate } from './../../models/emailTemplate.model'; import { AuthController } from './auth.controller'; import { AuthService } from './auth.service'; import { JwtStrategy } from './strategy/jwt.strategy'; import { LocalStrategy } from './strategy/local.strategy'; import { OptionalStrategy } from './strategy/optional.strategy'; require('dotenv').config(); const { SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD, SMTP_FROM_NAME, SMTP_FROM_EMAIL, } = process.env; @Module({ imports: [ UserModule, PassportModule, JwtModule.register({ secret: AppConstants.jwtSecret, signOptions: { expiresIn: '1y' }, }), MailerModule.forRoot({ transport: { host: SMTP_HOST, port: SMTP_PORT, secure: false, auth: { user: SMTP_USERNAME, pass: SMTP_PASSWORD, }, }, // defaults: { // from: '"' + SMTP_FROM_NAME + '" ' + "<" + SMTP_FROM_EMAIL + ">" // }, }), SequelizeModule.forFeature([ Organizations, Retailer, Stores, EmailTemplateHeader, EmailTemplate, EmailTemplateFooter, Settings, ]), ], controllers: [AuthController], providers: [ AuthService, MailServiceService, LocalStrategy, JwtStrategy, OptionalStrategy, ], }) export class AuthModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules/auth
/content/gmx-projects/gmx-admin/backend/src/modules/auth/dto/ResetPassword.dto.ts
import { IsNotEmpty, IsString, MinLength } from 'class-validator'; export class ResetPasswordDTO { @IsNotEmpty() @IsString() token: string; @IsNotEmpty() @IsString() @MinLength(6) password: string; @IsNotEmpty() @IsString() @MinLength(6) confirm_password: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/auth
/content/gmx-projects/gmx-admin/backend/src/modules/auth/dto/UserForgotPassword.dto.ts
import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; export class UserForgotPassword { @IsNotEmpty() @IsString() @IsEmail() email: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/auth
/content/gmx-projects/gmx-admin/backend/src/modules/auth/dto/JwtUser.dto.ts
export class JwtUserDTO { email: string; id: number; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/auth
/content/gmx-projects/gmx-admin/backend/src/modules/auth/dto/UserLogin.dto.ts
import { IsNotEmpty, IsString } from 'class-validator'; export class UserLoginDTO { @IsNotEmpty() @IsString() username: string; @IsNotEmpty() @IsString() password: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/auth
/content/gmx-projects/gmx-admin/backend/src/modules/auth/dto/userRegister.dto.ts
import { IsEmail, IsNotEmpty, IsOptional, IsString, Length, } from 'class-validator'; export class UserRegisterDTO { @IsNotEmpty() role: number; @IsOptional() name: string; @IsNotEmpty() @IsEmail() @Length(1, 255) email: string; @IsNotEmpty() @IsString() password: string; @IsNotEmpty() @IsString() confirmPassword: string; @IsOptional() planId: string; @IsOptional() planExpiryDate: Date; @IsOptional() subscriptionId: number; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/auth
/content/gmx-projects/gmx-admin/backend/src/modules/auth/dto/retailerRegister.dto.ts
import { IsNotEmpty, IsOptional, IsString, Length } from 'class-validator'; import { UserRegisterDTO } from './userRegister.dto'; export class RetailerRegisterDTO extends UserRegisterDTO{ @IsNotEmpty() @IsString() @Length(1, 255) companyName: string; @IsNotEmpty() selectedState: string; @IsNotEmpty() zipCode: number; @IsOptional() phoneNumber: number; @IsNotEmpty() licenseNumber: string; @IsNotEmpty() medRecId: number; @IsOptional() website: string; @IsOptional() address: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/auth
/content/gmx-projects/gmx-admin/backend/src/modules/auth/guards/jwt-auth.guard.ts
import { Injectable } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Injectable() export class JwtAuthGuard extends AuthGuard('jwt') { handleRequest(err, user, info) { return user; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules/auth
/content/gmx-projects/gmx-admin/backend/src/modules/auth/strategy/local.strategy.ts
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy } from 'passport-local'; import { AuthService } from '../auth.service'; @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { constructor(private authService: AuthService) { super(); } async validate(username: string, password: string): Promise<any> { const user = await this.authService.login({ username: username, password: password, }); if (!user) { throw new UnauthorizedException('Please enter valid credentials.'); } return user; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules/auth
/content/gmx-projects/gmx-admin/backend/src/modules/auth/strategy/optional.strategy.ts
import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { AppConstants } from 'src/constants/app.constant'; @Injectable() export class OptionalStrategy extends PassportStrategy(Strategy, 'optional') { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: AppConstants.jwtSecret, }); } // authenticate() { // return this.success({}) // } }
0
/content/gmx-projects/gmx-admin/backend/src/modules/auth
/content/gmx-projects/gmx-admin/backend/src/modules/auth/strategy/jwt.strategy.ts
import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { AppConstants } from 'src/constants/app.constant'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: AppConstants.jwtSecret, }); } async validate(payload: any) { return { id: payload.id, email: payload.email }; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/stores/stores.controller.ts
import { Body, Controller, Delete, Get, Param, Post, Put, Query, Request, UploadedFiles, UseGuards, UseInterceptors, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { FileFieldsInterceptor } from '@nestjs/platform-express'; import { diskStorage } from 'multer'; import { ResponseSuccess } from 'src/common/dto/response.dto'; import { IResponse } from 'src/common/interfaces/response.interface'; import { FileHelper } from 'src/services/FileHelper.service'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { StoreDto } from './dto/store.dto'; import { UpdateStoreDto } from './dto/update-store.dto'; import { StoresService } from './stores.service'; @UseGuards(JwtAuthGuard) @Controller() export class StoresController { constructor(private readonly storesService: StoresService) {} @UseGuards(AuthGuard('jwt')) @Get() async getAllStores( @Request() req, @Query('offset') offset: string, @Query('limit') limit: string, @Query('status') status: string, ): Promise<IResponse> { const stores = await this.storesService.getAllStores( req.user, +offset, +limit, +status, ); return new ResponseSuccess('Stores', stores); } @UseGuards(AuthGuard('jwt')) @Get('addresses') async getAllAddresses( @Request() req, ): Promise<IResponse> { const stores = await this.storesService.getAllAddresses( req.user ); return new ResponseSuccess('Stores', stores); } @UseGuards(AuthGuard('jwt')) @Post() @UseInterceptors( FileFieldsInterceptor( [ { name: 'medRecCertificatePath', maxCount: 1, }, { name: 'resaleLicensePath', maxCount: 1, }, ], { storage: diskStorage({ destination: '../assets', filename: FileHelper.customFileName, }), }, ), ) async createStore( @Request() req, @Body() storeDto: StoreDto, @UploadedFiles() file: { avatar?: []; background?: [] }, ): Promise<IResponse> { const store = await this.storesService.createStore( req.user, storeDto, file ); return new ResponseSuccess('Store added successfully.', store); } @UseGuards(AuthGuard('jwt')) @Get(':id') async findOne(@Request() req, @Param('id') id: string) { const data = await this.storesService.findOne(req.user, id); return new ResponseSuccess('Store.', data); } @UseGuards(AuthGuard('jwt')) @Put(':id') @UseInterceptors( FileFieldsInterceptor( [ { name: 'medRecCertificatePath', maxCount: 1, }, { name: 'resaleLicensePath', maxCount: 1, }, ], { storage: diskStorage({ destination: '../assets', filename: FileHelper.customFileName, }), }, ), ) async updateStore( @Param('id') id: string, @Body() storeDto: StoreDto, @Request() req, @UploadedFiles() file: { avatar?: []; background?: [] }, ): Promise<IResponse> { const store = await this.storesService.updateStore( req.user, id, storeDto, file ); return new ResponseSuccess('Store updated successfully.', store); } @UseGuards(AuthGuard('jwt')) @Post('change/default/:id') async changeStoreDefault(@Param('id') id: number): Promise<IResponse> { const store = await this.storesService.changeStoreDefault(id); return new ResponseSuccess('Set this as my default store.', store); } @UseGuards(AuthGuard('jwt')) @Delete(':id') async deleteStore(@Request() req, @Param('id') id: string): Promise<IResponse> { const store = await this.storesService.deleteStore(req.user, id); return new ResponseSuccess('Store deleted successfully..', store); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/stores/stores.service.ts
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { isBoolean } from 'class-validator'; import { Retailer } from 'src/models/retailer.model'; import { State } from 'src/models/state.model'; import { Stores } from 'src/models/stores.model'; import { JwtUserDTO } from '../auth/dto/JwtUser.dto'; import { StoreDto } from './dto/store.dto'; @Injectable() export class StoresService { constructor( @InjectModel(Stores) private StoresModel: typeof Stores, @InjectModel(Retailer) private RetailerCompanyModel: typeof Retailer, ) {} async getAllStores( jwtUserDTO: JwtUserDTO, offset = 0, limit = 10, status = 0, ) { let condition = {}; if (status) { condition = { isActive: '1' }; } const { count, rows: data } = await this.StoresModel.findAndCountAll({ include: [ { model: State, } ], where: { userId: jwtUserDTO.id, ...condition }, order: [['createdAt', 'desc']], }); return { count: count, currentPage: offset ? +offset : 0, totalPages: Math.ceil(count / limit), data: data, }; } async getAllAddresses( jwtUserDTO: JwtUserDTO ) { const retailerCompany = await this.RetailerCompanyModel.findOne({ attributes: ['id','defaultStoreId'], where: { userId: jwtUserDTO.id }, }); const data = await this.StoresModel.findAll({ include: [ { model: State, } ], where: { userId: jwtUserDTO.id }, order: [['isDefault', 'desc']], }); return {data, retailerCompany}; } async createStore( jwtUserDTO: JwtUserDTO, storeDto: StoreDto, file ) { if(isBoolean(storeDto.isDefault)) { await this.StoresModel.update({ isDefault: 0 }, { where: { userId: jwtUserDTO.id } }); } const { count } = await this.StoresModel.findAndCountAll({ where: { userId: jwtUserDTO.id }, }); if(count === 0) { storeDto.isDefault = "1"; } const medRecCertificatePath = (await file.medRecCertificatePath) ? file?.medRecCertificatePath[0]?.filename : null; const resaleLicensePath = (await file) ? file.resaleLicensePath ? file?.resaleLicensePath[0]?.filename : null : null; const retailerCompany = await this.RetailerCompanyModel.findOne({ where: { userId: jwtUserDTO.id }, }); const store = await this.StoresModel.create({ userId: jwtUserDTO.id, retailerCompanyID: retailerCompany?.id, isDefault: storeDto.isDefault, managerName: storeDto.managerName, phoneNumber: storeDto.phoneNumber, address: storeDto.address, stateId: storeDto.stateId, zipCode: storeDto.zipCode, licenseNumber: storeDto.licenseNumber, licenseExpirationDate: storeDto.licenseExpirationDate, certificatePath: medRecCertificatePath, resaleLicensePath: resaleLicensePath, }); return store; } async findOne(jwtUserDTO: JwtUserDTO, id: string) { const data = await this.StoresModel.findOne({ where: { id, userId: jwtUserDTO.id }, }); if (!data) throw new NotFoundException(); return data; } async updateStore( jwtUserDTO: JwtUserDTO, id: string, storeDto: StoreDto, file ) { if(storeDto.isDefault === "true") { await this.StoresModel.update({ isDefault: 0 }, { where: { userId: jwtUserDTO.id } }); storeDto.isDefault = "1"; } const data = await this.StoresModel.findOne({ where: { id, userId: jwtUserDTO.id }, }); const medRecCertificatePath = (await file.medRecCertificatePath) ? file?.medRecCertificatePath[0]?.filename : data?.certificatePath; const resaleLicensePath = (await file) ? file.resaleLicensePath ? file?.resaleLicensePath[0]?.filename : data?.resaleLicensePath : data?.resaleLicensePath; const retailerCompany = await this.RetailerCompanyModel.findOne({ where: { userId: jwtUserDTO.id }, }); if (!data) throw new NotFoundException(); data.update({ userId: jwtUserDTO.id, retailerCompanyID: retailerCompany?.id, isDefault: storeDto.isDefault, managerName: storeDto.managerName, phoneNumber: storeDto.phoneNumber, address: storeDto.address, stateId: storeDto.stateId, zipCode: storeDto.zipCode, licenseNumber: storeDto.licenseNumber, licenseExpirationDate: storeDto.licenseExpirationDate, certificatePath: medRecCertificatePath, resaleLicensePath: resaleLicensePath, }); if(storeDto.isDefault === "1") { retailerCompany.update({ defaultStoreId: data?.id, }); } return data; } async changeStoreDefault(id: number) { const store = await this.StoresModel.findOne({ where: { id: id }, }); if (!store) throw new NotFoundException('Store Not Found'); await this.StoresModel.update({ isDefault: 0 }, { where: { userId: store?.userId } }); const updatedStore = await store.update({ isDefault: 1, }); return updatedStore; } async deleteStore( jwtUserDTO: JwtUserDTO, id: string, ) { const store = await this.StoresModel.findOne({ where: { id: id, userId: jwtUserDTO?.id, }, }); if (!store) throw new BadRequestException('Something went wrong'); await store.destroy(); const updateDefaultStore = await this.StoresModel.findOne({ where: { id: id, userId: jwtUserDTO?.id, }, order: [['id', 'desc']], }); if(updateDefaultStore) { updateDefaultStore.update({ isDefault: 1, }); } return store; } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/stores/stores.module.ts
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { Stores } from 'src/models/stores.model'; import { StoresController } from './stores.controller'; import { StoresService } from './stores.service'; import { Retailer } from 'src/models/retailer.model'; @Module({ imports: [SequelizeModule.forFeature([Stores, Retailer])], controllers: [StoresController], providers: [StoresService], }) export class StoresModule {}
0
/content/gmx-projects/gmx-admin/backend/src/modules/stores
/content/gmx-projects/gmx-admin/backend/src/modules/stores/dto/store.dto.ts
import { IsNotEmpty, IsOptional } from 'class-validator'; export class StoreDto { @IsNotEmpty() managerName: string; @IsNotEmpty() address: string; @IsNotEmpty() stateId: string; @IsNotEmpty() zipCode: string; @IsNotEmpty() phoneNumber: string; @IsNotEmpty() licenseNumber: string; @IsNotEmpty() licenseExpirationDate: string; @IsNotEmpty() isDefault: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules/stores
/content/gmx-projects/gmx-admin/backend/src/modules/stores/dto/update-store.dto.ts
import { IsNotEmpty, IsOptional } from 'class-validator'; export class UpdateStoreDto { @IsNotEmpty() isDefault: boolean; @IsNotEmpty() managerName: string; @IsNotEmpty() phoneNumber: string; @IsNotEmpty() address: string; @IsNotEmpty() stateId: string; @IsNotEmpty() zipCode: string; }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/getfile/getFile.controller.ts
import { Controller, Get, Param, Res } from '@nestjs/common'; @Controller() export class GetFileController { constructor() {} // @UseGuards(AuthGuard('jwt')) @Get(':filepath/:filename') seeUploadedFile( @Param('filename') filename, @Param('filepath') filepath, @Res() res, ): string { return res.sendFile(filename, { root: '../assets/' + filepath + '/' }); } }
0
/content/gmx-projects/gmx-admin/backend/src/modules
/content/gmx-projects/gmx-admin/backend/src/modules/getfile/getFile.module.ts
import { Module } from '@nestjs/common'; import { GetFileController } from './getFile.controller'; @Module({ controllers: [GetFileController], providers: [], }) export class GetFileModule {}
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/orderInvoiceItems.model.ts
import { AutoIncrement, BelongsTo, Column, DataType, PrimaryKey, Table } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; import { Category } from './category.model'; import { Product } from './product.model'; import { Strain } from './strain.model'; import { OrderInvoice } from './orderInvoice.model'; import { Brand } from './brand.model'; import { User } from './user.model'; require('dotenv').config(); const { CURRENCY } = process.env; @Table({ tableName: 'order_invoice_items', paranoid: true, }) export class OrderInvoiceItems extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @Column orderId: number; @Column orderInvoiceId: number; @Column retailerId: number; @Column brandCompanyId: number; @Column brandId: number; @Column productId: number; @Column categoryId: number; @Column({ allowNull: true, }) strainId: number; @Column unitPerPackage: number; @Column({ type: DataType.FLOAT(10, 2), }) price: number; @Column({ type: DataType.VIRTUAL, }) get displayPrice(): string { return ( CURRENCY + (Math.round(this.getDataValue('price') * 100) / 100).toFixed(2) ); } @Column quantity: number; @Column({ type: DataType.FLOAT(10, 2), }) total: number; @Column({ type: DataType.VIRTUAL, }) get totalPrice(): string { return ( CURRENCY + (Math.round(this.getDataValue('total') * 100) / 100).toFixed(2) ); } @Column({ type: DataType.VIRTUAL, }) get orderTotal(): string { return ( CURRENCY + (Math.round(this.getDataValue('total') * 100) / 100).toFixed(2) ); } @Column({ type: DataType.FLOAT(10, 2), }) finalTotal: number; @Column({ type: DataType.VIRTUAL, }) get finalOrderTotal(): string { return ( CURRENCY + (Math.round(this.getDataValue('finalTotal') * 100) / 100).toFixed(2) ); } @Column({ allowNull: true, }) deliveryDate: Date; @Column({ type: DataType.ENUM({ values: [`1`, `2`, `3`, `4`, `5`], }), comment: '1 for Requested, 2 for Confirmed, 3 for Declined, 4 for Completed, 5 for Reviewed', }) status: number; @Column({ allowNull: true, type: DataType.TEXT, }) declineReason: string; @Column({ allowNull: true, }) declinedBy: number; @Column({ allowNull: true, }) declinedAt: Date; @BelongsTo(() => OrderInvoice, 'orderInvoiceId') orderInvoice: OrderInvoice; @BelongsTo(() => Brand, 'brandId') brand: Brand; @BelongsTo(() => User, 'retailerId') retailer: User; @BelongsTo(() => Product, 'productId') product: Product; @BelongsTo(() => Category, 'categoryId') category: Category; @BelongsTo(() => Strain, 'strainId') strain: Strain; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/medRec.model.ts
import { Table, Column, PrimaryKey, AutoIncrement, HasMany, ForeignKey, BelongsTo, DataType, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; @Table({ tableName: 'med_rec', paranoid: true, }) export class MedRec extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @Column title: string; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/productFavourite.model.ts
import { AutoIncrement, BelongsTo, Column, ForeignKey, PrimaryKey, Table, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; import { Product } from './product.model'; import { User } from './user.model'; @Table({ tableName: 'product_favourite', paranoid: true, }) export class ProductFavourite extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @ForeignKey(() => User) @Column userId: number; @BelongsTo(() => User, 'userId') user: User; @ForeignKey(() => Product) @Column productId: number; @BelongsTo(() => Product, 'productId') product: Product; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/offers.model.ts
import { Table, Column, PrimaryKey, AutoIncrement, DataType, ForeignKey, AllowNull, BelongsTo, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; import { User } from './user.model'; import { Brand } from './brand.model'; require('dotenv').config(); const { CURRENCY } = process.env; @Table({ tableName: 'offers', paranoid: true, }) export class Offers extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @ForeignKey(() => User) @Column userId: number; @ForeignKey(() => Brand) @Column brandId: number; @Column title: string; @Column({ unique: true, }) slug: string; @Column({ type: DataType.ENUM({ values: [`1`, `2`, `3`], }), comment: '1 for Discount and Deals, 2 for Bulk Order Pricing', }) offerType: number; @AllowNull @Column({ type: DataType.FLOAT(10, 2), }) price: number; @Column({ type: DataType.VIRTUAL, }) get displayPrice(): string { return ( CURRENCY + (Math.round(this.getDataValue('price') * 100) / 100).toFixed(2) ); } @AllowNull @Column({ type: DataType.ENUM({ values: [`1`, `2`], }), comment: '1 for Per Package, 2 for Per Order', }) orderType: number; @AllowNull @Column minQty: number; @AllowNull @Column maxQty: number; @AllowNull @Column({ type: DataType.TEXT, }) categories: string; @AllowNull @Column({ type: DataType.TEXT, }) products: string; @AllowNull @Column({ type: DataType.TEXT, }) originalProducts: string; @Column({ type: DataType.TEXT, }) retailers: string; @Column({ type: DataType.TEXT, }) originalRetailers: string; @AllowNull @Column startDate: Date; @AllowNull @Column endDate: Date; @AllowNull @Column({ type: DataType.ENUM({ values: [`1`, `2`], }), defaultValue: '2', comment: '1 for yes, 2 for no', }) isInfinite: number; @BelongsTo(() => User, { foreignKey: 'userId', onDelete: 'cascade' }) user: User; @BelongsTo(() => Brand, { foreignKey: 'brandId', onDelete: 'cascade' }) brand: Brand; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/emailTemplate.model.ts
import { EmailTemplateFooter } from './emailTemplateFooter.model'; import { EmailTemplateHeader } from './emailTemplateHeader.model'; import { Table, Column, PrimaryKey, AutoIncrement, HasMany, ForeignKey, BelongsTo, DataType, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; @Table({ tableName: 'email_template', paranoid: true, }) export class EmailTemplate extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @ForeignKey(() => EmailTemplateHeader) @Column headerId: number; @ForeignKey(() => EmailTemplateFooter) @Column footerId: number; @Column title: string; @Column subject: string; @Column({ type: DataType.TEXT, }) body: string; @Column({ type: DataType.ENUM({ values: [`1`, `2`], }), comment: '1 for active, 2 for inactive', }) status: number; @BelongsTo(() => EmailTemplateHeader, 'headerId') header: EmailTemplateHeader; @BelongsTo(() => EmailTemplateFooter, 'footerId') footer: EmailTemplateFooter; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/drivers.model.ts
import { Table, Column, PrimaryKey, AutoIncrement, ForeignKey, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; import { User } from './user.model'; @Table({ tableName: 'drivers', paranoid: true, }) export class Drivers extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @ForeignKey(() => User) @Column userId: number; @Column transporterName: string; @Column driversName: string; @Column cannabisIndustryLicense: string; @Column phoneNumber: string; @Column email: string; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/commentLike.model.ts
import { AfterCreate, AfterDestroy, AfterRestore, AutoIncrement, BelongsTo, Column, DataType, ForeignKey, PrimaryKey, Table, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; import { Comment } from './comment.model'; import { User } from './user.model'; import { Brand } from './brand.model'; import { Retailer } from './retailer.model'; @Table({ tableName: 'comment_like', paranoid: true, }) export class CommentLike extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @Column({ type: DataType.ENUM({ values: [`2`, `3`], }), comment: '2 for brand, 3 for retailer', }) role: number; @Column userId: number; @BelongsTo(() => Brand, { onDelete: 'cascade', foreignKey: 'userId' }) brand: Brand; @BelongsTo(() => Retailer, { onDelete: 'cascade', foreignKey: 'userId' }) retailer: Retailer; @ForeignKey(() => Comment) @Column commentId: number; @BelongsTo(() => Comment) comment: Comment; @AfterCreate @AfterRestore static async incrementCommentLikesCount(commentLike: CommentLike, options) { await Comment.increment('likeCount', { where: { id: commentLike.commentId, }, transaction: options.transaction, }); } @AfterDestroy static async decrementCommentLikesCount(commentLike: CommentLike) { await Comment.decrement('likeCount', { where: { id: commentLike.commentId, }, }); } }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/settings.model.ts
import { Table, Column, PrimaryKey, AutoIncrement } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; @Table({ tableName: 'settings', paranoid: true, }) export class Settings extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @Column name: string; @Column description: string; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/repost.model.ts
import { AutoIncrement, BelongsTo, Column, DataType, ForeignKey, PrimaryKey, Table, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; import { Post } from './post.model'; import { User } from './user.model'; @Table({ tableName: 'reposts', paranoid: true, }) export class Repost extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @Column({ type: DataType.ENUM({ values: [`2`, `3`], }), comment: '2 for brand, 3 for retailer', }) role: number; @ForeignKey(() => User) @Column userId: number; @BelongsTo(() => User) user: User; @ForeignKey(() => Post) @Column postId: number; @BelongsTo(() => Post, { foreignKey: 'postId' }) posts: Post; @Column repostId: number; // @BelongsTo(() => Post, { foreignKey: 'repostId' }) // repost: Post; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/category.model.ts
import { Table, Column, PrimaryKey, AutoIncrement, HasMany, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; import { Order } from './order.model'; import { Product } from './product.model'; @Table({ tableName: 'categories', paranoid: true, }) export class Category extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @Column title: string; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/stores.model.ts
import { AllowNull, AutoIncrement, BelongsTo, Column, DataType, ForeignKey, PrimaryKey, Table } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; import { State } from './state.model'; import { User } from './user.model'; import { Retailer } from './retailer.model'; @Table({ tableName: 'stores', // paranoid: true, }) export class Stores extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @ForeignKey(() => User) @Column userId: number; @ForeignKey(() => Retailer) @Column retailerCompanyID: number; @Column({ defaultValue: false }) isDefault: boolean; @AllowNull @Column managerName: string; @AllowNull @Column phoneNumber: string; @AllowNull @Column address: string; @ForeignKey(() => State) @Column stateId: number; @BelongsTo(() => State) state: State; @Column zipCode: number; @Column licenseNumber: string; @Column({ get() { const licenseExpirationDate = this.getDataValue('licenseExpirationDate'); return licenseExpirationDate ? new Date(licenseExpirationDate).toISOString().slice(0, 10) : null; }, }) licenseExpirationDate: Date; @Column certificatePath: string; @Column resaleLicensePath: string; @BelongsTo(() => User, 'userId') user: User; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/review.model.ts
import { Table, Column, PrimaryKey, AutoIncrement, ForeignKey, BelongsTo, DataType, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; import { Brand } from './brand.model'; import { Product } from './product.model'; import { User } from './user.model'; import { Order } from './order.model'; @Table({ tableName: 'reviews', paranoid: true, }) export class Review extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @ForeignKey(() => Order) @Column orderId: number; @BelongsTo(() => Order, 'orderId') order: Order; @ForeignKey(() => Product) @Column productId: number; @BelongsTo(() => Product, 'productId') product: Product; @ForeignKey(() => Brand) @Column brandId: number; @BelongsTo(() => Brand, 'brandId') brand: Brand; @ForeignKey(() => User) @Column retailerId: number; @BelongsTo(() => User, 'retailerId') retailer: User; @Column({ type: DataType.ENUM({ values: [`1`, `2`, `3`], }), comment: '1 for product, 2 for delivery on time, 3 for general', }) type: number; @Column({ type: DataType.FLOAT(10, 2), }) ratings: number; @Column({ type: DataType.TEXT, }) description: string; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/axisPoint.model.ts
import { Table, Column, PrimaryKey, AutoIncrement, DataType, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; @Table({ tableName: 'axis_point', paranoid: true, }) export class AxisPoint extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @Column({ defaultValue: 0, // type: DataType.BLOB('long'), type: DataType.BLOB, }) file: string; }
0
/content/gmx-projects/gmx-admin/backend/src
/content/gmx-projects/gmx-admin/backend/src/models/emailTemplateHeader.model.ts
import { Table, Column, PrimaryKey, AutoIncrement, HasMany, ForeignKey, BelongsTo, DataType, } from 'sequelize-typescript'; import { BaseModel } from './baseModel'; @Table({ tableName: 'email_template_header', paranoid: true, }) export class EmailTemplateHeader extends BaseModel { @PrimaryKey @AutoIncrement @Column id: number; @Column title: string; @Column({ type: DataType.TEXT, }) description: string; @Column @Column({ type: DataType.ENUM({ values: [`1`, `2`], }), comment: '1 for active, 2 for inactive', }) status: number; }