-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbillingNew.ts
More file actions
343 lines (296 loc) · 10.5 KB
/
billingNew.ts
File metadata and controls
343 lines (296 loc) · 10.5 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import BusinessOperationModel from '../models/businessOperation';
import { ResolverContextWithUser } from '../types/graphql';
import WorkspaceModel from '../models/workspace';
import UserModel from '../models/user';
import {
BusinessOperationPayloadType,
PayloadOfDepositByUser,
PayloadOfWorkspacePlanPurchase
} from '@hawk.so/types';
import checksumService from '../utils/checksumService';
import { UserInputError } from 'apollo-server-express';
import cloudPaymentsApi, { CloudPaymentsJsonData } from '../utils/cloudPaymentsApi';
import * as telegram from '../utils/telegram';
import { TelegramBotURLs } from '../utils/telegram';
/**
* The amount we will debit to confirm the subscription.
* After confirmation, we will refund the user money.
*/
const AMOUNT_FOR_CARD_VALIDATION = 1;
/**
* Input data for composePayment query
*/
interface ComposePaymentArgs {
input: {
workspaceId: string;
tariffPlanId: string;
shouldSaveCard?: boolean;
};
}
/**
* Data for processing payment with saved card
*/
interface PayWithCardArgs {
/**
* Input data
*/
input: {
/**
* Checksum for payment validation
*/
checksum: string;
/**
* Card id for processing payments
*/
cardId: string;
/**
* Is payment recurrent or not. If payment is recurrent, then the money will be debited every month
*/
isRecurrent?: boolean;
};
}
export default {
Query: {
/**
* API Query method for getting all transactions for passed workspaces
* @param _obj - parent object
* @param ids - ids of workspaces for which transactions have been requested
* @param user - current authorized user
* @param factories - factories for working with models
*/
async businessOperations(
_obj: undefined,
{ ids }: { ids: string[] },
{ user, factories }: ResolverContextWithUser
): Promise<BusinessOperationModel[]> {
return factories.businessOperationsFactory.getWorkspacesBusinessOperations(ids);
},
/**
* GraphQL version of composePayment: prepares data before charge
*/
async composePayment(
_obj: undefined,
{ input }: ComposePaymentArgs,
{ user, factories }: ResolverContextWithUser
): Promise<{
invoiceId: string;
plan: { id: string; name: string; monthlyCharge: number };
isCardLinkOperation: boolean;
currency: string;
checksum: string;
nextPaymentDate: Date;
cloudPaymentsPublicId: string;
}> {
const { workspaceId, tariffPlanId, shouldSaveCard } = input;
if (!workspaceId || !tariffPlanId || !user?.id) {
throw new UserInputError('No workspaceId, tariffPlanId or user id provided');
}
const workspace = await factories.workspacesFactory.findById(workspaceId);
const plan = await factories.plansFactory.findById(tariffPlanId);
if (!workspace || !plan) {
throw new UserInputError("Can't get workspace or plan by provided ids");
}
const member = await workspace.getMemberInfo(user.id);
if (!member) {
throw new UserInputError('User is not a member of the workspace');
}
const now = new Date();
const invoiceId = `${workspace.name} ${now.getDate()}/${now.getMonth() + 1} ${plan.name}`;
let isCardLinkOperation = false;
/**
* We need to only link card and not pay for the whole plan in case
* 1. We are paying for the same plan and
* 2. Plan is not expired and
* 3. Workspace is not blocked
*/
if (
workspace.tariffPlanId.toString() === tariffPlanId && // 1
!workspace.isTariffPlanExpired() && // 2
!workspace.isBlocked // 3
) {
isCardLinkOperation = true;
}
// Calculate next payment date
const lastChargeDate = workspace.lastChargeDate ? new Date(workspace.lastChargeDate) : now;
const nextPaymentDate = isCardLinkOperation ? new Date(lastChargeDate) : new Date(now);
if (workspace.isDebug) {
nextPaymentDate.setDate(nextPaymentDate.getDate() + 1);
} else {
nextPaymentDate.setMonth(nextPaymentDate.getMonth() + 1);
}
const checksumData = isCardLinkOperation
? {
isCardLinkOperation: true as const,
workspaceId: workspace._id.toString(),
userId: user.id,
nextPaymentDate: nextPaymentDate.toISOString(),
}
: {
workspaceId: workspace._id.toString(),
userId: user.id,
tariffPlanId: plan._id.toString(),
shouldSaveCard: Boolean(shouldSaveCard),
nextPaymentDate: nextPaymentDate.toISOString(),
};
const checksum = await checksumService.generateChecksum(checksumData);
/**
* Send info to Telegram (non-blocking)
*/
telegram
.sendMessage(`👀 [Billing / Compose payment]
card link operation: ${isCardLinkOperation}
amount: ${+plan.monthlyCharge} RUB
last charge date: ${workspace.lastChargeDate?.toISOString()}
next payment date: ${nextPaymentDate.toISOString()}
workspace id: ${workspace._id.toString()}
debug: ${Boolean(workspace.isDebug)}`
, TelegramBotURLs.Money)
.catch(e => console.error('Error while sending message to Telegram: ' + e));
return {
invoiceId,
plan: {
id: plan._id.toString(),
name: plan.name,
monthlyCharge: plan.monthlyCharge,
},
isCardLinkOperation,
currency: 'RUB',
checksum,
nextPaymentDate,
cloudPaymentsPublicId: process.env.CLOUDPAYMENTS_PUBLIC_ID || '',
};
},
},
/**
* Resolver for Union Payload type.
* Represents two types of payload depending on the operation's type
*/
BusinessOperationPayload: {
/**
* Returns type of the payload
* @param payload - result from resolver above
*/
__resolveType(payload: BusinessOperationPayloadType): string {
if ('cardPan' in payload) {
return 'PayloadOfDepositByUser';
}
return 'PayloadOfWorkspacePlanPurchase';
/**
* @todo access to operation.type
*/
/*
* if (operation.type) {
* case BusinessOperationType.WorkspacePlanPurchase:
* return 'PayloadOfWorkspacePlanPurchase';
* default:
* case BusinessOperationType.DepositByUser:
* return 'PayloadOfDepositByUser';
* }
*/
},
},
PayloadOfWorkspacePlanPurchase: {
/**
* Resolver for workspace by workspaceId
*
* @param payload - operation metadata
* @param _args - resolver args
* @param factories - resolver factories
*/
async workspace(payload: PayloadOfWorkspacePlanPurchase, _args: undefined, { factories }: ResolverContextWithUser): Promise<WorkspaceModel | null> {
return factories.workspacesFactory.findById(payload.workspaceId.toHexString());
},
},
PayloadOfDepositByUser: {
/**
* Resolver for workspace by workspaceId
*
* @param payload - operation metadata
* @param _args - resolver args
* @param factories - resolver factories
*/
async workspace(payload: PayloadOfDepositByUser, _args: undefined, { factories }: ResolverContextWithUser): Promise<WorkspaceModel | null> {
return factories.workspacesFactory.findById(payload.workspaceId.toHexString());
},
/**
* Resolver for user by userId
*
* @param payload - operation metadata
* @param _args - resolver args
* @param factories - resolver factories
*/
async user(payload: PayloadOfDepositByUser, _args: undefined, { factories }: ResolverContextWithUser): Promise<UserModel | null> {
return factories.usersFactory.findById(payload.userId.toHexString());
},
},
Mutation: {
/**
* Mutation for processing payment via saved card
*
* @param _obj - parent object
* @param args - mutation args
* @param user - current authorized user
* @param factories - factories for working with models
*/
async payWithCard(_obj: undefined, args: PayWithCardArgs, { factories, user }: ResolverContextWithUser): Promise<any> {
const paymentData = checksumService.parseAndVerifyChecksum(args.input.checksum);
if (!('tariffPlanId' in paymentData)) {
throw new UserInputError('Invalid checksum');
}
const fullUserInfo = await factories.usersFactory.findById(user.id);
const workspace = await factories.workspacesFactory.findById(paymentData.workspaceId);
const member = await workspace?.getMemberInfo(user.id);
const plan = await factories.plansFactory.findById(paymentData.tariffPlanId);
if (!workspace || !member || !plan || !fullUserInfo) {
throw new UserInputError('Wrong checksum data');
}
const token = fullUserInfo.bankCards?.find(card => card.id === args.input.cardId)?.token;
if (!token) {
throw new UserInputError('There is no saved card with provided id');
}
const jsonData: CloudPaymentsJsonData = {
checksum: args.input.checksum,
};
const isTariffPlanExpired = workspace.isTariffPlanExpired();
const dueDate = workspace.getTariffPlanDueDate();
if (args.input.isRecurrent) {
const interval = workspace.isDebug ? 'Day' : 'Month';
jsonData.cloudPayments = {
recurrent: {
interval,
period: 1,
},
};
/**
* If workspace has active tariff plan (not expired),
* we need to withdraw money only after tariff plan expired
*/
if (!isTariffPlanExpired) {
jsonData.cloudPayments.recurrent.startDate = dueDate.toDateString();
jsonData.cloudPayments.recurrent.amount = plan.monthlyCharge;
}
}
let amount = plan.monthlyCharge;
const isPaymentForCurrentTariffPlan = workspace.tariffPlanId.toString() === plan._id.toString();
/**
* True when we need to withdraw the amount only to validate the subscription
*/
const isOnlyCardValidationNeeded = args.input.isRecurrent && isPaymentForCurrentTariffPlan && !isTariffPlanExpired;
if (isOnlyCardValidationNeeded) {
amount = AMOUNT_FOR_CARD_VALIDATION;
}
const result = await cloudPaymentsApi.payByToken({
AccountId: user.id,
Amount: amount,
Token: token,
Currency: 'RUB',
JsonData: jsonData,
});
const operation = await factories.businessOperationsFactory.getBusinessOperationByTransactionId(result.Model.TransactionId.toString());
return {
recordId: operation?._id,
record: operation,
};
},
},
};