]> git.stg.codes - stg.git/blob - projects/sgconf/tariffs.cpp
c0d30a125e186b58767746e9df355d2c7c7418a0
[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           << Indent(level)       << "change policy timeout: " << formatTime(conf.changePolicyTimeout) << "\n";
247 }
248
249 void PrintTariff(const STG::GET_TARIFF::INFO & info, size_t level = 0)
250 {
251 PrintTariffConf(info.tariffConf, level);
252 std::cout << Indent(level) << "dir prices:\n";
253 for (size_t i = 0; i < info.dirPrice.size(); ++i)
254     PrintDirPriceData(i, info.dirPrice[i], level + 1);
255 }
256
257 std::vector<SGCONF::API_ACTION::PARAM> GetTariffParams()
258 {
259 std::vector<SGCONF::API_ACTION::PARAM> params;
260 params.push_back(SGCONF::API_ACTION::PARAM("fee", "<fee>", "\t\ttariff fee"));
261 params.push_back(SGCONF::API_ACTION::PARAM("free", "<free mb>", "\tprepaid traffic"));
262 params.push_back(SGCONF::API_ACTION::PARAM("passive-cost", "<cost>", "\tpassive cost"));
263 params.push_back(SGCONF::API_ACTION::PARAM("traff-type", "<type>", "\ttraffic type (up, down, up+down, max)"));
264 params.push_back(SGCONF::API_ACTION::PARAM("period", "<period>", "\ttarification period (daily, monthly)"));
265 params.push_back(SGCONF::API_ACTION::PARAM("change-policy", "<policy>", "tariff change policy (allow, to_cheap, to_expensive, deny)"));
266 params.push_back(SGCONF::API_ACTION::PARAM("change-policy-timeout", "<yyyy-mm-dd hh:mm:ss>", "tariff change policy timeout"));
267 params.push_back(SGCONF::API_ACTION::PARAM("times", "<hh:mm-hh:mm, ...>", "coma-separated day time-spans for each direction"));
268 params.push_back(SGCONF::API_ACTION::PARAM("day-prices", "<price/price, ...>", "coma-separated day prices for each direction"));
269 params.push_back(SGCONF::API_ACTION::PARAM("night-prices", "<price/price, ...>", "coma-separated night prices for each direction"));
270 params.push_back(SGCONF::API_ACTION::PARAM("thresholds", "<threshold, ...>", "coma-separated thresholds for each direction"));
271 return params;
272 }
273
274 void SimpleCallback(bool result,
275                     const std::string & reason,
276                     void * /*data*/)
277 {
278 if (!result)
279     {
280     std::cerr << "Operation failed. Reason: '" << reason << "'." << std::endl;
281     return;
282     }
283 std::cout << "Success.\n";
284 }
285
286 void GetTariffsCallback(bool result,
287                         const std::string & reason,
288                         const std::vector<STG::GET_TARIFF::INFO> & info,
289                         void * /*data*/)
290 {
291 if (!result)
292     {
293     std::cerr << "Failed to get tariff list. Reason: '" << reason << "'." << std::endl;
294     return;
295     }
296 std::cout << "Tariffs:\n";
297 for (size_t i = 0; i < info.size(); ++i)
298     PrintTariff(info[i], 1);
299 }
300
301 void GetTariffCallback(bool result,
302                        const std::string & reason,
303                        const std::vector<STG::GET_TARIFF::INFO> & info,
304                        void * data)
305 {
306 assert(data != NULL && "Expecting pointer to std::string with the tariff's name.");
307 const std::string & name = *static_cast<const std::string *>(data);
308 if (!result)
309     {
310     std::cerr << "Failed to get tariff. Reason: '" << reason << "'." << std::endl;
311     return;
312     }
313 for (size_t i = 0; i < info.size(); ++i)
314     if (info[i].tariffConf.name == name)
315         PrintTariff(info[i]);
316 }
317
318 bool GetTariffsFunction(const SGCONF::CONFIG & config,
319                         const std::string & /*arg*/,
320                         const std::map<std::string, std::string> & /*options*/)
321 {
322 STG::SERVCONF proto(config.server.data(),
323                     config.port.data(),
324                     config.localAddress.data(),
325                     config.localPort.data(),
326                     config.userName.data(),
327                     config.userPass.data());
328 return proto.GetTariffs(GetTariffsCallback, NULL) == STG::st_ok;
329 }
330
331 bool GetTariffFunction(const SGCONF::CONFIG & config,
332                        const std::string & arg,
333                        const std::map<std::string, std::string> & /*options*/)
334 {
335 STG::SERVCONF proto(config.server.data(),
336                     config.port.data(),
337                     config.localAddress.data(),
338                     config.localPort.data(),
339                     config.userName.data(),
340                     config.userPass.data());
341 // STG currently doesn't support <GetTariff name="..."/>.
342 // So get a list of tariffs and filter it. 'data' param holds a pointer to 'name'.
343 std::string name(arg);
344 return proto.GetTariffs(GetTariffCallback, &name) == STG::st_ok;
345 }
346
347 bool DelTariffFunction(const SGCONF::CONFIG & config,
348                        const std::string & arg,
349                        const std::map<std::string, std::string> & /*options*/)
350 {
351 STG::SERVCONF proto(config.server.data(),
352                     config.port.data(),
353                     config.localAddress.data(),
354                     config.localPort.data(),
355                     config.userName.data(),
356                     config.userPass.data());
357 return proto.DelTariff(arg, SimpleCallback, NULL) == STG::st_ok;
358 }
359
360 bool AddTariffFunction(const SGCONF::CONFIG & config,
361                        const std::string & arg,
362                        const std::map<std::string, std::string> & options)
363 {
364 TARIFF_DATA_RES conf;
365 conf.tariffConf.name = arg;
366 SGCONF::MaybeSet(options, "fee", conf.tariffConf.fee);
367 SGCONF::MaybeSet(options, "free", conf.tariffConf.free);
368 SGCONF::MaybeSet(options, "passive-cost", conf.tariffConf.passiveCost);
369 SGCONF::MaybeSet(options, "traff-type", conf.tariffConf.traffType, ConvTraffType);
370 SGCONF::MaybeSet(options, "period", conf.tariffConf.period, ConvPeriod);
371 SGCONF::MaybeSet(options, "change-policy", conf.tariffConf.changePolicy, ConvChangePolicy);
372 SGCONF::MaybeSet(options, "change-policy-timeout", conf.tariffConf.changePolicyTimeout, readTime(conf.tariffConf.changePolicyTimeout));
373 SGCONF::MaybeSet(options, "times", conf.dirPrice, ConvTimes);
374 SGCONF::MaybeSet(options, "day-prices", conf.dirPrice, ConvDayPrices);
375 SGCONF::MaybeSet(options, "night-prices", conf.dirPrice, ConvNightPrices);
376 SGCONF::MaybeSet(options, "thresholds", conf.dirPrice, ConvThresholds);
377 for (size_t i = 0; i < conf.dirPrice.size(); ++i)
378     {
379     if (!conf.dirPrice[i].priceDayA.empty() &&
380         !conf.dirPrice[i].priceNightA.empty() &&
381         !conf.dirPrice[i].priceDayB.empty() &&
382         !conf.dirPrice[i].priceNightB.empty())
383         conf.dirPrice[i].singlePrice = conf.dirPrice[i].priceDayA.data() == conf.dirPrice[i].priceNightA.data() &&
384                                        conf.dirPrice[i].priceDayB.data() == conf.dirPrice[i].priceNightB.data();
385     }
386 STG::SERVCONF proto(config.server.data(),
387                     config.port.data(),
388                     config.localAddress.data(),
389                     config.localPort.data(),
390                     config.userName.data(),
391                     config.userPass.data());
392 return proto.AddTariff(arg, conf, SimpleCallback, NULL) == STG::st_ok;
393 }
394
395 bool ChgTariffFunction(const SGCONF::CONFIG & config,
396                        const std::string & arg,
397                        const std::map<std::string, std::string> & options)
398 {
399 TARIFF_DATA_RES conf;
400 conf.tariffConf.name = arg;
401 SGCONF::MaybeSet(options, "fee", conf.tariffConf.fee);
402 SGCONF::MaybeSet(options, "free", conf.tariffConf.free);
403 SGCONF::MaybeSet(options, "passive-cost", conf.tariffConf.passiveCost);
404 SGCONF::MaybeSet(options, "traff-type", conf.tariffConf.traffType, ConvTraffType);
405 SGCONF::MaybeSet(options, "period", conf.tariffConf.period, ConvPeriod);
406 SGCONF::MaybeSet(options, "change-policy", conf.tariffConf.changePolicy, ConvChangePolicy);
407 SGCONF::MaybeSet(options, "change-policy-timeout", conf.tariffConf.changePolicyTimeout, readTime(conf.tariffConf.changePolicyTimeout));
408 SGCONF::MaybeSet(options, "times", conf.dirPrice, ConvTimes);
409 SGCONF::MaybeSet(options, "day-prices", conf.dirPrice, ConvDayPrices);
410 SGCONF::MaybeSet(options, "night-prices", conf.dirPrice, ConvNightPrices);
411 SGCONF::MaybeSet(options, "thresholds", conf.dirPrice, ConvThresholds);
412 for (size_t i = 0; i < conf.dirPrice.size(); ++i)
413     {
414     if (!conf.dirPrice[i].priceDayA.empty() &&
415         !conf.dirPrice[i].priceNightA.empty() &&
416         !conf.dirPrice[i].priceDayB.empty() &&
417         !conf.dirPrice[i].priceNightB.empty())
418         conf.dirPrice[i].singlePrice = conf.dirPrice[i].priceDayA.data() == conf.dirPrice[i].priceNightA.data() &&
419                                        conf.dirPrice[i].priceDayB.data() == conf.dirPrice[i].priceNightB.data();
420     }
421 STG::SERVCONF proto(config.server.data(),
422                     config.port.data(),
423                     config.localAddress.data(),
424                     config.localPort.data(),
425                     config.userName.data(),
426                     config.userPass.data());
427 return proto.ChgTariff(conf, SimpleCallback, NULL) == STG::st_ok;
428 }
429
430 } // namespace anonymous
431
432 void SGCONF::AppendTariffsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks)
433 {
434 std::vector<API_ACTION::PARAM> params(GetTariffParams());
435 blocks.Add("Tariff management options")
436       .Add("get-tariffs", SGCONF::MakeAPIAction(commands, GetTariffsFunction), "\tget tariff list")
437       .Add("get-tariff", SGCONF::MakeAPIAction(commands, "<name>", GetTariffFunction), "get tariff")
438       .Add("add-tariff", SGCONF::MakeAPIAction(commands, "<name>", params, AddTariffFunction), "add tariff")
439       .Add("del-tariff", SGCONF::MakeAPIAction(commands, "<name>", DelTariffFunction), "delete tariff")
440       .Add("chg-tariff", SGCONF::MakeAPIAction(commands, "<name>", params, ChgTariffFunction), "change tariff");
441 }