-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
301 lines (270 loc) · 12.8 KB
/
Copy pathmain.cpp
File metadata and controls
301 lines (270 loc) · 12.8 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
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <memory>
#include <sstream>
// --- Предварительные объявления ---
class Transaction;
class Client;
// --- Pattern: Strategy (Способы оплаты) ---
class PaymentStrategy {
public:
virtual ~PaymentStrategy() = default;
virtual std::string getName() const = 0;
virtual int calculateTotal(int amount) const = 0;
virtual bool canPay(const Client& client, int total) const = 0;
virtual void charge(Client& client, int total) const = 0;
virtual void refund(Client& client, int total) const = 0;
};
// --- Предметная область: Client ---
class Client {
public:
std::string name;
int cardBalance;
int walletBalance;
int creditLimit;
Client(std::string n, int cb, int wb, int cl)
: name(std::move(n)), cardBalance(cb), walletBalance(wb), creditLimit(cl) {}
};
// Конкретные стратегии [cite: 40, 118]
class CardStrategy : public PaymentStrategy {
public:
std::string getName() const override { return "Card"; }
int calculateTotal(int amount) const override { return amount + 2; }
bool canPay(const Client& client, int total) const override { return client.cardBalance >= total; }
void charge(Client& client, int total) const override { client.cardBalance -= total; }
void refund(Client& client, int total) const override { client.cardBalance += total; }
};
class WalletStrategy : public PaymentStrategy {
public:
std::string getName() const override { return "Wallet"; }
int calculateTotal(int amount) const override { return amount; }
bool canPay(const Client& client, int total) const override { return client.walletBalance >= total; }
void charge(Client& client, int total) const override { client.walletBalance -= total; }
void refund(Client& client, int total) const override { client.walletBalance += total; }
};
class InstallmentsStrategy : public PaymentStrategy {
public:
std::string getName() const override { return "Installments"; }
int calculateTotal(int amount) const override { return amount + 10; }
bool canPay(const Client& client, int total) const override { return client.creditLimit >= total; }
void charge(Client& client, int total) const override { client.creditLimit -= total; }
void refund(Client& client, int total) const override { client.creditLimit += total; }
};
// --- Pattern: State (Жизненный цикл транзакции) ---
class TransactionState {
public:
virtual ~TransactionState() = default;
virtual std::string toString() const = 0;
virtual std::string authorize(Transaction& tx) { return "Invalid state transition"; }
virtual std::string capture(Transaction& tx) { return "Invalid state transition"; }
virtual std::string refund(Transaction& tx) { return "Invalid state transition"; }
virtual std::string cancel(Transaction& tx) { return "Invalid state transition"; }
};
// --- Pattern: Chain of Responsibility (Проверки authorize) ---
class Handler {
protected:
std::shared_ptr<Handler> next;
public:
virtual ~Handler() = default;
void setNext(std::shared_ptr<Handler> n) { next = n; }
virtual std::string handle(Transaction& tx, Client& client) = 0;
};
// --- Предметная область: Transaction ---
class Transaction {
public:
std::string id;
std::string clientName;
int amount;
int riskScore;
int chargedTotal = 0;
std::shared_ptr<PaymentStrategy> strategy = nullptr;
std::shared_ptr<TransactionState> state;
Transaction(std::string id, std::string cn, int amt, int rs, std::shared_ptr<TransactionState> init)
: id(std::move(id)), clientName(std::move(cn)), amount(amt), riskScore(rs), state(init) {}
};
// Реализации состояний [cite: 44]
class CreatedState : public TransactionState {
public:
std::string toString() const override { return "Created"; }
std::string authorize(Transaction& tx) override; // Реализация ниже
std::string cancel(Transaction& tx) override; // Реализация ниже
};
class AuthorizedState : public TransactionState {
public:
std::string toString() const override { return "Authorized"; }
std::string capture(Transaction& tx) override;
std::string cancel(Transaction& tx) override;
};
class CapturedState : public TransactionState {
public:
std::string toString() const override { return "Captured"; }
std::string refund(Transaction& tx) override;
};
class RefundedState : public TransactionState {
public:
std::string toString() const override { return "Refunded"; }
};
class CancelledState : public TransactionState {
public:
std::string toString() const override { return "Cancelled"; }
};
// --- Конкретные обработчики Chain of Responsibility [cite: 46-48] ---
class StrategySelectedHandler : public Handler {
public:
std::string handle(Transaction& tx, Client& client) override {
if (!tx.strategy) return "Strategy not set";
return next ? next->handle(tx, client) : "";
}
};
class RiskCheckHandler : public Handler {
public:
std::string handle(Transaction& tx, Client& client) override {
if (tx.riskScore > 70) return "High risk transaction";
return next ? next->handle(tx, client) : "";
}
};
class FundsCheckHandler : public Handler {
public:
std::string handle(Transaction& tx, Client& client) override {
int total = tx.strategy->calculateTotal(tx.amount);
if (!tx.strategy->canPay(client, total)) return "Insufficient funds";
return next ? next->handle(tx, client) : "";
}
};
// Глобальное хранилище данных
std::map<std::string, Client> clients;
std::map<std::string, Transaction> transactions;
// Реализации переходов состояний (нужен доступ к хранилищу)
std::string CreatedState::authorize(Transaction& tx) {
auto it = clients.find(tx.clientName);
if (it == clients.end()) return "Client not found";
auto sH = std::make_shared<StrategySelectedHandler>();
auto rH = std::make_shared<RiskCheckHandler>();
auto fH = std::make_shared<FundsCheckHandler>();
sH->setNext(rH); rH->setNext(fH);
std::string result = sH->handle(tx, it->second);
if (result.empty()) {
tx.state = std::make_shared<AuthorizedState>();
return tx.id + " authorized";
}
return result;
}
std::string CreatedState::cancel(Transaction& tx) {
tx.state = std::make_shared<CancelledState>();
return tx.id + " cancelled";
}
std::string AuthorizedState::capture(Transaction& tx) {
auto& client = clients[tx.clientName];
int total = tx.strategy->calculateTotal(tx.amount);
tx.strategy->charge(client, total);
tx.chargedTotal = total;
tx.state = std::make_shared<CapturedState>();
return tx.id + " captured: " + std::to_string(total);
}
std::string AuthorizedState::cancel(Transaction& tx) {
tx.state = std::make_shared<CancelledState>();
return tx.id + " cancelled";
}
std::string CapturedState::refund(Transaction& tx) {
auto& client = clients[tx.clientName];
tx.strategy->refund(client, tx.chargedTotal);
tx.state = std::make_shared<RefundedState>();
return tx.id + " refunded: " + std::to_string(tx.chargedTotal);
}
// --- Движок обработки команд ---
void process() {
std::string line;
while (std::getline(std::cin, line) && !line.empty()) {
std::stringstream ss(line);
std::string cmd;
ss >> cmd;
std::vector<std::string> args;
std::string arg;
while (ss >> arg) args.push_back(arg);
if (cmd == "exit") {
if (!args.empty()) std::cout << "Invalid command" << std::endl;
else break;
continue;
}
if (cmd == "create_client") {
if (args.size() < 4) { std::cout << "Too few arguments" << std::endl; continue; }
if (args.size() > 4) { std::cout << "Too many arguments" << std::endl; continue; }
try {
std::string name = args[0];
int cb = std::stoi(args[1]), wb = std::stoi(args[2]), cl = std::stoi(args[3]);
if (cb < 0 || wb < 0 || cl < 0) throw std::exception();
if (clients.count(name)) std::cout << "Client already exists" << std::endl;
else {
clients.emplace(name, Client(name, cb, wb, cl));
std::cout << "Client " << name << " created" << std::endl;
}
} catch (...) { std::cout << "Invalid client parameters" << std::endl; }
}
else if (cmd == "create_tx") {
if (args.size() < 4) { std::cout << "Too few arguments" << std::endl; continue; }
if (args.size() > 4) { std::cout << "Too many arguments" << std::endl; continue; }
try {
std::string tid = args[0], cname = args[1];
int amt = std::stoi(args[2]), rs = std::stoi(args[3]);
if (amt <= 0 || rs < 0 || rs > 100) throw std::exception();
if (transactions.count(tid)) std::cout << "Transaction already exists" << std::endl;
else if (!clients.count(cname)) std::cout << "Client not found" << std::endl;
else {
transactions.emplace(tid, Transaction(tid, cname, amt, rs, std::make_shared<CreatedState>()));
std::cout << "Transaction " << tid << " created" << std::endl;
}
} catch (...) { std::cout << "Invalid transaction parameters" << std::endl; }
}
else if (cmd == "set_strategy") {
if (args.size() != 2) { std::cout << (args.size() < 2 ? "Too few arguments" : "Too many arguments") << std::endl; continue; }
if (!transactions.count(args[0])) { std::cout << "Transaction not found" << std::endl; continue; }
auto& tx = transactions.at(args[0]);
if (args[1] == "Card") tx.strategy = std::make_shared<CardStrategy>();
else if (args[1] == "Wallet") tx.strategy = std::make_shared<WalletStrategy>();
else if (args[1] == "Installments") tx.strategy = std::make_shared<InstallmentsStrategy>();
else { std::cout << "Invalid strategy" << std::endl; continue; }
std::cout << "Strategy " << args[1] << " set for " << tx.id << std::endl;
}
else if (cmd == "authorize") {
if (args.size() != 1) { std::cout << (args.empty() ? "Too few arguments" : "Too many arguments") << std::endl; continue; }
if (!transactions.count(args[0])) std::cout << "Transaction not found" << std::endl;
else std::cout << transactions.at(args[0]).state->authorize(transactions.at(args[0])) << std::endl;
}
else if (cmd == "capture") {
if (args.size() != 1) { std::cout << (args.empty() ? "Too few arguments" : "Too many arguments") << std::endl; continue; }
if (!transactions.count(args[0])) std::cout << "Transaction not found" << std::endl;
else std::cout << transactions.at(args[0]).state->capture(transactions.at(args[0])) << std::endl;
}
else if (cmd == "refund") {
if (args.size() != 1) { std::cout << (args.empty() ? "Too few arguments" : "Too many arguments") << std::endl; continue; }
if (!transactions.count(args[0])) std::cout << "Transaction not found" << std::endl;
else std::cout << transactions.at(args[0]).state->refund(transactions.at(args[0])) << std::endl;
}
else if (cmd == "cancel") {
if (args.size() != 1) { std::cout << (args.empty() ? "Too few arguments" : "Too many arguments") << std::endl; continue; }
if (!transactions.count(args[0])) std::cout << "Transaction not found" << std::endl;
else std::cout << transactions.at(args[0]).state->cancel(transactions.at(args[0])) << std::endl;
}
else if (cmd == "status") {
if (args.size() != 1) { std::cout << (args.empty() ? "Too few arguments" : "Too many arguments") << std::endl; continue; }
if (!transactions.count(args[0])) std::cout << "Transaction not found" << std::endl;
else std::cout << args[0] << " status: " << transactions.at(args[0]).state->toString() << std::endl;
}
else if (cmd == "balance") {
if (args.size() != 1) { std::cout << (args.empty() ? "Too few arguments" : "Too many arguments") << std::endl; continue; }
if (!clients.count(args[0])) std::cout << "Client not found" << std::endl;
else {
auto& c = clients.at(args[0]);
std::cout << c.name << " balances: card=" << c.cardBalance << " wallet=" << c.walletBalance << " credit=" << c.creditLimit << std::endl;
}
} else {
std::cout << "Invalid command" << std::endl;
}
}
}
int main() {
process();
return 0;
}