-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSplitWise.js
107 lines (83 loc) · 2.56 KB
/
SplitWise.js
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
var Transaction = require('./Transaction').Transaction
var UserTransaction = require('./UserTransaction').UserTransaction
var User = require('./User').User
var Utils = require('./Utils').Utils
var {
TRANSACTION_TYPE_CREDIT,
TRANSACTION_TYPE_DEBIT,
} = require('./constant')
class SplitWise {
#users
#transactions
#user_transactions
constructor() {
this.#users = {}
this.#transactions = {}
this.#user_transactions = {}
}
get Users() {
return this.#users
}
get Transactions() {
return this.#transactions
}
get UserTransactions() {
return this.#user_transactions
}
set Users(users) {
this.#users = users
}
set Transactions(transactions) {
this.#transactions = transactions
}
set UserTransactions(user_transactions) {
this.#user_transactions = user_transactions
}
addUser(name, email, phone) {
try {
var user = User.createUser(name, email, phone)
this.Users = {
...this.Users,
[user.Phone] : user
}
return Utils.success(user)
} catch(err) {
return Utils.failed(err)
}
}
addTransaction(payerPhone, expense_type, amount, payee) {
try {
var payer = this.findUser(payerPhone)
var tran = Transaction.createTransaction(payer.ID, expense_type, amount, payee)
this.Transactions = {
...this.Transactions,
[tran.ID]: tran
}
var ut = UserTransaction.createUserTransaction(tran.ID, payer.ID, TRANSACTION_TYPE_DEBIT, amount)
this.UserTransactions = {
...this.UserTransactions,
[ut.ID] : ut
}
for(let i=0; i<payee.length; i++) {
let phone = payee[i]
let user = this.findUser(phone)
let share = Utils.getShare(payee, amount, expense_type)
let t = UserTransaction.createUserTransaction(tran.ID, user.ID, TRANSACTION_TYPE_CREDIT, share)
this.UserTransactions = {
...this.UserTransactions,
[t.ID] : t
}
}
return Utils.success(tran)
} catch(err) {
return Utils.failed(err)
}
}
findUser(phone) {
if(this.Users[phone] === undefined) {
throw "User not found"
}
return this.Users[phone]
}
}
module.exports.SplitWise = SplitWise