Repository navigation
Expand file tree
/
Copy pathOrderEngine.h
More file actions
73 lines (61 loc) · 2.31 KB
/
Copy pathOrderEngine.h
File metadata and controls
73 lines (61 loc) · 2.31 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
#ifndef ORDER_ENGINE_H
#define ORDER_ENGINE_H
#include <iostream>
#include <string>
#include <vector>
#include <mutex>
#include <fstream>
struct Product {
int product_id;
std::string name;
int stock_count;
double price;
};
struct Order {
int order_id;
int user_id;
int product_id;
std::string status;
};
class ConcurrentOrderProcessor {
private:
std::vector<Product> inventory;
std::vector<Order> order_history;
std::mutex inventory_mutex;
int next_order_id = 1;
public:
void add_product(int id, std::string name, int stock, double price) {
inventory.push_back({id, name, stock, price});
}
bool process_checkout(int user_id, int product_id) {
std::lock_guard<std::mutex> lock(inventory_mutex);
std::ofstream log_file("orders_log.txt", std::ios::app);
for (size_t i = 0; i < inventory.size(); ++i) {
if (inventory[i].product_id == product_id) {
if (inventory[i].stock_count > 0) {
inventory[i].stock_count--;
order_history.push_back({next_order_id++, user_id, product_id, "SUCCESS"});
std::cout << "[SUCCESS] Order #" << (next_order_id - 1)
<< ": User " << user_id << " bought " << inventory[i].name << std::endl;
if (log_file.is_open()) {
log_file << "ORDER_ID: " << (next_order_id - 1)
<< " | USER_ID: " << user_id
<< " | STATUS: SUCCESS | ITEM: " << inventory[i].name << "\n";
}
return true;
} else {
order_history.push_back({next_order_id++, user_id, product_id, "FAILED_OUT_OF_STOCK"});
std::cout << "[REJECTED] User " << user_id << ": Item Sold Out!" << std::endl;
if (log_file.is_open()) {
log_file << "ORDER_ID: " << (next_order_id - 1)
<< " | USER_ID: " << user_id
<< " | STATUS: FAILED_OUT_OF_STOCK\n";
}
return false;
}
}
}
return false;
}
};
#endif