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