Skip to content
This repository was archived by the owner on May 6, 2022. It is now read-only.

Commit 81918f1

Browse files
authored
Merge pull request #76 from Tolfix/dev
v2.2
2 parents 4c0a9ee + 087a7c9 commit 81918f1

19 files changed

Lines changed: 137 additions & 180 deletions

File tree

package.json

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "cpg-api",
3-
"version": "v2.1",
3+
"version": "v2.2",
44
"description": "Central Payment Gateway",
55
"main": "./build/Main.js",
66
"dependencies": {
@@ -36,6 +36,7 @@
3636
"jsonwebtoken": "^8.5.1",
3737
"mongoose": "^6.1.4",
3838
"mongoose-auto-increment": "^5.0.1",
39+
"mongoose-query-parser": "^1.2.1",
3940
"node-fetch": ">=3.1.1",
4041
"nodemailer": "^6.7.0",
4142
"npm": "^7.20.5",
@@ -57,15 +58,15 @@
5758
},
5859
"repository": {
5960
"type": "git",
60-
"url": "git+https://github.com/Tolfix/CGP-API.git"
61+
"url": "git+https://github.com/Tolfix/cpg-api.git"
6162
},
6263
"keywords": [],
6364
"author": "Tolfix",
6465
"license": "MIT",
6566
"bugs": {
66-
"url": "https://github.com/Tolfix/CGP-API/issues"
67+
"url": "https://github.com/Tolfix/cpg-api/issues"
6768
},
68-
"homepage": "https://github.com/Tolfix/CGP-API#readme",
69+
"homepage": "https://github.com/Tolfix/cpg-api#readme",
6970
"devDependencies": {
7071
"@types/cors": "^2.8.12",
7172
"@types/cron": "^1.7.3",

src/Config.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ export const Plugins: Array<string> = JSON.parse(process.env.PLUGINS ?? "[]");
127127
// Webhooks
128128
export const Webhook_Secret = process.env.WEBHOOK_SECRET ?? "";
129129

130-
export const GetSMTPConfig: () => Promise<IConfigs["smtp"]> = () =>
130+
export const GetSMTPConfig: () => Promise<IConfigs["smtp"]> = async () =>
131131
{
132132
return ConfigModel.find().then(config =>
133133
{

src/Database/Models/Customers/Customer.model.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import mongoose, { Document, model, Schema } from "mongoose"
22
import increment from "mongoose-auto-increment";
33
import { Default_Language, MongoDB_URI } from "../../../Config";
4-
import { ICustomer } from "../../../Interfaces/Customer.interface";
4+
import { ICustomer, ICustomerMethods } from "../../../Interfaces/Customer.interface";
55
import Logger from "../../../Lib/Logger";
66
import GetText from "../../../Translation/GetText";
77

@@ -101,6 +101,11 @@ const CustomerSchema = new Schema
101101
}
102102
);
103103

104+
CustomerSchema.methods.fullName = function(sC = false)
105+
{
106+
return `${this.personal.first_name} ${this.personal.last_name} ${sC ? (this.billing.company ? ` (${this.billing.company})` : "") : ""}`;
107+
}
108+
104109
// Log when creation
105110
CustomerSchema.post('save', function(doc: ICustomer & Document)
106111
{
@@ -118,6 +123,6 @@ CustomerSchema.plugin(increment.plugin, {
118123
incrementBy: 1
119124
});
120125

121-
const CustomerModel = model<ICustomer & Document>("customer", CustomerSchema);
126+
const CustomerModel = model<ICustomer & Document & ICustomerMethods>("customer", CustomerSchema);
122127

123128
export default CustomerModel;

src/Interfaces/Customer.interface.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ export interface ICustomer
3131
};
3232
}
3333

34+
export interface ICustomerMethods
35+
{
36+
fullName<incCo extends boolean | undefined = undefined>(sC?: incCo): incCo extends undefined ? `${string} ${string}` : `${string} ${string} ${string}`;
37+
}
38+
3439
export interface Personal
3540
{
3641
first_name: string;

src/Lib/MongoFind.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { Model } from "mongoose";
2+
import { Request } from "express"
3+
import { MongooseQueryParser } from "mongoose-query-parser";
4+
const p = new MongooseQueryParser();
5+
6+
export default function MongoFind<T>(model: Model<T>, query: Request["query"], eQuery?: any)
7+
{
8+
const data = p.parse(query);
9+
10+
const b = model.find({
11+
...data.filter,
12+
...eQuery ?? {}
13+
}).sort(data.sort ?? "1").skip(data.skip ?? 0).limit(data.limit ?? 10);
14+
if(data.select)
15+
b.select(data.select);
16+
17+
if(data.populate)
18+
b.populate(data.populate);
19+
20+
return b.exec();
21+
}

src/Middlewares/EnsureAuth.ts

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,25 +9,35 @@ export default function EnsureAuth()
99
return (req: Request, res: Response, next: NextFunction) =>
1010
{
1111
const authHeader = req.headers['authorization'];
12-
if(!authHeader)
12+
const tokenQuery = req.query.access_token;
13+
if(!authHeader && !tokenQuery)
1314
return APIError({
1415
text: "Missing 'authorization' in header"
1516
})(res);
1617

17-
const b64auth = (authHeader).split(' ');
18+
let b64auth: string[];
19+
if(authHeader)
20+
b64auth = authHeader.split(' ');
1821

19-
if(!b64auth[0].toLocaleLowerCase().match(/basic|bearer/g))
22+
if(tokenQuery)
23+
b64auth = ["query", tokenQuery as string];
24+
25+
// @ts-ignore
26+
if(!b64auth[0].toLocaleLowerCase().match(/query|bearer/g))
2027
return APIError({
2128
text: "Missing 'basic' or 'bearer' in authorization"
2229
})(res);
23-
30+
31+
// @ts-ignore
2432
if(!b64auth[1])
2533
return APIError({
2634
text: "Missing 'buffer' in authorization"
2735
})(res);
28-
29-
if(b64auth[0].toLocaleLowerCase() === "bearer")
36+
37+
// @ts-ignore
38+
if(b64auth[0].toLocaleLowerCase() === "bearer" || b64auth[0].toLocaleLowerCase() === "query")
3039
{
40+
// @ts-ignore
3141
const token = (Buffer.isBuffer(b64auth[1]) ? Buffer.from(b64auth[1], 'base64') : b64auth[1]).toString();
3242
jwt.verify(token, JWT_Access_Token, (err, payload) =>
3343
{

src/Models/BaseModelAPI.ts

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import { Request } from "express";
2+
import MongoFind from "../Lib/MongoFind";
3+
14
export default class BaseModelAPI<IModel extends { uid: string }>
25
{
36
private idFunction;
@@ -39,26 +42,21 @@ export default class BaseModelAPI<IModel extends { uid: string }>
3942
});
4043
}
4144

42-
public findAll(limit: number, skip: number, sort: string, order: string): Promise<Array<IModel>>
45+
public findAll(query: Request["query"]): Promise<Array<IModel>>
4346
{
4447
return new Promise((resolve, reject) =>
4548
{
46-
this.iModel.find()
47-
.select("-_id -__v")
48-
.limit(limit)
49-
.skip(skip)
50-
.sort({ sort: order })
51-
.exec(function (err: any, users: any)
49+
MongoFind(this.iModel, query).then((result: any) =>
50+
{
51+
const r = result.map((i: any) =>
5252
{
53-
if (err)
54-
{
55-
reject(err);
56-
}
57-
else
58-
{
59-
resolve(users);
60-
}
61-
})
53+
const r = i.toJSON();
54+
//@ts-ignore
55+
delete r.__v;
56+
return r;
57+
});
58+
resolve(r);
59+
}).catch(reject);
6260
});
6361
}
6462

src/Server/Routes/v2/Categories/Categories.controller.ts

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,7 @@ function getByUid(req: Request, res: Response)
3333

3434
function list(req: Request, res: Response)
3535
{
36-
const limit = parseInt(req.query._end as string)
37-
&& parseInt(req.query._end as string) <= 100 ?
38-
parseInt(req.query._end as string)
39-
:
40-
25;
41-
let start = 0;
42-
if(req.query)
43-
if(req.query._start)
44-
start = Number.isInteger(parseInt(req.query._start as string)) ? parseInt(req.query._start as string) : 0;
45-
46-
const sort = req.query._sort as string ?? "id";
47-
const order = req.query._order as string ?? "asc";
48-
49-
API.findAll(limit, start, sort, order).then((result: any) =>
36+
API.findAll(req.query).then((result: any) =>
5037
{
5138
APISuccess(result)(res)
5239
})

src/Server/Routes/v2/ConfigurableOptions/ConfigurableOptions.controller.ts

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,20 +32,7 @@ function getByUid(req: Request, res: Response)
3232

3333
function list(req: Request, res: Response)
3434
{
35-
const limit = parseInt(req.query._end as string)
36-
&& parseInt(req.query._end as string) <= 100 ?
37-
parseInt(req.query._end as string)
38-
:
39-
25;
40-
let start = 0;
41-
if(req.query)
42-
if(req.query._start)
43-
start = Number.isInteger(parseInt(req.query._start as string)) ? parseInt(req.query._start as string) : 0;
44-
45-
const sort = req.query._sort as string ?? "id";
46-
const order = req.query._order as string ?? "asc";
47-
48-
API.findAll(limit, start, sort, order).then((result: any) =>
35+
API.findAll(req.query).then((result: any) =>
4936
{
5037
APISuccess(result)(res)
5138
});

src/Server/Routes/v2/Customers/Customers.config.ts

Lines changed: 52 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ import LoginAttemptTemplate from "../../../../Email/Templates/Customer/LoginAtte
2121
import ResetPasswordTemplate from "../../../../Email/Templates/Customer/ResetPassword.template";
2222
import OrderCancelTemplate from "../../../../Email/Templates/Customer/OrderCancel.template";
2323
import Header from "../../../../Email/Templates/General/Header";
24+
import MongoFind from "../../../../Lib/MongoFind";
25+
import createPDFInvoice from "../../../../Lib/Invoices/CreatePDFInvoice";
2426

2527
export = class CustomerRouter
2628
{
@@ -53,10 +55,10 @@ export = class CustomerRouter
5355
if(!customer)
5456
return APIError(`Unable to find customer`)(res);
5557

56-
const invoices = await InvoiceModel.find({
58+
const invoices = await MongoFind(InvoiceModel, req.query, {
5759
$or: [
58-
{ customer_uid: customer.uid},
59-
{ customer_uid: customer.id}
60+
{ customer_uid: customer.uid },
61+
{ customer_uid: customer.id }
6062
]
6163
});
6264

@@ -78,7 +80,7 @@ export = class CustomerRouter
7880
if(!customer)
7981
return APIError(`Unable to find customer`)(res);
8082

81-
const invoice = await InvoiceModel.findOne({
83+
const [invoice] = await MongoFind(InvoiceModel, req.query, {
8284
// lol almost forgot to add customer_uid kek
8385
$or: [
8486
{
@@ -97,6 +99,46 @@ export = class CustomerRouter
9799
return APISuccess(invoice)(res);
98100
});
99101

102+
this.router.get("/my/invoices/:id/preview", EnsureAuth(), async (req, res) =>
103+
{
104+
const invoiceId = req.params.id;
105+
106+
if(!invoiceId)
107+
return APIError(`Invalid invoice id`)(res);
108+
109+
const customer = await CustomerModel.findOne({
110+
// @ts-ignore
111+
id: req.customer.id
112+
});
113+
114+
if(!customer)
115+
return APIError(`Unable to find customer`)(res);
116+
117+
const [invoice] = await MongoFind(InvoiceModel, req.query, {
118+
// lol almost forgot to add customer_uid kek
119+
$or: [
120+
{
121+
customer_uid: customer.uid,
122+
},
123+
{
124+
customer_uid: customer.id,
125+
},
126+
],
127+
id: invoiceId,
128+
});
129+
130+
if(!invoice)
131+
return APIError(`Unable to find invoice`)(res);
132+
133+
const result = await createPDFInvoice(invoice);
134+
135+
res.writeHead(200, {
136+
'Content-Type': "application/pdf",
137+
});
138+
139+
return res.end(result, "base64");
140+
});
141+
100142
this.router.get("/my/orders", EnsureAuth(), async (req, res) =>
101143
{
102144
const customer = await CustomerModel.findOne({
@@ -107,10 +149,10 @@ export = class CustomerRouter
107149
if(!customer)
108150
return APIError(`Unable to find customer`)(res);
109151

110-
const orders = await OrderModel.find({
152+
const orders = await MongoFind(OrderModel, req.query,{
111153
$or: [
112-
{ customer_uid: customer.uid},
113-
{ customer_uid: customer.id}
154+
{ customer_uid: customer.uid },
155+
{ customer_uid: customer.id }
114156
]
115157
});
116158

@@ -132,7 +174,7 @@ export = class CustomerRouter
132174
if(!customer)
133175
return APIError(`Unable to find customer`)(res);
134176

135-
const order = await OrderModel.findOne({
177+
const [order] = await MongoFind(OrderModel, req.query,{
136178
$or: [
137179
{
138180
customer_uid: customer.uid,
@@ -215,7 +257,7 @@ export = class CustomerRouter
215257
if(!customer)
216258
return APIError(`Unable to find customer`)(res);
217259

218-
const transactions = await TransactionsModel.find({
260+
const transactions = await MongoFind(TransactionsModel, req.query,{
219261
$or: [
220262
{ customer_uid: customer.uid},
221263
{ customer_uid: customer.id}
@@ -240,7 +282,7 @@ export = class CustomerRouter
240282
if(!customer)
241283
return APIError(`Unable to find customer`)(res);
242284

243-
const transactions = await TransactionsModel.find({
285+
const [transactions] = await MongoFind(TransactionsModel, req.query,{
244286
$or: [
245287
{
246288
customer_uid: customer.uid,

0 commit comments

Comments
 (0)