-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathseller-payout-service.ts
215 lines (190 loc) · 6.57 KB
/
seller-payout-service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/**
* SudoSOS back-end API service.
* Copyright (C) 2024 Study association GEWIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @license
*/
/**
* This is the module page of the seller-payout-service.
*
* @module seller-payouts
*/
import {
FindManyOptions,
FindOptionsRelations,
FindOptionsWhere,
} from 'typeorm';
import QueryFilter, { FilterMapping } from '../helpers/query-filter';
import SellerPayout from '../entity/transactions/payout/seller-payout';
import { PaginationParameters } from '../helpers/pagination';
import { UpdateSellerPayoutRequest } from '../controller/request/seller-payout-request';
import Dinero from 'dinero.js';
import TransferService from './transfer-service';
import User from '../entity/user/user';
import { SellerPayoutResponse } from '../controller/response/seller-payout-response';
import { parseUserToBaseResponse } from '../helpers/revision-to-response';
import { RequestWithToken } from '../middleware/token-middleware';
import { asDate, asNumber } from '../helpers/validators';
import { SalesReportService } from './report-service';
import WithManager from '../database/with-manager';
export interface SellerPayoutFilterParameters {
sellerPayoutId?: number;
requestedById?: number;
fromDate?: Date;
tillDate?: Date;
returnTransfer?: boolean;
}
export interface CreateSellerPayoutParams {
requestedById: number;
reference: string;
startDate: Date;
endDate: Date;
}
export function parseSellerPayoutFilters(req: RequestWithToken): SellerPayoutFilterParameters {
return {
requestedById: asNumber(req.query.requestedById),
fromDate: asDate(req.query.fromDate),
tillDate: asDate(req.query.tillDate),
};
}
export default class SellerPayoutService extends WithManager {
public static asSellerPayoutResponse(payout: SellerPayout): SellerPayoutResponse {
return {
id: payout.id,
createdAt: payout.createdAt.toISOString(),
updatedAt: payout.updatedAt.toISOString(),
version: payout.version,
requestedBy: parseUserToBaseResponse(payout.requestedBy, false),
amount: payout.amount.toObject(),
startDate: payout.startDate.toISOString(),
endDate: payout.endDate.toISOString(),
reference: payout.reference,
};
}
/**
* Get seller payouts from database
* @param params
* @param pagination
*/
public async getSellerPayouts(
params: SellerPayoutFilterParameters,
pagination: PaginationParameters = {},
): Promise<[SellerPayout[], number]> {
const { take, skip } = pagination;
const [data, count] = await this.manager.findAndCount(SellerPayout, {
...(SellerPayoutService.getOptions(params)),
take,
skip,
});
return [data, count];
}
/**
* Create a new seller payout
* @param params
*/
public async createSellerPayout(params: CreateSellerPayoutParams): Promise<SellerPayout> {
const report = await new SalesReportService().getReport({
forId: params.requestedById,
fromDate: params.startDate,
tillDate:params.endDate,
});
const amount = report.totalInclVat;
const requestedBy = await this.manager.getRepository(User)
.findOne({ where: { id: params.requestedById } });
if (!requestedBy) {
throw new Error(`User with ID "${params.requestedById}" not found.`);
}
const transfer = await new TransferService().createTransfer({
createdAt: params.endDate.toISOString(),
amount: amount.toObject(),
description: `Seller payout: ${params.reference}`,
fromId: params.requestedById,
toId: null,
});
const payout = await this.manager.getRepository(SellerPayout).save({
...params,
requestedBy,
amount,
transfer,
});
const [[dbPayout]] = await this.getSellerPayouts({ sellerPayoutId: payout.id, returnTransfer: true });
return dbPayout;
}
/**
* Update an existing seller payout
* @param id
* @param params
*/
public async updateSellerPayout(id: number, params: UpdateSellerPayoutRequest): Promise<SellerPayout> {
let [[payout]] = await this.getSellerPayouts({ sellerPayoutId: id, returnTransfer: true });
if (!payout) {
throw new Error(`Payout with ID "${id}" not found.`);
}
const { amount: amountReq, ...rest } = params;
const amount = Dinero(amountReq);
await this.manager.getRepository(SellerPayout).update(id, {
amount,
...rest,
});
const { transfer } = payout;
transfer.amountInclVat = amount;
await this.manager.save(transfer);
[[payout]] = await this.getSellerPayouts({ sellerPayoutId: id, returnTransfer: true });
return payout;
}
/**
* Delete an existing seller payout (with its corresponding transfer)
* @param id
*/
public async deleteSellerPayout(id: number) {
const [[payout]] = await this.getSellerPayouts({ sellerPayoutId: id, returnTransfer: true });
if (!payout) {
throw new Error(`Payout with ID "${id}" not found.`);
}
await this.manager.remove(payout);
await this.manager.remove(payout.transfer);
}
/**
* Create filter options object
* @param params
*/
public static getOptions(params: SellerPayoutFilterParameters): FindManyOptions<SellerPayout> {
const filterMapping: FilterMapping = {
sellerPayoutId: 'id',
requestedById: 'requestedBy.id',
};
const relations: FindOptionsRelations<SellerPayout> = {
requestedBy: true,
transfer: params.returnTransfer,
};
const whereOptions: FindOptionsWhere<SellerPayout> = QueryFilter.createFilterWhereClause(filterMapping, params);
const whereOptionsDates = QueryFilter.createFilterWhereDateRange<SellerPayout>('startDate', 'endDate', params.fromDate, params.tillDate);
let where: FindOptionsWhere<SellerPayout>[];
if (whereOptionsDates.length > 0) {
where = whereOptionsDates.map((w) => ({
...w,
...whereOptions,
}));
} else {
where = [whereOptions];
}
return {
where,
relations,
order: { endDate: 'DESC' },
};
}
}