#include #include #include void from_json(const json &j, order &order) { j.at("name").get_to(order.name); j.at("address").get_to(order.address); j.at("phone").get_to(order.phone); j.at("email").get_to(order.email); j.at("id").get_to(order.id); } void to_json(nlohmann::json &j, const order &order) { j = json{{"name", order.name}, {"address", order.address}, {"phone", order.phone}, {"email", order.email}, {"id", order.id}}; } void orders::load() { try { json j; std::fstream f(get_path()); f >> j; j.get_to(data); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } } void orders::sort() { // std::cout << "sorting..." << std::endl; // std::vector vec; // vec.reserve(data.size()); // for (auto &el : *this) { // vec.push_back(el); // } // std::stable_sort(vec.begin(), vec.end(), [](const auto &a, const auto &b) { // int aid = a["id"]; // int bid = b["id"]; // if (aid > bid) { // return 1; // } // if (aid < bid) { // return -1; // } // return 0; // }); // clear(); // for (const auto &json : vec) { // push_back(json); // } } const fs::path &orders::get_path() { static fs::path orders_json; if (orders_json.empty()) orders_json = data_directory.get_path() / "orders.json"; return orders_json; } orders::orders(const with_data_directory &dir) : data_directory(dir) { if (fs::exists(get_path())) { load(); } else { write(); } } void orders::write() { try { std::ofstream of(get_path()); json j{data}; of << j; } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } } orders::~orders() { write(); } auto max_element( json::iterator begin, json::iterator end, std::function cmp) { auto largest = begin; if (begin == end) return end; for (; begin != end; begin++) if (cmp(largest, begin)) largest = begin; return largest; } void orders::push(json data) { // int id = 0; // if (size() > 0) { // const auto res = // max_element(begin(), end(), [](const json &a, const json &b) { // std::cout << "max_element " << a["id"] << b["id"] << std::endl; // std::cout << a["id"] << std::endl; // std::cout << b["id"] << std::endl; // return a["id"] < b["id"]; // }); // id = (*res)["id"]; // } // std::cout << "--\n" << id << std::endl; // data["id"] = id + 1; // std::cout << data["id"] << std::endl; order o; data["id"] = 0; data.get_to(o); std::cout << data << std::endl; data.push_back(o); }