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

major #161

Open
wants to merge 96 commits into
base: main
Choose a base branch
from
Open

major #161

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
af50b3c
removed trycatch
thegodhope Oct 12, 2023
66f35a3
Merge branch 'dev' of https://github.com/hngx-org/zuriportfolio-comma…
thegodhope Oct 12, 2023
92da911
changed my route to collection
thegodhope Oct 20, 2023
91fb725
Merge branch 'dev' of https://github.com/hngx-org/zuriportfolio-comma…
thegodhope Oct 20, 2023
ee955b5
Chore : fix swagger docs
Cyrus-11 Oct 21, 2023
0cd80a2
Merge pull request #134 from hngx-org/feat-get-all-categories
Benrobo Oct 21, 2023
d96139c
Merge pull request #140 from hngx-org/chore-swaggerFix
Benrobo Oct 21, 2023
c0f6281
edited sales report controller
AirZED Oct 21, 2023
3cdbd39
edited sales report controller
AirZED Oct 21, 2023
679487f
edited sales report controller
AirZED Oct 21, 2023
b011892
edited sales report controller
AirZED Oct 21, 2023
3ae6e9c
added doc for promo tracking
Benrobo Oct 21, 2023
b9c320a
Merge pull request #141 from hngx-org/sales_report
Benrobo Oct 21, 2023
75c35a6
Merge pull request #142 from hngx-org/fix-track-promo
Benrobo Oct 21, 2023
b397edd
temp fix the categories issues when adding products
Benrobo Oct 21, 2023
6aff41f
Merge branch 'fix-track-promo' into dev
Benrobo Oct 21, 2023
ea27efa
updated sales
Benrobo Oct 21, 2023
c26e744
updated swager
Benrobo Oct 21, 2023
afb2208
removed unused type
Benrobo Oct 21, 2023
f9d0448
added uuid validations
Benrobo Oct 21, 2023
2b84915
Merge pull request #143 from hngx-org/fix-track-promo
Benrobo Oct 21, 2023
8b57d2b
checked if merchant exists or not.
Benrobo Oct 21, 2023
3e2c9cf
Merge pull request #144 from hngx-org/fix-track-promo
Benrobo Oct 21, 2023
b5f6027
updated
Benrobo Oct 21, 2023
caa4b38
updated validation
Benrobo Oct 21, 2023
e60739c
chore: add the sign up Auth API swagger docs
iamstarcode Oct 21, 2023
e0d3c4b
updated logger
Benrobo Oct 21, 2023
22f7f1f
Merge pull request #145 from iamstarcode/chore-add-auth-swagger-doc
Benrobo Oct 21, 2023
25a2d5f
updated categories endpoint
Benrobo Oct 21, 2023
5c894c7
Merge branch 'dev' of https://github.com/hngx-org/zuriportfolio-comma…
Benrobo Oct 21, 2023
b832fe9
updated add product
Benrobo Oct 21, 2023
121f813
revamped fetching of sales reports
Benrobo Oct 22, 2023
813f861
updated swagger
Benrobo Oct 22, 2023
92917ea
added activities
Benrobo Oct 22, 2023
49ab9a4
Merge pull request #147 from hngx-org/fix-sales-report
Benrobo Oct 22, 2023
43af320
Merge pull request #148 from hngx-org/fix-sales-report
Benrobo Oct 22, 2023
358e363
updated revenue endpoint/handler
Benrobo Oct 22, 2023
bab2505
Merge pull request #149 from hngx-org/fix-sales-report
Benrobo Oct 22, 2023
7009abc
updated sales report
Benrobo Oct 22, 2023
c3035d4
updated sales report
Benrobo Oct 22, 2023
4f4dfa4
Merge branch 'dev' of https://github.com/hngx-org/zuriportfolio-comma…
thegodhope Oct 22, 2023
cf6517b
fix: remove unused quantiy field
iamstarcode Oct 22, 2023
8097aa9
chore:API-versioning
Oct 22, 2023
a5a9033
Merge pull request #150 from hngx-org/fix-sales-report
Benrobo Oct 22, 2023
a170698
Merge pull request #151 from iamstarcode/fix-remove-quantity-field
Benrobo Oct 22, 2023
e703691
Merge branch 'dev' of https://github.com/hngx-org/zuriportfolio-comma…
Oct 22, 2023
8329ef8
chore:API-versioning
Oct 22, 2023
b7f85da
Merge pull request #152 from hngx-org/chore-api-version
Benrobo Oct 22, 2023
ae8e162
added api versioning
Benrobo Oct 22, 2023
2d7273b
added api versioning
Benrobo Oct 22, 2023
e62db28
Merge pull request #153 from hngx-org/fix-sales-report
Benrobo Oct 22, 2023
1cd5054
fixed naming convention on the product route
thegodhope Oct 22, 2023
6d29074
fix: order_item table PK should auto increment
iamstarcode Oct 22, 2023
a30866e
refixed m changes
thegodhope Oct 22, 2023
42342f2
Merge pull request #154 from iamstarcode/fix-order-item-prisma-schema
Benrobo Oct 22, 2023
1e2185f
added paginstion, updated documentation, added versioning to all routes
Edidiva Oct 22, 2023
bd7cd03
Merge branch 'dev' of https://github.com/hngx-org/zuriportfolio-comma…
Edidiva Oct 22, 2023
1bda8f6
Merge pull request #158 from hngx-org/perf-getProductsByShopId
AirZED Oct 22, 2023
1763f31
fix: product id to use uuid instead of string
iamstarcode Oct 22, 2023
53a1477
updated docs for no revenue endpoint
edahmitchel Oct 22, 2023
dd83489
Merge pull request #160 from iamstarcode/fix-product-uuid
Edidiva Oct 22, 2023
d47fef7
Merge pull request #162 from edahmitchel/dev
Edidiva Oct 22, 2023
a47fc1c
took naming changes made to the product route and set it back to default
thegodhope Oct 22, 2023
9e9065f
fix: remove the need to generate uuid
iamstarcode Oct 22, 2023
4dd7632
Added Html and CSS root route to the end point.
Oludayo02 Oct 22, 2023
004dccd
Merge pull request #164 from iamstarcode/fix-remove-uuid-generation
AirZED Oct 22, 2023
f21ebeb
remove unnecessory part of docs
AirZED Oct 22, 2023
6a3037e
Merge branch 'dev' into getAllShops
Oludayo20 Oct 22, 2023
beb5c13
added comments to shop routes
AirZED Oct 22, 2023
2a09fb5
more
AirZED Oct 22, 2023
f9688d5
removed product quantity validation when creating product
Benrobo Oct 22, 2023
b9ae58c
removed product quantity validation when creating product
Benrobo Oct 22, 2023
41e63ec
fix: update swagger doc for add product
iamstarcode Oct 22, 2023
acfe3c8
Merge pull request #168 from hngx-org/fix-sales-report
Benrobo Oct 22, 2023
71a1763
Merge pull request #169 from iamstarcode/fix-update-add-product-swagg…
Benrobo Oct 22, 2023
a6a04fd
added documentation for shop and discount
edahmitchel Oct 22, 2023
6c8a303
Merge pull request #170 from edahmitchel/dev
Benrobo Oct 22, 2023
b387058
updated orders docs and api url link
edahmitchel Oct 22, 2023
4f7212b
code fixes and refactoring
excellencyjumo Oct 22, 2023
a95914c
added a guard clause
Benrobo Oct 22, 2023
dccf792
Merge branch 'dev' of https://github.com/hngx-org/zuriportfolio-comma…
Benrobo Oct 22, 2023
ef467ee
Merge pull request #172 from hngx-org/feat-added-guard-clause
Benrobo Oct 22, 2023
6bd1c0e
Merge pull request #171 from edahmitchel/dev
Benrobo Oct 22, 2023
e9f3555
Merge pull request #167 from hngx-org/sales_report
Benrobo Oct 22, 2023
926119b
Merge pull request #173 from hngx-org/feat-sales-report
Benrobo Oct 22, 2023
62a6478
updated
Benrobo Oct 22, 2023
81748d2
chore: updated middleware
Benrobo Oct 22, 2023
20224fc
Merge pull request #165 from Oludayo20/getAllShops
Benrobo Oct 22, 2023
76bc9c5
chore: implement guardClause
Cyrus-11 Oct 22, 2023
5296007
Merge pull request #174 from hngx-org/chore-auth-guard-clause
Benrobo Oct 22, 2023
588deb6
changes made to the product routes and docs
thegodhope Oct 22, 2023
589debf
Merge branch 'dev' of https://github.com/hngx-org/zuriportfolio-comma…
thegodhope Oct 22, 2023
522e92e
nopromo route fixed
thegodhope Oct 22, 2023
5b65ade
Merge pull request #155 from hngx-org/feat-get-all-categories
Benrobo Oct 22, 2023
d25df0f
types for discount
excellencyjumo Oct 22, 2023
5d3544c
Merge pull request #176 from hngx-org/feat-sales-report
Benrobo Oct 22, 2023
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
437 changes: 372 additions & 65 deletions documentation.json

Large diffs are not rendered by default.

51 changes: 51 additions & 0 deletions prisma/migrations/20231022135956_test/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
Warnings:

- The values [complete] on the enum `STATUS` will be removed. If these variants are still used in the database, this will fail.
- You are about to drop the column `user_type` on the `activity` table. All the data in the column will be lost.
- You are about to drop the column `usage` on the `promotion` table. All the data in the column will be lost.
- Added the required column `sub_category_id` to the `product` table without a default value. This is not possible if the table is not empty.

*/
-- AlterEnum
BEGIN;
CREATE TYPE "STATUS_new" AS ENUM ('pending', 'completed', 'failed');
ALTER TABLE "order" ALTER COLUMN "status" DROP DEFAULT;
ALTER TABLE "order" ALTER COLUMN "status" TYPE "STATUS_new" USING ("status"::text::"STATUS_new");
ALTER TYPE "STATUS" RENAME TO "STATUS_old";
ALTER TYPE "STATUS_new" RENAME TO "STATUS";
DROP TYPE "STATUS_old";
ALTER TABLE "order" ALTER COLUMN "status" SET DEFAULT 'pending';
COMMIT;

-- AlterTable
ALTER TABLE "activity" DROP COLUMN "user_type";

-- AlterTable
ALTER TABLE "product" ADD COLUMN "sub_category_id" INTEGER NOT NULL;

-- AlterTable
ALTER TABLE "promotion" DROP COLUMN "usage";

-- CreateTable
CREATE TABLE "track_promotion" (
"id" SERIAL NOT NULL,
"product_id" TEXT NOT NULL,
"promo_id" INTEGER NOT NULL,
"user_id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "track_promotion_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "product" ADD CONSTRAINT "product_sub_category_id_fkey" FOREIGN KEY ("sub_category_id") REFERENCES "product_sub_category"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "track_promotion" ADD CONSTRAINT "track_promotion_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "track_promotion" ADD CONSTRAINT "track_promotion_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "track_promotion" ADD CONSTRAINT "track_promotion_promo_id_fkey" FOREIGN KEY ("promo_id") REFERENCES "promotion"("id") ON DELETE CASCADE ON UPDATE CASCADE;
46 changes: 24 additions & 22 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ model order {
}

model order_item {
id Int @id @unique
id Int @id @default(autoincrement())
order_id String
product_id String
merchant_id String
Expand All @@ -124,22 +124,23 @@ model order_item {
}

model product {
id String @id @unique
user_id String
shop_id String
category_id Int
name String
description String
quantity Int @default(1)
price Float
discount_price Float @default(0)
tax Float
admin_status ADMIN_STATUS @default(pending)
is_published Boolean @default(false)
is_deleted product_status @default(active)
currency String
createdAt DateTime @default(now())
updatedAt DateTime @default(now())
id String @id @default(uuid())
user_id String
shop_id String
category_id Int
sub_category_id Int
name String
description String
quantity Int @default(1)
price Float
discount_price Float @default(0)
tax Float
admin_status ADMIN_STATUS @default(pending)
is_published Boolean @default(false)
is_deleted product_status @default(active)
currency String
createdAt DateTime @default(now())
updatedAt DateTime @default(now())

image product_image[]
track_promotion track_promotion[]
Expand All @@ -149,7 +150,8 @@ model product {
user user? @relation(fields: [user_id], references: [id], onDelete: Cascade)
shop shop @relation(fields: [shop_id], references: [id], onDelete: Cascade)
digital_assets product_digital_assets?
sub_category product_sub_category @relation(fields: [category_id], references: [id])
category product_category @relation(fields: [category_id], references: [id]) //! Remove this later on.
sub_category product_sub_category @relation(fields: [sub_category_id], references: [id])
// rating
}

Expand All @@ -160,7 +162,6 @@ model product_digital_assets {
link String
type PRODUCT_ASSET_TYPE @default(external)
product_id String @unique
// user_id String
created_at DateTime @default(now())
updated_at DateTime @default(now())

Expand All @@ -181,6 +182,7 @@ model product_category {
user_id String
user user @relation(fields: [user_id], references: [id], onDelete: Cascade)

product product[] //! Remove this later on
sub_categories product_sub_category[]
}

Expand Down Expand Up @@ -284,13 +286,13 @@ model sales_report {
}

model activity {
id String @id
id String @id @default(uuid())
action String
user_id String
title String
description String
user_type ACTIVITY_USER_TYPE
createdAt DateTime @default(now())
// user_type ACTIVITY_USER_TYPE
createdAt DateTime @default(now())

user user @relation(fields: [user_id], references: [id], onDelete: Cascade)
}
5 changes: 2 additions & 3 deletions src/@types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ export interface TrackPromo {
}

export interface AddSalesReportType {
user_id: string;
sales: number;
order_id: string;
}
Expand All @@ -53,7 +52,7 @@ export interface CreateDiscountType {
discount_type: string;
amount: number;
quantity: number;
maximum_discount_price: number;
maximum_discount_price?: number;
product_ids: string[];
valid_from: string;
valid_to: string;
Expand All @@ -64,7 +63,7 @@ export interface UpdateDiscountType {
amount: number;
code: string;
quantity: number;
maximum_discount_price: number;
maximum_discount_price?: number;
product_ids: string[];
valid_from: string;
valid_to: string;
Expand Down
29 changes: 19 additions & 10 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import HandleErrors from './middlewares/error';
import { Routes } from './@types';
import swaggerUi from 'swagger-ui-express';
import swagggerJson from './doc/swagger.json';
import path from 'path';

export default class App {
public app: express.Application;
Expand All @@ -31,15 +32,16 @@ export default class App {
cors({
origin: '*',
credentials: true,
}),
})
);
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: false }));
this.app.use('/', express.static(path.join(__dirname, '..', 'src/public')));
}

initSwaggerUI() {
// handle swagger-doc
this.app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swagggerJson));
this.app.use('/api/v1/docs', swaggerUi.serve, swaggerUi.setup(swagggerJson));
}

listen() {
Expand All @@ -54,25 +56,32 @@ export default class App {
initializedRoutes(routes: Routes[]) {
// initialize all routes middleware
routes.forEach((route) => {
this.app.use('/api', route.router);
this.app.use('/api/v1', route.router);
});

this.app.use('/', (req, res) => {
res.json({ message: 'Youve reached Zuriportfolio shop internal api' });
res.sendFile(path.join(__dirname, '..', 'src/public/views', 'index.html'));
});


this.app.use('/api', (req, res) => {
res.json({ message: 'Youve reached Zuriportfolio shop internal api' });
res.sendFile(path.join(__dirname, '..', 'src/public/views', 'index.html'));

this.app.use('/api/v1', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'src/public/views', 'index.html'));
});

this.initSwaggerUI();

this.app.all('*', (req, res) => {
return res.status(404).json({
errorStatus: true,
code: '--route/route-not-found',
message: 'The requested route was not found.',
});
res.status(404);
if (req.accepts('html')) {
return res.sendFile(path.join(__dirname, '..', 'src/public/views', '404.html'));
} else if (req.accepts('json')) {
return res.json({ message: '404 Not Found' });
} else {
return res.type('txt').send('404 Not Found');
}
});
// handle global errors
this.app.use(HandleErrors);
Expand Down
4 changes: 2 additions & 2 deletions src/config/test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// for test purpose.
// user id for prod db
export const TestUserId = '2ae314e8-006a-4bc6-a172-bfeca0a78ec1';
export const TestUserId = 'a87be40d-8632-4c45-9b44-c893560d58c9';
// 'd7955c27-4d61-4cd6-a6bb-e6402151d51f'

// for development purpose
// export const TestUserId = 'bac3e83f-b796-4e72-b20e-6e43d038d25d';
// export const TestUserId = 'bac3e83f-b796-4e72-b20e-6e43d038d25d';
53 changes: 18 additions & 35 deletions src/controller/activity.controller.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,21 @@
// import { Request, Response } from 'express';
// import BaseController from './base.controller';
// import { v4 as uuidv4 } from 'uuid';
// import prisma from '../config/prisma';
// import { TestUserId } from '../config/test';
// import { createActivitySchema } from '../helper/validate';
import { Request, Response } from 'express';
import BaseController from './base.controller';
import prisma from '../config/prisma';
import { TestUserId } from '../config/test';

// export default class ActivityController extends BaseController {
// constructor() {
// super();
// }
export default class ActivityController extends BaseController {
constructor() {
super();
}

// async addActivity(req: Request, res: Response) {
// const user_id = (req as any).user?.id ?? TestUserId;
// const { error, value } = createActivitySchema.validate(req.body);
// if (error) {
// return this.error(res, '--addActivity/invalid request', 'Invalid requets', 400);
// }
// const { action, title, description } = value;
// // Creating activity in the database
// const activityId = uuidv4();
// const newActivity = await prisma.activity.create({
// data: {
// id: activityId,
// action: action,
// user: {
// connect: {
// id: user_id,
// },
// },
// title: title,
// description: description,
// },
// });
async getActivities(req: Request, res: Response) {
const userId = (req as any).user?.id ?? TestUserId;
const allActivities = await prisma.activity.findMany({
where: {
user_id: userId,
},
});

// return this.success(res, '--addActivity/success', 'Activity recorded successfully', 201, newActivity);
// }
// }
return this.success(res, '--activities/success', 'activities fetched successfully', 200, allActivities);
}
}
30 changes: 24 additions & 6 deletions src/controller/discount.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import prisma from '../config/prisma';
import { v4 as uuidv4 } from 'uuid';
import { createDiscountSchema, trackPromotionSchema, updatedDiscountSchema, validateUUID } from '../helper/validate';
import { CreateDiscountType, UpdateDiscountType } from '../@types';
import { genRandNum, validateDateRange } from '../helper';
import { genRandNum, isUUID, validateDateRange } from '../helper';
import logger from '../config/logger';
import { TestUserId } from '../config/test';

Expand Down Expand Up @@ -46,10 +46,9 @@ export default class DiscountController extends BaseController {

const { amount, discount_type, quantity, maximum_discount_price, product_ids, valid_from, valid_to } =
req.body as CreateDiscountType;
const validDiscountType = ['percentage', 'fixed'];
const validDiscountType = ['percentage'];
const validDiscountEnum = {
percentage: 'Percentage',
fixed: 'Fixed',
};

// verify date range
Expand Down Expand Up @@ -148,6 +147,25 @@ export default class DiscountController extends BaseController {
// check if product exists
// ! Remember to work on accepting an array of product id's.
const { promo_id, productId, merchant_id } = payload;

// check if product and userId id is a valid uuid
if (!isUUID(productId) || !isUUID(merchant_id)) {
logger.error(`[Track Promo]: One of more of the ids passed are invalid.`);

return this.error(res, '--discount/invalid-uuid', `One of more of the ids passed are invalid.`, 400);
}

// check if user exists
const userExists = await prisma.user.findFirst({
where: { id: merchant_id },
});

if (!userExists) {
logger.error(`[Track Promo]: Merchant not found. ${merchant_id}`);

return this.error(res, '--discount/user-notfound', 'Merchant not found', 404);
}

const promo_product = await prisma.promo_product.findFirst({
where: {
product_id: productId,
Expand All @@ -168,7 +186,7 @@ export default class DiscountController extends BaseController {
res,
'--discount/promo-notfound',
`product promo with this id ${promo_id} doesn't exist. `,
404
404,
);
}

Expand Down Expand Up @@ -202,7 +220,7 @@ export default class DiscountController extends BaseController {
'--discount/promo-notfound',
`> Promo tracked for product ${track_promotion.product.name}
> Merchant: ${track_promotion.user.email}`,
404
404,
);
}

Expand Down Expand Up @@ -336,7 +354,7 @@ export default class DiscountController extends BaseController {
'--discount/promotions',
'Products with promotions and tracked promotions fetched successfully',
200,
productsWithPromotionsAndTrackedCounts
productsWithPromotionsAndTrackedCounts,
);
}
}
Expand Down
Loading