Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: admin create product #580

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/controllers/AdminController.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Request, Response } from "express";
import { check, param, validationResult } from "express-validator";
import { UserRole } from "../enums/userRoles";
import { HttpError } from "../middleware";
import {
AdminLogService,
AdminOrganisationService,
AdminUserService,
AdminLogService,
} from "../services";
import { HttpError } from "../middleware";
import { check, param, validationResult } from "express-validator";
import { UserRole } from "../enums/userRoles";

/**
* @swagger
Expand Down
7 changes: 3 additions & 4 deletions src/controllers/AuthController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ const signUp = async (req: Request, res: Response, next: NextFunction) => {
const { message, user, access_token } = await authService.signUp(req.body);
res.status(201).json({ message, user, access_token });
} catch (error) {
console.log(error);
next(error);
}
};
Expand Down Expand Up @@ -626,16 +625,16 @@ const verify2FA = async (req: Request, res: Response, next: NextFunction) => {
};

export {
VerifyUserMagicLink,
changePassword,
createMagicToken,
enable2FA,
forgotPassword,
googleAuthCall,
// handleGoogleAuth,
login,
resetPassword,
signUp,
verifyOtp,
enable2FA,
verify2FA,
verifyOtp,
VerifyUserMagicLink,
};
6 changes: 2 additions & 4 deletions src/controllers/NewsLetterSubscriptionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,6 @@ const subscribeToNewsletter = async (
: "You are already subscribed to our newsletter",
});
} catch (error) {
console.log(error);

next(error);
}
};
Expand Down Expand Up @@ -294,8 +292,8 @@ const getAllNewsletter = async (
});

return res.status(200).json({
status: "",
message: "",
status_code: 200,
message: "Subscribers list fetched successfully",
data: data,
meta,
});
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/OrgController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1207,7 +1207,7 @@ export class OrgController {

/**
* @swagger
* /api/v1/organizations/{org_id}/roles/{role_id}:
* /api/v1/organisations/{org_id}/roles/{role_id}:
* get:
* summary: Get a specific role in an organization
* tags: [Organizations]
Expand Down
15 changes: 9 additions & 6 deletions src/controllers/ProductController.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NextFunction, Request, Response } from "express";
import { ProductService } from "../services/product.services";
import { BadRequest } from "../middleware";
import { ProductService } from "../services/product.services";

class ProductController {
private productService: ProductService;
Expand All @@ -18,7 +18,7 @@ class ProductController {

/**
* @openapi
* /api/v1/organizations/{org_id}/product:
* /api/v1/organisations/{org_id}/product:
* post:
* summary: Create a product
* tags: [Product]
Expand Down Expand Up @@ -100,9 +100,12 @@ class ProductController {
const id = req.params.org_id;
const product = req.body;
const newProduct = await this.productService.createProduct(id, product);
res
.status(201)
.json({ message: "Product created successfully", data: newProduct });
res.status(201).json({
status_code: 201,
message: "Product created successfully",
status: "success",
data: newProduct,
});
};

/**
Expand Down Expand Up @@ -335,7 +338,7 @@ class ProductController {

/**
* @openapi
* /api/v1/organizations/{org_id}/products/{product_id}:
* /api/v1/organisations/{org_id}/products/{product_id}:
* get:
* summary: get a product by its ID
* tags: [Product]
Expand Down
9 changes: 7 additions & 2 deletions src/middleware/request-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ const requestBodyValidator = (schema: ZodSchema<any>) => {
next();
} catch (err) {
if (err instanceof ZodError) {
return res.status(400).json({
const errorMessages = err.errors.map((error: any) => ({
path: `${error.path.join(",")}`,
message: `${error.message}`,
}));

return res.status(422).json({
message: "Invalid request body",
// errors: err.errors,
errors: errorMessages,
});
}
next(err);
Expand Down
17 changes: 12 additions & 5 deletions src/models/product.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
DeleteDateColumn,
Entity,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
CreateDateColumn,
} from "typeorm";
import { Organization } from "./organization";
import ExtendedBaseEntity from "./extended-base-entity";
import { ProductSize, StockStatus } from "../enums/product";
import ExtendedBaseEntity from "./extended-base-entity";
import { Organization } from "./organization";
import { User } from "./user";
@Entity()
export class Product extends ExtendedBaseEntity {
Expand Down Expand Up @@ -58,4 +59,10 @@ export class Product extends ExtendedBaseEntity {

@ManyToOne(() => User, (user) => user.products)
user: User;

@Column({ type: "float", nullable: false, default: 0 })
cost_price: number;

@DeleteDateColumn()
deletedAt?: Date;
}
3 changes: 1 addition & 2 deletions src/routes/admin.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Router } from "express";
import admin from "../controllers/AdminController";
import { authMiddleware, checkPermissions } from "../middleware";
import { UserRole } from "../enums/userRoles";
import { Organization } from "../models";
import { authMiddleware, checkPermissions } from "../middleware";
import { Limiter } from "../utils";

const adminRouter = Router();
Expand Down
6 changes: 3 additions & 3 deletions src/routes/organisation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ orgRouter.delete(
);

orgRouter.post(
"/organizations",
"/organisations",
authMiddleware,
organizationValidation,
orgController.createOrganisation.bind(orgController),
Expand Down Expand Up @@ -87,13 +87,13 @@ orgRouter.put(
);

orgRouter.get(
"/organizations/:org_id/roles/:role_id",
"/organisations/:org_id/roles/:role_id",
authMiddleware,
orgController.getSingleRole.bind(orgController),
);

orgRouter.get(
"/organizations/:org_id/roles",
"/organisations/:org_id/roles",
authMiddleware,
orgController.getAllOrganizationRoles.bind(orgController),
);
Expand Down
15 changes: 7 additions & 8 deletions src/routes/product.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,37 @@
import { Router } from "express";
import { ProductController } from "../controllers/ProductController";
import { authMiddleware, validOrgAdmin } from "../middleware";
import { validateProductDetails } from "../middleware/product";
import { validateUserToOrg } from "../middleware/organizationValidation";
import { adminOnly } from "../middleware";
import { requestBodyValidator } from "../middleware/request-validation";
import { productSchema } from "../schema/product.schema";

const productRouter = Router();
const productController = new ProductController();

// route
productRouter.post(
"/organizations/:org_id/products",
validateProductDetails,
"/organisations/:org_id/products",
requestBodyValidator(productSchema),
authMiddleware,
validOrgAdmin,
productController.createProduct,
);

productRouter.get(
"/organizations/:org_id/products/search",
"/organisations/:org_id/products/search",
authMiddleware,
validateUserToOrg,
productController.getProduct,
);

productRouter.delete(
"/organizations/:org_id/products/:product_id",
"/organisations/:org_id/products/:product_id",
authMiddleware,
validOrgAdmin,
productController.deleteProduct,
);

productRouter.get(
"/organizations/:org_id/products/:product_id",
"/organisations/:org_id/products/:product_id",
authMiddleware,
validOrgAdmin,
productController.getSingleProduct,
Expand Down
9 changes: 5 additions & 4 deletions src/schema/product.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import { z } from "zod";

export const productSchema = z.object({
name: z.string().min(1, "Name is required"),
description: z.string().optional(),
category: z.string().optional(),
price: z.number().min(1, "Price is required"),
image: z.string().optional(),
description: z.string().min(1, "Description is required"),
category: z.string().min(1, "Category is required"),
price: z.number().min(0.1, "Price is required and must be greater than 0"),
image: z.string(),
quantity: z.number().min(1, "Quantity is required"),
cost_price: z.number().optional(),
});

export type ProductSchema = z.infer<typeof productSchema>;
Expand Down
4 changes: 2 additions & 2 deletions src/services/admin.services.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// / src/services/AdminOrganisationService.ts
import { NextFunction, Request, Response } from "express";
import { Request } from "express";
// import { getRepository, Repository } from 'typeorm';
import { User, Organization, Log } from "../models";
import AppDataSource from "../data-source";
import { HttpError } from "../middleware";
import { Log, Organization, User } from "../models";
import { hashPassword } from "../utils/index";

export class AdminOrganisationService {
Expand Down
2 changes: 1 addition & 1 deletion src/services/newsLetterSubscription.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Repository } from "typeorm";
import AppDataSource from "../data-source";
import { BadRequest, HttpError, ResourceNotFound } from "../middleware";
import { NewsLetterSubscriber } from "../models/newsLetterSubscription";
import { INewsLetterSubscriptionService } from "../types";
import { BadRequest, HttpError, ResourceNotFound } from "../middleware";

export class NewsLetterSubscriptionService
implements INewsLetterSubscriptionService
Expand Down
15 changes: 4 additions & 11 deletions src/services/org.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,16 @@ import { v4 as uuidv4 } from "uuid";
import config from "../config/index";
import AppDataSource from "../data-source";
import { UserRole } from "../enums/userRoles";
import {
BadRequest,
ResourceNotFound,
HttpError,
Conflict,
} from "../middleware";
import { Organization, Invitation, UserOrganization } from "../models";
import { BadRequest, Conflict, ResourceNotFound } from "../middleware";
import { Invitation, Organization, UserOrganization } from "../models";
import { OrganizationRole } from "../models/organization-role.entity";
import { User } from "../models/user";
import { ICreateOrganisation, ICreateOrgRole, IOrgService } from "../types";
import log from "../utils/logger";

import { addEmailToQueue } from "../utils/queue";
import renderTemplate from "../views/email/renderTemplate";
import { PermissionCategory } from "../enums/permission-category.enum";
import { Permissions } from "../models/permissions.entity";
import { addEmailToQueue } from "../utils/queue";
import renderTemplate from "../views/email/renderTemplate";
const frontendBaseUrl = config.BASE_URL;

export class OrgService implements IOrgService {
Expand Down Expand Up @@ -196,7 +190,6 @@ export class OrgService implements IOrgService {
const organization = await organizationRepository.findOne({
where: { id: organizationId },
});
console.log("here", organization);
if (!organization) {
throw new ResourceNotFound(
`Organization with ID ${organizationId} not found`,
Expand Down
5 changes: 0 additions & 5 deletions src/services/product.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ export class ProductService {
if (!organization) {
throw new ServerError("Invalid organisation credentials");
}

const newProduct = this.productRepository.create(new_Product);
newProduct.org = organization;
newProduct.stock_status = await this.calculateProductStatus(
Expand All @@ -93,15 +92,11 @@ export class ProductService {
}

return {
status_code: 201,
status: "success",
message: "Product created successfully",
data: {
id: product.id,
name: product.name,
description: product.description,
price: product.price,
image: product.image,
status: product.stock_status,
quantity: product.quantity,
created_at: product.created_at,
Expand Down
11 changes: 4 additions & 7 deletions src/test/product.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
//@ts-nocheck
import { ProductService } from "../services/product.services";
import { Repository } from "typeorm";
import { Product } from "../models/product";
import { StockStatus } from "../enums/product";
import { ProductSchema } from "../schema/product.schema";
import { ServerError } from "../middleware";
import { Organization } from "../models/organization";
import { ServerError, ResourceNotFound } from "../middleware";
import { Product } from "../models/product";
import { ProductSchema } from "../schema/product.schema";
import { ProductService } from "../services/product.services";

jest.mock("../utils", () => ({
getIsInvalidMessage: jest
Expand Down Expand Up @@ -70,9 +70,6 @@ describe("ProductService", () => {
.mockResolvedValue(StockStatus.IN_STOCK);

const result = await productService.createProduct(mockOrgId, mockProduct);
expect(result.status_code).toEqual(201);
expect(result.status).toEqual("success");
expect(result.message).toEqual("Product created successfully");
expect(result.data.name).toEqual(mockProduct.name);
expect(result.data.description).toEqual(mockProduct.description);
expect(result.data.price).toEqual(mockProduct.price);
Expand Down
Loading