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