]> git.stg.codes - stg.git/blob - projects/sgconf/tariffs.cpp
c384df1fa639bb280d949ae099c11df70ce56b36
[stg.git] / projects / sgconf / tariffs.cpp
1 #include "tariffs.h"
2
3 #include "api_action.h"
4 #include "options.h"
5 #include "config.h"
6 #include "utils.h"
7
8 #include "stg/servconf.h"
9 #include "stg/servconf_types.h"
10 #include "stg/tariff_conf.h"
11 #include "stg/common.h"
12 #include "stg/os_int.h"
13
14 #include <iostream>
15 #include <algorithm>
16 #include <sstream>
17 #include <string>
18 #include <map>
19 #include <cassert>
20
21 namespace
22 {
23
24 std::string Indent(size_t level, bool dash = false)
25 {
26 if (level == 0)
27     return "";
28 return dash ? std::string(level * 4 - 2, ' ') + "- " : std::string(level * 4, ' ');
29 }
30
31 std::string ChangePolicyToString(TARIFF::CHANGE_POLICY changePolicy)
32 {
33 switch (changePolicy)
34     {
35     case TARIFF::ALLOW: return "allow";
36     case TARIFF::TO_CHEAP: return "to_cheap";
37     case TARIFF::TO_EXPENSIVE: return "to_expensive";
38     case TARIFF::DENY: return "deny";
39     }
40 return "unknown";
41 }
42
43 std::string PeriodToString(TARIFF::PERIOD period)
44 {
45 switch (period)
46     {
47     case TARIFF::DAY:
48         return "daily";
49     case TARIFF::MONTH:
50         return "monthly";
51     }
52 return "unknown";
53 }
54
55 std::string TraffTypeToString(TARIFF::TRAFF_TYPE traffType)
56 {
57 switch (traffType)
58     {
59     case TARIFF::TRAFF_UP:
60         return "upload";
61     case TARIFF::TRAFF_DOWN:
62         return "download";
63     case TARIFF::TRAFF_UP_DOWN:
64         return "upload + download";
65     case TARIFF::TRAFF_MAX:
66         return "max(upload, download)";
67     }
68 return "unknown";
69 }
70
71 void ConvPeriod(const std::string & value, RESETABLE<TARIFF::PERIOD> & res)
72 {
73 std::string lowered = ToLower(value);
74 if (lowered == "daily")
75     res = TARIFF::DAY;
76 else if (lowered == "monthly")
77     res = TARIFF::MONTH;
78 else
79     throw SGCONF::ACTION::ERROR("Period should be 'daily' or 'monthly'. Got: '" + value + "'");
80 }
81
82 void ConvChangePolicy(const std::string & value, RESETABLE<TARIFF::CHANGE_POLICY> & res)
83 {
84 std::string lowered = ToLower(value);
85 if (lowered == "allow")
86     res = TARIFF::ALLOW;
87 else if (lowered == "to_cheap")
88     res = TARIFF::TO_CHEAP;
89 else if (lowered == "to_expensive")
90     res = TARIFF::TO_EXPENSIVE;
91 else if (lowered == "deny")
92     res = TARIFF::DENY;
93 else
94     throw SGCONF::ACTION::ERROR("Change policy should be 'allow', 'to_cheap', 'to_expensive' or 'deny'. Got: '" + value + "'");
95 }
96
97 void ConvTraffType(const std::string & value, RESETABLE<TARIFF::TRAFF_TYPE> & res)
98 {
99 std::string lowered = ToLower(value);
100 lowered.erase(std::remove(lowered.begin(), lowered.end(), ' '), lowered.end());
101 if (lowered == "upload")
102     res = TARIFF::TRAFF_UP;
103 else if (lowered == "download")
104     res = TARIFF::TRAFF_DOWN;
105 else if (lowered == "upload+download")
106     res = TARIFF::TRAFF_UP_DOWN;
107 else if (lowered.substr(0, 3) == "max")
108     res = TARIFF::TRAFF_MAX;
109 else
110     throw SGCONF::ACTION::ERROR("Traff type should be 'upload', 'download', 'upload + download' or 'max'. Got: '" + value + "'");
111 }
112
113 DIRPRICE_DATA_RES ConvTimeSpan(const std::string & value)
114 {
115 size_t dashPos = value.find_first_of('-');
116 if (dashPos == std::string::npos)
117     throw SGCONF::ACTION::ERROR("Time span should be in format 'hh:mm-hh:mm'. Got: '" + value + "'");
118 size_t fromColon = value.find_first_of(':');
119 if (fromColon == std::string::npos || fromColon > dashPos)
120     throw SGCONF::ACTION::ERROR("Time span should be in format 'hh:mm-hh:mm'. Got: '" + value + "'");
121 size_t toColon = value.find_first_of(':', dashPos);
122 if (toColon == std::string::npos)
123     throw SGCONF::ACTION::ERROR("Time span should be in format 'hh:mm-hh:mm'. Got: '" + value + "'");
124 DIRPRICE_DATA_RES res;
125 res.hDay = FromString<int>(value.substr(0, fromColon));
126 if (res.hDay.data() < 0 || res.hDay.data() > 23)
127     throw SGCONF::ACTION::ERROR("Invalid 'from' hours. Got: '" + value.substr(0, fromColon) + "'");
128 res.mDay = FromString<int>(value.substr(fromColon + 1, dashPos - fromColon - 1));
129 if (res.mDay.data() < 0 || res.mDay.data() > 59)
130     throw SGCONF::ACTION::ERROR("Invalid 'from' minutes. Got: '" + value.substr(fromColon + 1, dashPos - fromColon - 1) + "'");
131 res.hNight = FromString<int>(value.substr(dashPos + 1, toColon - dashPos - 1));
132 if (res.hNight.data() < 0 || res.hNight.data() > 23)
133     throw SGCONF::ACTION::ERROR("Invalid 'to' hours. Got: '" + value.substr(dashPos + 1, toColon - dashPos - 1) + "'");
134 res.mNight = FromString<int>(value.substr(toColon + 1, value.length() - toColon));
135 if (res.mNight.data() < 0 || res.mNight.data() > 59)
136     throw SGCONF::ACTION::ERROR("Invalid 'to' minutes. Got: '" + value.substr(toColon + 1, value.length() - toColon) + "'");
137 return res;
138 }
139
140 void Splice(std::vector<DIRPRICE_DATA_RES> & lhs, const std::vector<DIRPRICE_DATA_RES> & rhs)
141 {
142 for (size_t i = 0; i < lhs.size() && i < rhs.size(); ++i)
143     lhs[i].Splice(rhs[i]);
144 }
145
146 void ConvTimes(std::string value, std::vector<DIRPRICE_DATA_RES> & res)
147 {
148 value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
149 Splice(res, Split<std::vector<DIRPRICE_DATA_RES> >(value, ',', ConvTimeSpan));
150 }
151
152 struct ConvPrice : public std::unary_function<std::string, DIRPRICE_DATA_RES>
153 {
154     typedef RESETABLE<double> (DIRPRICE_DATA_RES::* MemPtr);
155     ConvPrice(MemPtr before, MemPtr after)
156         : m_before(before), m_after(after)
157     {}
158
159     DIRPRICE_DATA_RES operator()(const std::string & value)
160     {
161     DIRPRICE_DATA_RES res;
162     size_t slashPos = value.find_first_of('/');
163     if (slashPos == std::string::npos)
164         {
165         double price = 0;
166         if (str2x(value, price) < 0)
167             throw SGCONF::ACTION::ERROR("Price should be a floating point number. Got: '" + value + "'");
168         (res.*m_before) = (res.*m_after) = price;
169         res.noDiscount = true;
170         }
171     else
172         {
173         double price = 0;
174         if (str2x(value.substr(0, slashPos), price) < 0)
175             throw SGCONF::ACTION::ERROR("Price should be a floating point number. Got: '" + value.substr(0, slashPos) + "'");
176         (res.*m_before) = price;
177         if (str2x(value.substr(slashPos + 1, value.length() - slashPos), price) < 0)
178             throw SGCONF::ACTION::ERROR("Price should be a floating point number. Got: '" + value.substr(slashPos + 1, value.length() - slashPos) + "'");
179         (res.*m_after) = price;
180         res.noDiscount = false;
181         }
182     return res;
183     }
184
185     MemPtr m_before;
186     MemPtr m_after;
187 };
188
189 void ConvDayPrices(std::string value, std::vector<DIRPRICE_DATA_RES> & res)
190 {
191 value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
192 Splice(res, Split<std::vector<DIRPRICE_DATA_RES> >(value, ',', ConvPrice(&DIRPRICE_DATA_RES::priceDayA, &DIRPRICE_DATA_RES::priceDayB)));
193 }
194
195 void ConvNightPrices(std::string value, std::vector<DIRPRICE_DATA_RES> & res)
196 {
197 value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
198 Splice(res, Split<std::vector<DIRPRICE_DATA_RES> >(value, ',', ConvPrice(&DIRPRICE_DATA_RES::priceNightA, &DIRPRICE_DATA_RES::priceNightB)));
199 }
200
201 DIRPRICE_DATA_RES ConvThreshold(std::string value)
202 {
203 DIRPRICE_DATA_RES res;
204 double threshold = 0;
205 if (str2x(value, threshold) < 0)
206     throw SGCONF::ACTION::ERROR("Threshold should be a floating point value. Got: '" + value + "'");
207 res.threshold = threshold;
208 return res;
209 }
210
211 void ConvThresholds(std::string value, std::vector<DIRPRICE_DATA_RES> & res)
212 {
213 value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
214 Splice(res, Split<std::vector<DIRPRICE_DATA_RES> >(value, ',', ConvThreshold));
215 }
216
217 std::string TimeToString(int h, int m)
218 {
219 std::ostringstream stream;
220 stream << (h < 10 ? "0" : "") << h << ":"
221        << (m < 10 ? "0" : "") << m;
222 return stream.str();
223 }
224
225 void PrintDirPriceData(size_t dir, const DIRPRICE_DATA & data, size_t level)
226 {
227 std::string night = TimeToString(data.hNight, data.mNight);
228 std::string day = TimeToString(data.hDay, data.mDay);
229 std::cout << Indent(level, true) << "dir: " << dir << "\n"
230           << Indent(level)       << "'" << night << "' - '" << day << "': " << data.priceDayA << "/" << data.priceDayB << "\n"
231           << Indent(level)       << "'" << day << "' - '" << night << "': " << data.priceNightA << "/" << data.priceNightB << "\n"
232           << Indent(level)       << "threshold: " << data.threshold << "\n"
233           << Indent(level)       << "single price: " << (data.singlePrice ? "yes" : "no") << "\n"
234           << Indent(level)       << "discount: " << (data.noDiscount ? "no" : "yes") << "\n"; // Attention!
235 }
236
237 void PrintTariffConf(const TARIFF_CONF & conf, size_t level)
238 {
239 std::cout << Indent(level, true) << "name: " << conf.name << "\n"
240           << Indent(level)       << "fee: " << conf.fee << "\n"
241           << Indent(level)       << "free mb: " << conf.free << "\n"
242           << Indent(level)       << "passive cost: " << conf.passiveCost << "\n"
243           << Indent(level)       << "traff type: " << TraffTypeToString(conf.traffType) << "\n"
244           << Indent(level)       << "period: " << PeriodToString(conf.period) << "\n"
245           << Indent(level)       << "change policy: " << ChangePolicyToString(conf.changePolicy) << "\n";
246 }
247
248 void PrintTariff(const STG::GET_TARIFF::INFO & info, size_t level = 0)
249 {
250 PrintTariffConf(info.tariffConf, level);
251 std::cout << Indent(level) << "dir prices:\n";
252 for (size_t i = 0; i < info.dirPrice.size(); ++i)
253     PrintDirPriceData(i, info.dirPrice[i], level + 1);
254 }
255
256 std::vector<SGCONF::API_ACTION::PARAM> GetTariffParams()
257 {
258 std::vector<SGCONF::API_ACTION::PARAM> params;
259 params.push_back(SGCONF::API_ACTION::PARAM("fee", "<fee>", "\t\ttariff fee"));
260 params.push_back(SGCONF::API_ACTION::PARAM("free", "<free mb>", "\tprepaid traffic"));
261 params.push_back(SGCONF::API_ACTION::PARAM("passive-cost", "<cost>", "\tpassive cost"));
262 params.push_back(SGCONF::API_ACTION::PARAM("traff-type", "<type>", "\ttraffic type (up, down, up+down, max)"));
263 params.push_back(SGCONF::API_ACTION::PARAM("period", "<period>", "\ttarification period (daily, monthly)"));
264 params.push_back(SGCONF::API_ACTION::PARAM("change-policy", "<policy>", "tariff change policy (allow, to_cheap, to_expensive, deny)"));
265 params.push_back(SGCONF::API_ACTION::PARAM("times", "<hh:mm-hh:mm, ...>", "coma-separated day time-spans for each direction"));
266 params.push_back(SGCONF::API_ACTION::PARAM("day-prices", "<price/price, ...>", "coma-separated day prices for each direction"));
267 params.push_back(SGCONF::API_ACTION::PARAM("night-prices", "<price/price, ...>", "coma-separated night prices for each direction"));
268 params.push_back(SGCONF::API_ACTION::PARAM("thresholds", "<threshold, ...>", "coma-separated thresholds for each direction"));
269 return params;
270 }
271
272 void SimpleCallback(bool result,
273                     const std::string & reason,
274                     void * /*data*/)
275 {
276 if (!result)
277     {
278     std::cerr << "Operation failed. Reason: '" << reason << "'." << std::endl;
279     return;
280     }
281 std::cout << "Success.\n";
282 }
283
284 void GetTariffsCallback(bool result,
285                         const std::string & reason,
286                         const std::vector<STG::GET_TARIFF::INFO> & info,
287                         void * /*data*/)
288 {
289 if (!result)
290     {
291     std::cerr << "Failed to get tariff list. Reason: '" << reason << "'." << std::endl;
292     return;
293     }
294 std::cout << "Tariffs:\n";
295 for (size_t i = 0; i < info.size(); ++i)
296     PrintTariff(info[i], 1);
297 }
298
299 void GetTariffCallback(bool result,
300                        const std::string & reason,
301                        const std::vector<STG::GET_TARIFF::INFO> & info,
302                        void * data)
303 {
304 assert(data != NULL && "Expecting pointer to std::string with the tariff's name.");
305 const std::string & name = *static_cast<const std::string *>(data);
306 if (!result)
307     {
308     std::cerr << "Failed to get tariff. Reason: '" << reason << "'." << std::endl;
309     return;
310     }
311 for (size_t i = 0; i < info.size(); ++i)
312     if (info[i].tariffConf.name == name)
313         PrintTariff(info[i]);
314 }
315
316 bool GetTariffsFunction(const SGCONF::CONFIG & config,
317                         const std::string & /*arg*/,
318                         const std::map<std::string, std::string> & /*options*/)
319 {
320 STG::SERVCONF proto(config.server.data(),
321                     config.port.data(),
322                     config.localAddress.data(),
323                     config.localPort.data(),
324                     config.userName.data(),
325                     config.userPass.data());
326 return proto.GetTariffs(GetTariffsCallback, NULL) == STG::st_ok;
327 }
328
329 bool GetTariffFunction(const SGCONF::CONFIG & config,
330                        const std::string & arg,
331                        const std::map<std::string, std::string> & /*options*/)
332 {
333 STG::SERVCONF proto(config.server.data(),
334                     config.port.data(),
335                     config.localAddress.data(),
336                     config.localPort.data(),
337                     config.userName.data(),
338                     config.userPass.data());
339 // STG currently doesn't support <GetTariff name="..."/>.
340 // So get a list of tariffs and filter it. 'data' param holds a pointer to 'name'.
341 std::string name(arg);
342 return proto.GetTariffs(GetTariffCallback, &name) == STG::st_ok;
343 }
344
345 bool DelTariffFunction(const SGCONF::CONFIG & config,
346                        const std::string & arg,
347                        const std::map<std::string, std::string> & /*options*/)
348 {
349 STG::SERVCONF proto(config.server.data(),
350                     config.port.data(),
351                     config.localAddress.data(),
352                     config.localPort.data(),
353                     config.userName.data(),
354                     config.userPass.data());
355 return proto.DelTariff(arg, SimpleCallback, NULL) == STG::st_ok;
356 }
357
358 bool AddTariffFunction(const SGCONF::CONFIG & config,
359                        const std::string & arg,
360                        const std::map<std::string, std::string> & options)
361 {
362 TARIFF_DATA_RES conf;
363 conf.tariffConf.name = arg;
364 SGCONF::MaybeSet(options, "fee", conf.tariffConf.fee);
365 SGCONF::MaybeSet(options, "free", conf.tariffConf.free);
366 SGCONF::MaybeSet(options, "passive-cost", conf.tariffConf.passiveCost);
367 SGCONF::MaybeSet(options, "traff-type", conf.tariffConf.traffType, ConvTraffType);
368 SGCONF::MaybeSet(options, "period", conf.tariffConf.period, ConvPeriod);
369 SGCONF::MaybeSet(options, "change-policy", conf.tariffConf.changePolicy, ConvChangePolicy);
370 SGCONF::MaybeSet(options, "times", conf.dirPrice, ConvTimes);
371 SGCONF::MaybeSet(options, "day-prices", conf.dirPrice, ConvDayPrices);
372 SGCONF::MaybeSet(options, "night-prices", conf.dirPrice, ConvNightPrices);
373 SGCONF::MaybeSet(options, "thresholds", conf.dirPrice, ConvThresholds);
374 for (size_t i = 0; i < conf.dirPrice.size(); ++i)
375     {
376     if (!conf.dirPrice[i].priceDayA.empty() &&
377         !conf.dirPrice[i].priceNightA.empty() &&
378         !conf.dirPrice[i].priceDayB.empty() &&
379         !conf.dirPrice[i].priceNightB.empty())
380         conf.dirPrice[i].singlePrice = conf.dirPrice[i].priceDayA.data() == conf.dirPrice[i].priceNightA.data() &&
381                                        conf.dirPrice[i].priceDayB.data() == conf.dirPrice[i].priceNightB.data();
382     }
383 STG::SERVCONF proto(config.server.data(),
384                     config.port.data(),
385                     config.localAddress.data(),
386                     config.localPort.data(),
387                     config.userName.data(),
388                     config.userPass.data());
389 return proto.AddTariff(arg, conf, SimpleCallback, NULL) == STG::st_ok;
390 }
391
392 bool ChgTariffFunction(const SGCONF::CONFIG & config,
393                        const std::string & arg,
394                        const std::map<std::string, std::string> & options)
395 {
396 TARIFF_DATA_RES conf;
397 conf.tariffConf.name = arg;
398 SGCONF::MaybeSet(options, "fee", conf.tariffConf.fee);
399 SGCONF::MaybeSet(options, "free", conf.tariffConf.free);
400 SGCONF::MaybeSet(options, "passive-cost", conf.tariffConf.passiveCost);
401 SGCONF::MaybeSet(options, "traff-type", conf.tariffConf.traffType, ConvTraffType);
402 SGCONF::MaybeSet(options, "period", conf.tariffConf.period, ConvPeriod);
403 SGCONF::MaybeSet(options, "change-policy", conf.tariffConf.changePolicy, ConvChangePolicy);
404 SGCONF::MaybeSet(options, "times", conf.dirPrice, ConvTimes);
405 SGCONF::MaybeSet(options, "day-prices", conf.dirPrice, ConvDayPrices);
406 SGCONF::MaybeSet(options, "night-prices", conf.dirPrice, ConvNightPrices);
407 SGCONF::MaybeSet(options, "thresholds", conf.dirPrice, ConvThresholds);
408 for (size_t i = 0; i < conf.dirPrice.size(); ++i)
409     {
410     if (!conf.dirPrice[i].priceDayA.empty() &&
411         !conf.dirPrice[i].priceNightA.empty() &&
412         !conf.dirPrice[i].priceDayB.empty() &&
413         !conf.dirPrice[i].priceNightB.empty())
414         conf.dirPrice[i].singlePrice = conf.dirPrice[i].priceDayA.data() == conf.dirPrice[i].priceNightA.data() &&
415                                        conf.dirPrice[i].priceDayB.data() == conf.dirPrice[i].priceNightB.data();
416     }
417 STG::SERVCONF proto(config.server.data(),
418                     config.port.data(),
419                     config.localAddress.data(),
420                     config.localPort.data(),
421                     config.userName.data(),
422                     config.userPass.data());
423 return proto.ChgTariff(conf, SimpleCallback, NULL) == STG::st_ok;
424 }
425
426 } // namespace anonymous
427
428 void SGCONF::AppendTariffsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks)
429 {
430 std::vector<API_ACTION::PARAM> params(GetTariffParams());
431 blocks.Add("Tariff management options")
432       .Add("get-tariffs", SGCONF::MakeAPIAction(commands, GetTariffsFunction), "\tget tariff list")
433       .Add("get-tariff", SGCONF::MakeAPIAction(commands, "<name>", GetTariffFunction), "get tariff")
434       .Add("add-tariff", SGCONF::MakeAPIAction(commands, "<name>", params, AddTariffFunction), "add tariff")
435       .Add("del-tariff", SGCONF::MakeAPIAction(commands, "<name>", DelTariffFunction), "delete tariff")
436       .Add("chg-tariff", SGCONF::MakeAPIAction(commands, "<name>", params, ChgTariffFunction), "change tariff");
437 }