Skip to content

Commit

Permalink
Merge pull request #99 from AhmadReshadarm/master
Browse files Browse the repository at this point in the history
Feauters/Notification
  • Loading branch information
mr4pson authored Oct 30, 2022
2 parents 6bcd1f9 + b22620c commit 687bfda
Show file tree
Hide file tree
Showing 17 changed files with 578 additions and 196 deletions.
2 changes: 1 addition & 1 deletion core/entities/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export { Review, Comment, ReactionComment, ReactionReview } from './reviews/';
export { Question, QuestionComment, QuestionReactionComment, ReactionQuestion } from './questions';
export { Wishlist, WishlistProduct } from './wishlists';
export { Slide, Advertisement } from './banners';
export { Basket, OrderProduct, Address, Checkout } from './orders';
export { Basket, OrderProduct, Address, Checkout, Subscription } from './orders';
export {
Brand,
Category,
Expand Down
3 changes: 2 additions & 1 deletion core/entities/orders/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { Basket } from './basket.entity';
export { OrderProduct } from "./orderProduct.entity";
export { OrderProduct } from './orderProduct.entity';
export { Address } from './address.entity';
export { Checkout } from './checkout.entity';
export { Subscription } from './subscrition.entity';
16 changes: 16 additions & 0 deletions core/entities/orders/subscrition.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Subscription {
@PrimaryGeneratedColumn()
id: string;

@Column('text', { nullable: true })
subscriber: string;

constructor(args?: { subscriber: string }) {
if (args) {
this.subscriber = args.subscriber;
}
}
}
10 changes: 6 additions & 4 deletions orders/basket/basket.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ export class BasketController {
// if (resp.locals.user?.role !== Role.Admin) {
// req.query.userId = String(resp.locals.user?.id);
// }

const baskets = await this.basketService.getBaskets(req.query);

resp.json(baskets);
try {
const baskets = await this.basketService.getBaskets(req.query);
resp.json(baskets);
} catch (error) {
resp.status(HttpStatus.INTERNAL_SERVER_ERROR).json(`somthing went wrong ${error}`);
}
}

@Get(':id')
Expand Down
76 changes: 67 additions & 9 deletions orders/checkout/checkout.controller.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { CheckoutStatus } from 'core/enums/checkout-status.enum';
import webpush from 'web-push';
import { Role } from '../../core/enums/roles.enum';
import { Request, Response } from 'express';
import { Request, Response, NextFunction } from 'express';
import { singleton } from 'tsyringe';
import { Controller, Delete, Get, Middleware, Post, Put } from '../../core/decorators';
import { Checkout } from '../../core/entities';
import { Checkout, Subscription } from '../../core/entities';
import { HttpStatus } from '../../core/lib/http-status';
import { validation } from '../../core/lib/validator';
import { isAdmin, isUser, verifyToken } from '../../core/middlewares';
import { createInvoice } from '../../orders/functions/createInvoice';
import { sendInvoice } from '../../orders/functions/send.mail';
import { CheckoutService } from './checkout.service';
import { invoiceTamplate } from '../functions/invoice.tamplate';

@singleton()
@Controller('/checkouts')
Expand Down Expand Up @@ -50,14 +51,71 @@ export class CheckoutController {
async createCheckout(req: Request, resp: Response) {
const newCheckout = new Checkout(req.body);
newCheckout.userId = resp.locals.user.id;
const name = resp.locals.user.name;
const { jwt } = resp.locals;
let created: any;
try {
await validation(newCheckout);
} catch (error) {
console.log(`validation faild: ${error}`);
}
try {
created = await this.checkoutService.createCheckout(newCheckout);
resp.status(HttpStatus.CREATED).json(created);
} catch (error) {
resp.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: `saving order faild: ${error}` });
}
try {
const invoiceData: any = await createInvoice(created!, jwt.name);
sendInvoice(invoiceTamplate(invoiceData), jwt.email);
console.log('invoice send succsfuly');
} catch (error) {
console.log(`sending invoice faild: ${error}`);
}
try {
const subscrition = await this.checkoutService.getSubscribers();
if (!subscrition || subscrition.length === 0) return;
const payload = JSON.stringify({
title: `Заказ №: ${created?.id}`,
message: `Сума: ${created?.totalAmount}`,
url: `https:wuluxe.ru/admin/checkouts/${created?.id}`,
});
webpush.setVapidDetails(
'mailto:[email protected]',
process.env.NOTIFACATION_PUBLIC_KEY!,
process.env.NOTIFACATION_PRIVATE_KEY!,
);
for (let i = 0; i < subscrition.length; i++) {
webpush.sendNotification(JSON.parse(`${subscrition[i].subscriber}`), payload);
}
} catch (error) {
console.log(`sending notification faild: ${error}`);
}
}

await validation(newCheckout);
const created = await this.checkoutService.createCheckout(newCheckout);
@Post('subscribe')
@Middleware([verifyToken, isAdmin])
async createSubscriber(req: Request, resp: Response, next: NextFunction) {
try {
const subscrition = await this.checkoutService.getSubscribers();
if (subscrition && subscrition.length !== 0) {
for (let i = 0; i < subscrition.length; i++) {
if (subscrition[i].subscriber === req.body.subscriber) {
resp.status(HttpStatus.ACCEPTED).json({ message: 'Your are all set' });
return;
}
}
}
} catch (error) {
next();
}

// const invoice = await createInvoice(created!, { name });
// sendInvoice(invoice, resp.locals.user.email);
resp.status(HttpStatus.CREATED).json(created);
try {
const newSubscrition = await validation(new Subscription({ subscriber: req.body.subscriber }));
const created = await this.checkoutService.createSubscriber(newSubscrition);
resp.status(HttpStatus.OK).json(created);
} catch (error) {
resp.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: `somthing went wrong: ${error}` });
}
}

@Put(':id')
Expand Down
15 changes: 15 additions & 0 deletions orders/checkout/checkout.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { DataSource, Equal, Repository } from 'typeorm';
import { CustomExternalError } from '../../core/domain/error/custom.external.error';
import { ErrorCode } from '../../core/domain/error/error.code';
import { Checkout } from '../../core/entities';
import { Subscription } from '../../core/entities';
import { Role } from '../../core/enums/roles.enum';
import { PaginationDTO } from '../../core/lib/dto';
import { HttpStatus } from '../../core/lib/http-status';
Expand All @@ -14,9 +15,11 @@ import { CheckoutDTO, CheckoutQueryDTO, UserAuth, UserDTO } from '../order.dtos'
@singleton()
export class CheckoutService {
private checkoutRepository: Repository<Checkout>;
private subscribersRepository: Repository<Subscription>;

constructor(dataSource: DataSource, private orderProductService: OrderProductService) {
this.checkoutRepository = dataSource.getRepository(Checkout);
this.subscribersRepository = dataSource.getRepository(Subscription);
}

async getCheckouts(
Expand Down Expand Up @@ -136,6 +139,18 @@ export class CheckoutService {
}
}

async createSubscriber(newSubscrition: Subscription): Promise<Subscription | null> {
return this.subscribersRepository.save(newSubscrition);
}

async getSubscribers(): Promise<any> {
return await this.subscribersRepository.find({
order: {
id: 'DESC',
},
});
}

async createCheckout(newCheckout: Checkout): Promise<Checkout | null> {
const created = await this.checkoutRepository.save(newCheckout);

Expand Down
29 changes: 7 additions & 22 deletions orders/functions/createInvoice.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,35 @@
const niceInvoice = require('nice-invoice');
import axios from 'axios';
import { Checkout, OrderProduct } from 'core/entities';
const getProducts = async (orderProducts: OrderProduct[]) => {
const products = [];
for (const orderProduct of orderProducts) {
const product = await axios.get(`${process.env.CATALOG_DB}/products/${orderProduct.productId}`);
products.push({
item: product.data.name,
name: product.data.name,
description: `${product.data.desc.slice(0, 70)}...`,
quantity: orderProduct.qty,
price: orderProduct.productPrice,
tax: '',
});
}

return products;
};
const createInvoice = async (checkout: Checkout, user: { name: string }) => {
const createInvoice = async (checkout: Checkout, userName: any) => {
const invoiceDetail = {
shipping: {
name: user.name,
name: userName,
address: checkout.address.address,
city: '_',
state: '_',
country: 'RU',
door: checkout.address.door,
floor: checkout.address.floor,
receverName: checkout.address.receiverName,
postal_code: checkout.address.zipCode,
},
items: await getProducts(checkout.basket.orderProducts),

subtotal: checkout.totalAmount,
total: checkout.totalAmount,
order_number: checkout.id,
header: {
company_name: 'Wuluxe',
company_address: 'МО, г. Люберцы, Октябрьский проспект 181',
},
footer: {
text: 'wuluxe.ru',
},
currency_symbol: '₽',
date: {
billing_date: new Date(checkout.createdAt).toLocaleDateString('ru-RU'),
},
billingDate: checkout.createdAt,
};
return invoiceDetail;
// return niceInvoice(invoiceDetail, 'wuluxe.pdf');
};

export { createInvoice };
144 changes: 0 additions & 144 deletions orders/functions/index.html

This file was deleted.

Loading

0 comments on commit 687bfda

Please sign in to comment.