add compact tariff tests
This commit is contained in:
@@ -0,0 +1,726 @@
|
||||
#ifndef MOBILISIS_COMPACT_ENGINE_H
|
||||
#define MOBILISIS_COMPACT_ENGINE_H
|
||||
#include "compact_tariff.h"
|
||||
#include <QVector>
|
||||
#include <QSaveFile>
|
||||
#include <QCryptographicHash>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace Mobilisis {
|
||||
struct CompactChoice {
|
||||
qint64 price = 0;
|
||||
int minutes = 0;
|
||||
QDateTime end;
|
||||
};
|
||||
|
||||
class CompactEngine {
|
||||
public:
|
||||
CompactTariff tariff;
|
||||
QString error;
|
||||
QJsonObject sessionPlan;
|
||||
QString project;
|
||||
QJsonObject postpaid;
|
||||
QMap<QString, QVector<CompactChoice>> expanded;
|
||||
|
||||
|
||||
bool load(const QString &path)
|
||||
{
|
||||
if (!tariff.load(path, error))
|
||||
return false;
|
||||
QFile input(path);
|
||||
input.open(QIODevice::ReadOnly);
|
||||
const auto bytes = input.readAll();
|
||||
const auto root = QJsonDocument::fromJson(bytes).object();
|
||||
project = root.value("project").toString();
|
||||
postpaid = root.value("postpaid").toObject();
|
||||
expanded.clear();
|
||||
if (!validate())
|
||||
return false;
|
||||
const auto cacheSettings = root.value("calculation").toObject();
|
||||
if (cacheSettings.value("generatedRateStorage").toString("cache") == "cache") {
|
||||
QByteArray fingerprint = bytes + QByteArray("compact-engine-2");
|
||||
const auto holidayName = root.value("calendar").toObject().value("holidayFile").toString();
|
||||
if (!holidayName.isEmpty()) {
|
||||
QFile holidays(QFileInfo(path).dir().filePath(holidayName));
|
||||
if (!holidays.open(QIODevice::ReadOnly))
|
||||
return fail(holidays.errorString());
|
||||
fingerprint += holidays.readAll();
|
||||
}
|
||||
QJsonObject cache;
|
||||
cache.insert("inputHash", QString::fromLatin1(QCryptographicHash::hash(
|
||||
fingerprint, QCryptographicHash::Sha256).toHex()));
|
||||
const auto name = cacheSettings.value("cacheFile").toString("tariff-calculated.json");
|
||||
const auto cachePath = QFileInfo(path).dir().filePath(name);
|
||||
if (QFileInfo(cachePath).absoluteFilePath() == QFileInfo(path).absoluteFilePath() ||
|
||||
(!holidayName.isEmpty() && QFileInfo(cachePath).absoluteFilePath() ==
|
||||
QFileInfo(QFileInfo(path).dir().filePath(holidayName)).absoluteFilePath()))
|
||||
return fail("Cache must not overwrite tariff input");
|
||||
QFile previous(cachePath);
|
||||
QJsonObject old;
|
||||
if (previous.open(QIODevice::ReadOnly))
|
||||
old = QJsonDocument::fromJson(previous.readAll()).object();
|
||||
previous.close();
|
||||
if (old.value("inputHash") == cache.value("inputHash") && readCache(old))
|
||||
return true;
|
||||
if (!generateRates()) return false;
|
||||
QJsonObject cachePlans;
|
||||
for (auto it = expanded.cbegin(); it != expanded.cend(); ++it) {
|
||||
QJsonArray rows;
|
||||
for (const auto &choice : it.value()) {
|
||||
QJsonObject row;
|
||||
row.insert("priceMinor", double(choice.price));
|
||||
row.insert("durationMinutes", choice.minutes);
|
||||
rows.append(row);
|
||||
}
|
||||
cachePlans.insert(it.key(), rows);
|
||||
}
|
||||
cache.insert("ratePlans", cachePlans);
|
||||
if (old != cache) {
|
||||
QSaveFile output(cachePath);
|
||||
const auto payload = QJsonDocument(cache).toJson();
|
||||
if (!output.open(QIODevice::WriteOnly) ||
|
||||
output.write(payload) != payload.size() || !output.commit())
|
||||
return fail("Cannot atomically write compact tariff cache");
|
||||
}
|
||||
}
|
||||
if (expanded.isEmpty() && !generateRates()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool choices(const QString &productId, const QDateTime &sessionStart,
|
||||
QVector<CompactChoice> &result)
|
||||
{
|
||||
error.clear();
|
||||
result.clear();
|
||||
if (!sessionStart.isValid() || !tariff.products.contains(productId))
|
||||
return fail("Invalid session start or product");
|
||||
const auto start = tariff.localTime(sessionStart);
|
||||
QDateTime paidStart;
|
||||
QString period;
|
||||
if (!nextPaid(productId, start, paidStart, period))
|
||||
return false;
|
||||
QJsonObject today;
|
||||
if (!tariff.profileForDate(productId, start.date(), today, error))
|
||||
return false;
|
||||
bool inBreak = false;
|
||||
for (const auto &value : today.value("breaks").toArray()) {
|
||||
const auto range = value.toObject();
|
||||
inBreak |= start.time() >= QTime::fromString(range.value("from").toString(), "HH:mm") &&
|
||||
start.time() < QTime::fromString(range.value("to").toString(), "HH:mm");
|
||||
}
|
||||
if (paidStart > start && !inBreak &&
|
||||
today.value("outsidePeriods").toString() != "presale")
|
||||
return fail("Purchases outside paid periods are closed");
|
||||
|
||||
// Every later plan lookup uses the original session date for seasons.
|
||||
const auto plan = tariff.planForPeriod(productId, period, start);
|
||||
if (plan.isEmpty())
|
||||
return fail("No rate plan for paid period");
|
||||
sessionPlan = plan;
|
||||
QVector<CompactChoice> rows = expanded.value(plan.value("id").toString());
|
||||
const int productLimit = tariff.products.value(productId)
|
||||
.value("maximumStayMinutes").toInt(std::numeric_limits<int>::max());
|
||||
const auto cap = plan.value("priceCapTicket").toObject();
|
||||
const auto daily = plan.value("mode") == "daily" ? plan :
|
||||
tariff.plans.value(cap.value("ratePlanId").toString());
|
||||
// Different period plans may introduce price boundaries between the
|
||||
// starting plan's rows, so derive those choices from paid minutes.
|
||||
QStringList mappedPlans;
|
||||
const auto product = tariff.products.value(productId);
|
||||
for (const auto &value : product.value("ratePlansByPeriod").toObject())
|
||||
if (!mappedPlans.contains(value.toString())) mappedPlans.append(value.toString());
|
||||
for (const auto &season : product.value("seasonalRatePlansByPeriod").toObject())
|
||||
for (const auto &value : season.toObject())
|
||||
if (!mappedPlans.contains(value.toString())) mappedPlans.append(value.toString());
|
||||
if (mappedPlans.size() > 1 && plan.value("mode") != "daily") {
|
||||
QVector<CompactChoice> combined;
|
||||
const int limit = qMin(productLimit, plan.value("maximumTimeMinutes").toInt(1440));
|
||||
const int minimum = plan.value("minimumTimeMinutes").toInt(1);
|
||||
for (int minutes = minimum; minutes <= limit; ++minutes) {
|
||||
CompactChoice row;
|
||||
row.minutes = minutes;
|
||||
if (!expiry(productId, paidStart, minutes, plan.value("carryOver").toBool(), row.end))
|
||||
return false;
|
||||
if (!priceAcrossPeriods(productId, start, paidStart, row.end, row.price))
|
||||
return false;
|
||||
row.price = qMin(row.price, static_cast<qint64>(
|
||||
plan.value("maximumPriceMinor").toDouble(2147483647)));
|
||||
if (!combined.isEmpty() && combined.last().end == row.end) break;
|
||||
if (!combined.isEmpty() && combined.last().price == row.price)
|
||||
combined.last() = row;
|
||||
else combined.append(row);
|
||||
}
|
||||
rows = combined;
|
||||
}
|
||||
for (auto row : rows) {
|
||||
bool ticket = plan.value("mode") == "daily";
|
||||
ticket |= !cap.isEmpty() && row.price >= plan.value("maximumPriceMinor").toDouble();
|
||||
if (ticket) {
|
||||
if (cap.value("type") == "rolling_24h") {
|
||||
row.end = paidStart.addSecs(86400);
|
||||
row.minutes = 1440;
|
||||
result.append(row);
|
||||
} else {
|
||||
const auto stack = daily.value("stacking").toObject();
|
||||
const int days = stack.value("enabled").toBool()
|
||||
? stack.value("maximumDays").toInt(1) : 1;
|
||||
const qint64 dailyPrice = daily.value("dailyPriceMinor").toDouble();
|
||||
for (int count = 1; count <= days; ++count) {
|
||||
CompactChoice day = row;
|
||||
day.price += (count - 1) * dailyPrice;
|
||||
if (!dayEnd(productId, paidStart.date(), count, day.end))
|
||||
return false;
|
||||
day.minutes = count * 1440;
|
||||
result.append(day);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (row.minutes > productLimit)
|
||||
continue;
|
||||
if (!expiry(productId, paidStart, row.minutes, plan.value("carryOver").toBool(), row.end))
|
||||
return false;
|
||||
qint64 periodPrice = 0;
|
||||
if (!priceAcrossPeriods(productId, start, paidStart, row.end, periodPrice))
|
||||
return false;
|
||||
row.price = qMin(periodPrice, static_cast<qint64>(
|
||||
plan.value("maximumPriceMinor").toDouble(2147483647)));
|
||||
if (result.isEmpty() || result.last().end != row.end)
|
||||
result.append(row);
|
||||
}
|
||||
return !result.isEmpty() || fail("No purchasable tariff choices");
|
||||
}
|
||||
|
||||
// Resolve money separately from the +/- selection ladder. Never interpolate
|
||||
// wall-clock expiry times: unpaid calendar intervals must remain unpaid.
|
||||
bool paymentChoice(const QString &product, const QDateTime &start,
|
||||
const QVector<CompactChoice> &choices, qint64 amount,
|
||||
CompactChoice &choice, int &index, bool &dayTicket)
|
||||
{
|
||||
error.clear();
|
||||
choice = CompactChoice();
|
||||
index = -1;
|
||||
dayTicket = false;
|
||||
for (int i = 0; i < choices.size(); ++i)
|
||||
if (choices[i].price <= amount) index = i;
|
||||
if (index < 0) return fail("Payment below minimum ticket price");
|
||||
choice = choices[index];
|
||||
const auto mode = sessionPlan.value("mode").toString();
|
||||
const auto cap = sessionPlan.value("priceCapTicket").toObject();
|
||||
const qint64 capPrice = static_cast<qint64>(
|
||||
sessionPlan.value("maximumPriceMinor").toDouble(2147483647));
|
||||
dayTicket = mode == "daily" ||
|
||||
(cap.value("type") == "day_ticket" && choice.price >= capPrice);
|
||||
if (amount == choice.price || index + 1 >= choices.size() ||
|
||||
dayTicket || (mode != "fixed_steps" && mode != "linear")) return true;
|
||||
const auto upper = choices[index + 1];
|
||||
// A cap ticket is discrete; its synthetic duration is not a rate anchor.
|
||||
if (!cap.isEmpty() && upper.price >= capPrice) return true;
|
||||
if (upper.price <= choice.price || upper.minutes < choice.minutes)
|
||||
return fail("Invalid payment interpolation anchors");
|
||||
const qint64 span = upper.price - choice.price;
|
||||
const qint64 numerator = (amount - choice.price) *
|
||||
qint64(upper.minutes - choice.minutes);
|
||||
const int minutes = choice.minutes + int((numerator + span - 1) / span);
|
||||
QDateTime paidStart, end;
|
||||
QString period;
|
||||
if (!nextPaid(product, tariff.localTime(start), paidStart, period) ||
|
||||
!expiry(product, paidStart, minutes,
|
||||
sessionPlan.value("carryOver").toBool(), end)) return false;
|
||||
// Do not charge extra when the day-end cutoff grants no extra time.
|
||||
if (end <= choice.end) return true;
|
||||
choice.price = amount;
|
||||
choice.minutes = minutes;
|
||||
choice.end = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Actual elapsed interval. Free calendar periods never buy paid minutes.
|
||||
// Exit grace begins after successful payment and does not reduce this bill.
|
||||
bool quoteStay(const QString &product, const QDateTime &entry,
|
||||
const QDateTime &billingEnd, CompactChoice "e,
|
||||
qint64 &paidSeconds)
|
||||
{
|
||||
error.clear();
|
||||
quote = CompactChoice();
|
||||
paidSeconds = 0;
|
||||
if (!entry.isValid() || !billingEnd.isValid() || entry > billingEnd ||
|
||||
!tariff.products.contains(product)) return fail("Invalid entry/end time or product");
|
||||
const auto start = tariff.localTime(entry);
|
||||
const auto end = tariff.localTime(billingEnd);
|
||||
if (start.date().daysTo(end.date()) > 3660)
|
||||
return fail("Stay exceeds ten-year calculation horizon");
|
||||
const auto mode = postpaid.value("billingMode").toString("exact");
|
||||
const auto incrementValue = postpaid.value("moneyIncrementMinor");
|
||||
const double incrementNumber = incrementValue.isUndefined() ? 10 : incrementValue.toDouble(-1);
|
||||
const double grace = postpaid.value("exitGraceMinutes").toDouble(15);
|
||||
if ((mode != "exact" && mode != "started_hours") ||
|
||||
incrementNumber < 1 || incrementNumber > 2147483647 ||
|
||||
incrementNumber != std::floor(incrementNumber) ||
|
||||
grace < 0 || grace > 1440 || grace != std::floor(grace))
|
||||
return fail("Invalid postpaid billing mode, money increment or exit grace");
|
||||
const qint64 increment = qint64(incrementNumber);
|
||||
QString activeId;
|
||||
qint64 seconds = 0;
|
||||
long double total = 0;
|
||||
qint64 capBudget = 0;
|
||||
auto charge = [&]() {
|
||||
if (!seconds) return true;
|
||||
const auto plan = tariff.plans.value(activeId);
|
||||
const auto kind = plan.value("mode").toString();
|
||||
if (kind != "fixed_steps" && kind != "linear" && kind != "tiered")
|
||||
return fail("Postpaid currently supports fixed_steps, linear and tiered plans only");
|
||||
const auto rows = expanded.value(activeId);
|
||||
if (rows.isEmpty()) return fail("Missing expanded postpaid rate plan");
|
||||
const qint64 minutes = mode == "started_hours"
|
||||
? ((seconds + 3599) / 3600) * 60 : (seconds + 59) / 60;
|
||||
if (minutes > rows.last().minutes)
|
||||
return fail("Postpaid duration exceeds configured rate coverage");
|
||||
long double amount = 0;
|
||||
// Fixed-step prices are duration anchors; interpolate from zero.
|
||||
// Linear/tiered plans retain their configured started-block rules.
|
||||
if (kind == "fixed_steps") {
|
||||
qint64 previousPrice = 0;
|
||||
int previousMinutes = 0;
|
||||
for (const auto &row : rows) {
|
||||
if (row.minutes >= minutes) {
|
||||
if (row.minutes <= previousMinutes)
|
||||
return fail("Ambiguous fixed-step duration anchors");
|
||||
amount = previousPrice + (long double)(row.price - previousPrice) *
|
||||
(minutes - previousMinutes) / (row.minutes - previousMinutes);
|
||||
break;
|
||||
}
|
||||
previousPrice = row.price;
|
||||
previousMinutes = row.minutes;
|
||||
}
|
||||
} else if (kind == "linear" && mode == "exact") {
|
||||
const auto step = plan.value("step").toObject();
|
||||
const int duration = step.value("durationMinutes").toInt();
|
||||
const int every = step.value("priceIncreaseEverySteps").toInt(1);
|
||||
if (duration <= 0 || every <= 0) return fail("Invalid linear postpaid rate");
|
||||
const long double first = step.value("firstPriceMinor").toDouble();
|
||||
const long double increase = step.value("priceIncreaseMinor").toDouble();
|
||||
amount = minutes <= duration ? first * minutes / duration
|
||||
: first + increase * (minutes - duration) / (qint64(duration) * every);
|
||||
} else {
|
||||
for (const auto &row : rows) {
|
||||
if (row.minutes >= minutes) { amount = row.price; break; }
|
||||
}
|
||||
}
|
||||
amount = std::max(amount, (long double)plan.value("minimumPriceMinor").toDouble());
|
||||
amount = std::min(amount, (long double)plan.value("maximumPriceMinor").toDouble(2147483647));
|
||||
total += amount;
|
||||
capBudget += qint64(plan.value("maximumPriceMinor").toDouble(2147483647));
|
||||
return true;
|
||||
};
|
||||
// Accumulate consecutive use of a rate plan across breaks/closed days.
|
||||
// A rate-plan change starts a new billing segment; season stays at entry.
|
||||
for (QDate date = start.date(); date <= end.date(); date = date.addDays(1)) {
|
||||
QVector<QPair<QDateTime, QDateTime>> ranges;
|
||||
QStringList periods;
|
||||
if (!intervals(product, date, ranges, periods)) return false;
|
||||
for (int i = 0; i < ranges.size(); ++i) {
|
||||
const auto begin = qMax(start, ranges[i].first);
|
||||
const auto finish = qMin(end, ranges[i].second);
|
||||
if (finish <= begin) continue;
|
||||
const auto id = tariff.planForPeriod(product, periods[i], start).value("id").toString();
|
||||
if (id.isEmpty()) return fail("Missing postpaid period rate plan");
|
||||
if (!activeId.isEmpty() && id != activeId) {
|
||||
if (!charge()) return false;
|
||||
seconds = 0;
|
||||
}
|
||||
activeId = id;
|
||||
seconds += begin.secsTo(finish);
|
||||
paidSeconds += begin.secsTo(finish);
|
||||
}
|
||||
}
|
||||
if (!charge()) return false;
|
||||
const long double rounded = std::min((long double)capBudget,
|
||||
std::ceil(total / increment - 1e-12L) * increment);
|
||||
if (rounded > 2147483647) return fail("Postpaid price exceeds supported amount");
|
||||
quote.price = qint64(rounded);
|
||||
quote.minutes = int((paidSeconds + 59) / 60);
|
||||
quote.end = billingEnd;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool expand(const QJsonObject &plan, QVector<CompactChoice> &rows)
|
||||
{
|
||||
rows.clear();
|
||||
const auto mode = plan.value("mode").toString();
|
||||
for (auto it = plan.begin(); it != plan.end(); ++it) {
|
||||
if (it.key().endsWith("Minor") &&
|
||||
(!it.value().isDouble() || it.value().toDouble() < 0 ||
|
||||
it.value().toDouble() > 2147483647 ||
|
||||
it.value().toDouble() != std::floor(it.value().toDouble())))
|
||||
return fail("Prices must be nonnegative integer minor units");
|
||||
}
|
||||
const int maximum = plan.value("maximumTimeMinutes").toInt(1440);
|
||||
const int minimum = plan.value("minimumTimeMinutes").toInt(1);
|
||||
const qint64 cap = plan.value("maximumPriceMinor").toDouble(2147483647);
|
||||
if (maximum < minimum || maximum > 525600 || minimum < 1 || cap < 0)
|
||||
return fail("Invalid tariff duration or price limits");
|
||||
if (mode == "fixed_steps") {
|
||||
QMap<qint64, int> steps;
|
||||
for (const auto &value : plan.value("steps").toArray()) {
|
||||
const auto step = value.toObject();
|
||||
const double price = step.value("priceMinor").toDouble(-1);
|
||||
const double duration = step.value("durationMinutes").toDouble(-1);
|
||||
if (price < 0 || price != std::floor(price) || duration <= 0 ||
|
||||
duration > 525600 || steps.contains(static_cast<qint64>(price)))
|
||||
return fail("Invalid or duplicate preset step");
|
||||
steps.insert(static_cast<qint64>(price), static_cast<int>(std::ceil(duration)));
|
||||
}
|
||||
if (steps.isEmpty())
|
||||
return fail("fixed_steps needs steps");
|
||||
const auto presets = steps;
|
||||
const int count = plan.value("fillGaps").toObject().value("stepCount").toInt();
|
||||
if (count < 0 || count > 100000)
|
||||
return fail("Invalid gap-fill step count");
|
||||
if (count >= 2 && steps.size() >= 2 &&
|
||||
(steps.lastKey() - steps.firstKey()) % (count - 1) == 0) {
|
||||
const qint64 firstPrice = steps.firstKey();
|
||||
const qint64 priceStep = (steps.lastKey() - firstPrice) / (count - 1);
|
||||
const int firstTime = steps.first();
|
||||
const int timeSpan = steps.last() - firstTime;
|
||||
for (int i = 1; i < count - 1; ++i) {
|
||||
const qint64 price = firstPrice + i * priceStep;
|
||||
if (!presets.contains(price))
|
||||
steps[price] = firstTime + static_cast<int>(std::ceil(double(timeSpan) * i / (count - 1)));
|
||||
}
|
||||
}
|
||||
int previous = 0;
|
||||
for (auto it = steps.cbegin(); it != steps.cend(); ++it) {
|
||||
if (it.value() < previous)
|
||||
return fail("Step durations must increase with price");
|
||||
previous = it.value();
|
||||
if (it.value() >= minimum && it.value() <= maximum && it.key() <= cap) {
|
||||
CompactChoice choice;
|
||||
choice.price = it.key();
|
||||
choice.minutes = it.value();
|
||||
rows.append(choice);
|
||||
}
|
||||
}
|
||||
} else if (mode == "fixed_price" || mode == "daily") {
|
||||
CompactChoice choice;
|
||||
choice.price = plan.value(mode == "daily" ? "dailyPriceMinor" : "fixedPriceMinor").toDouble(-1);
|
||||
choice.minutes = mode == "daily" ? 1440 : plan.value("fixedDurationMinutes").toInt();
|
||||
if (choice.price < 0 || choice.minutes <= 0)
|
||||
return fail("Invalid fixed ticket");
|
||||
rows.append(choice);
|
||||
} else if (mode == "linear" || mode == "tiered") {
|
||||
for (int minutes = minimum; minutes <= maximum; ++minutes) {
|
||||
CompactChoice choice;
|
||||
choice.minutes = minutes;
|
||||
if (mode == "linear") {
|
||||
const auto step = plan.value("step").toObject();
|
||||
const int duration = step.value("durationMinutes").toInt();
|
||||
const int every = step.value("priceIncreaseEverySteps").toInt(1);
|
||||
if (duration <= 0 || every <= 0 ||
|
||||
step.value("firstPriceMinor").toDouble(-1) < 0 ||
|
||||
step.value("priceIncreaseMinor").toDouble(-1) < 0)
|
||||
return fail("Invalid linear step");
|
||||
choice.price = step.value("firstPriceMinor").toDouble() +
|
||||
((minutes - 1) / duration / every) * static_cast<qint64>(step.value("priceIncreaseMinor").toDouble());
|
||||
} else {
|
||||
int remaining = qMax(0, minutes - plan.value("freeMinutes").toInt());
|
||||
const auto tiers = plan.value("tiers").toArray();
|
||||
for (int i = 0; i < tiers.size() && remaining > 0; ++i) {
|
||||
const auto tier = tiers.at(i).toObject();
|
||||
const int duration = tier.value("durationMinutes").toInt();
|
||||
const qint64 price = tier.value("priceMinor").toDouble(-1);
|
||||
if (duration <= 0 || price < 0)
|
||||
return fail("Invalid tier");
|
||||
const bool repeat = tier.value("repeat").toBool();
|
||||
if (repeat && i != tiers.size() - 1)
|
||||
return fail("Only the last tier may repeat");
|
||||
const int blocks = repeat ? (remaining + duration - 1) / duration : 1;
|
||||
choice.price += price * blocks;
|
||||
remaining -= duration * blocks;
|
||||
}
|
||||
if (remaining > 0)
|
||||
break;
|
||||
}
|
||||
choice.price = qMin(cap, qMax(choice.price, static_cast<qint64>(plan.value("minimumPriceMinor").toDouble())));
|
||||
if (choice.price < 0)
|
||||
return fail("Negative tariff price");
|
||||
if (!rows.isEmpty() && rows.last().price == choice.price)
|
||||
rows.last().minutes = minutes;
|
||||
else
|
||||
rows.append(choice);
|
||||
}
|
||||
} else {
|
||||
return fail("Unknown pricing mode");
|
||||
}
|
||||
return !rows.isEmpty() || fail("Rate plan has no selectable prices");
|
||||
}
|
||||
|
||||
private:
|
||||
bool generateRates()
|
||||
{
|
||||
expanded.clear();
|
||||
for (const auto &plan : tariff.plans) {
|
||||
QVector<CompactChoice> rows;
|
||||
if (!expand(plan, rows)) return false;
|
||||
expanded.insert(plan.value("id").toString(), rows);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool readCache(const QJsonObject &cache)
|
||||
{
|
||||
const auto plans = cache.value("ratePlans").toObject();
|
||||
if (plans.size() != tariff.plans.size()) return false;
|
||||
QMap<QString, QVector<CompactChoice>> candidate;
|
||||
for (auto it = tariff.plans.cbegin(); it != tariff.plans.cend(); ++it) {
|
||||
const auto rows = plans.value(it.key()).toArray();
|
||||
if (rows.isEmpty()) return false;
|
||||
QVector<CompactChoice> parsed;
|
||||
for (const auto &value : rows) {
|
||||
const auto row = value.toObject();
|
||||
const double price = row.value("priceMinor").toDouble(-1);
|
||||
const double minutes = row.value("durationMinutes").toDouble(-1);
|
||||
if (price < 0 || price > 2147483647 || price != std::floor(price) ||
|
||||
minutes < 1 || minutes > 525600 || minutes != std::floor(minutes))
|
||||
return false;
|
||||
CompactChoice choice;
|
||||
choice.price = static_cast<qint64>(price);
|
||||
choice.minutes = static_cast<int>(minutes);
|
||||
if (!parsed.isEmpty() && (parsed.last().price > choice.price ||
|
||||
parsed.last().minutes > choice.minutes)) return false;
|
||||
parsed.append(choice);
|
||||
}
|
||||
candidate.insert(it.key(), parsed);
|
||||
}
|
||||
expanded = candidate;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Accumulate paid seconds under each consecutive plan. A break or a
|
||||
// closed day with the same plan does not restart its tier progression.
|
||||
bool priceAcrossPeriods(const QString &product, const QDateTime &seasonStart,
|
||||
const QDateTime &start, const QDateTime &end, qint64 &price)
|
||||
{
|
||||
price = 0;
|
||||
QString activePlan;
|
||||
qint64 activeSeconds = 0;
|
||||
auto charge = [&]() {
|
||||
if (activeSeconds == 0) return true;
|
||||
const auto rows = expanded.value(activePlan);
|
||||
const qint64 minutes = (activeSeconds + 59) / 60;
|
||||
for (const auto &row : rows) {
|
||||
if (row.minutes >= minutes) {
|
||||
price += row.price;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return fail("Period duration exceeds its rate plan");
|
||||
};
|
||||
for (QDate date = start.date(); date <= end.date(); date = date.addDays(1)) {
|
||||
QVector<QPair<QDateTime, QDateTime>> ranges;
|
||||
QStringList periods;
|
||||
if (!intervals(product, date, ranges, periods)) return false;
|
||||
for (int i = 0; i < ranges.size(); ++i) {
|
||||
const auto begin = qMax(start, ranges[i].first);
|
||||
const auto finish = qMin(end, ranges[i].second);
|
||||
if (begin >= finish) continue;
|
||||
const auto plan = tariff.planForPeriod(product, periods[i], seasonStart);
|
||||
const auto id = plan.value("id").toString();
|
||||
if (id.isEmpty()) return fail("Missing period rate plan");
|
||||
if (!activePlan.isEmpty() && activePlan != id) {
|
||||
if (!charge()) return false;
|
||||
activeSeconds = 0;
|
||||
}
|
||||
activePlan = id;
|
||||
activeSeconds += begin.secsTo(finish);
|
||||
}
|
||||
}
|
||||
return charge();
|
||||
}
|
||||
|
||||
bool fail(const QString &message) { error = message; return false; }
|
||||
bool validate()
|
||||
{
|
||||
QStringList seasonIds;
|
||||
QMap<QString, QString> dates;
|
||||
for (const auto &value : tariff.seasons) {
|
||||
const auto season = value.toObject();
|
||||
const auto id = season.value("id").toString();
|
||||
const auto first = season.value("from").toString();
|
||||
const auto last = season.value("to").toString();
|
||||
if (id.isEmpty() || seasonIds.contains(id) ||
|
||||
!QDate::fromString("2000-" + first, Qt::ISODate).isValid() ||
|
||||
!QDate::fromString("2000-" + last, Qt::ISODate).isValid())
|
||||
return fail("Invalid or duplicate season");
|
||||
seasonIds.append(id);
|
||||
for (QDate date(2000, 1, 1); date.year() == 2000; date = date.addDays(1)) {
|
||||
const auto day = date.toString("MM-dd");
|
||||
const bool inside = first <= last ? first <= day && day <= last
|
||||
: first <= day || day <= last;
|
||||
if (inside && dates.contains(day)) return fail("Overlapping seasons");
|
||||
if (inside) dates[day] = id;
|
||||
}
|
||||
}
|
||||
for (const auto &product : tariff.products) {
|
||||
const auto overrides = product.value("seasonalRatePlansByPeriod").toObject();
|
||||
for (auto it = overrides.begin(); it != overrides.end(); ++it) {
|
||||
if (!seasonIds.contains(it.key())) return fail("Unknown seasonal override");
|
||||
}
|
||||
}
|
||||
for (const auto &profile : tariff.profiles) {
|
||||
QTime previous;
|
||||
QStringList ids;
|
||||
for (const auto &value : profile.value("periods").toArray()) {
|
||||
const auto period = value.toObject();
|
||||
const auto from = QTime::fromString(period.value("from").toString(), "HH:mm");
|
||||
const auto to = QTime::fromString(period.value("to").toString(), "HH:mm");
|
||||
const auto id = period.value("id").toString();
|
||||
if (!from.isValid() || !to.isValid() || from >= to ||
|
||||
(previous.isValid() && from < previous) || id.isEmpty() || ids.contains(id))
|
||||
return fail("Paid periods must be ordered, distinct, and within one day");
|
||||
previous = to;
|
||||
ids.append(id);
|
||||
}
|
||||
previous = QTime();
|
||||
for (const auto &value : profile.value("breaks").toArray()) {
|
||||
const auto pause = value.toObject();
|
||||
const auto from = QTime::fromString(pause.value("from").toString(), "HH:mm");
|
||||
const auto to = QTime::fromString(pause.value("to").toString(), "HH:mm");
|
||||
if (!from.isValid() || !to.isValid() || from >= to ||
|
||||
(previous.isValid() && from < previous))
|
||||
return fail("Breaks must be ordered and non-overlapping");
|
||||
previous = to;
|
||||
}
|
||||
const auto outside = profile.value("outsidePeriods").toString("closed");
|
||||
if (outside != "closed" && outside != "presale") return fail("Unknown outsidePeriods");
|
||||
}
|
||||
for (const auto &plan : tariff.plans) {
|
||||
const auto cap = plan.value("priceCapTicket").toObject();
|
||||
const auto type = cap.value("type").toString();
|
||||
if (!cap.isEmpty()) {
|
||||
if (!plan.contains("maximumPriceMinor")) return fail("Cap ticket requires maximumPriceMinor");
|
||||
if (type == "rolling_24h") {
|
||||
if (!plan.value("carryOver").toBool()) return fail("24-hour cap requires carryOver");
|
||||
} else if (type == "day_ticket") {
|
||||
const auto target = tariff.plans.value(cap.value("ratePlanId").toString());
|
||||
if (target.value("mode") != "daily") return fail("Day-ticket cap requires a daily plan");
|
||||
} else return fail("Unknown cap ticket type");
|
||||
}
|
||||
const auto stack = plan.value("stacking").toObject();
|
||||
if (!stack.isEmpty() && (plan.value("mode") != "daily" ||
|
||||
stack.value("maximumDays").toInt(1) < 1 || stack.value("maximumDays").toInt(1) > 366))
|
||||
return fail("Invalid day-ticket stacking");
|
||||
if (plan.value("mode") == "tiered" &&
|
||||
plan.value("billing").toString("per_started_tier") != "per_started_tier")
|
||||
return fail("Unsupported tier billing");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool intervals(const QString &product, const QDate &date,
|
||||
QVector<QPair<QDateTime, QDateTime>> &ranges, QStringList &periods)
|
||||
{
|
||||
ranges.clear();
|
||||
periods.clear();
|
||||
QJsonObject profile;
|
||||
if (!tariff.profileForDate(product, date, profile, error))
|
||||
return false;
|
||||
for (const auto &value : profile.value("periods").toArray()) {
|
||||
const auto period = value.toObject();
|
||||
const QTime from = QTime::fromString(period.value("from").toString(), "HH:mm");
|
||||
const QTime to = QTime::fromString(period.value("to").toString(), "HH:mm");
|
||||
if (!from.isValid() || !to.isValid() || from >= to)
|
||||
return fail("Invalid or overnight paid period");
|
||||
QVector<QPair<QTime, QTime>> segments;
|
||||
segments.append(qMakePair(from, to));
|
||||
for (const auto &breakValue : profile.value("breaks").toArray()) {
|
||||
const auto pause = breakValue.toObject();
|
||||
const auto begin = QTime::fromString(pause.value("from").toString(), "HH:mm");
|
||||
const auto end = QTime::fromString(pause.value("to").toString(), "HH:mm");
|
||||
if (!begin.isValid() || !end.isValid() || begin >= end)
|
||||
return fail("Invalid break");
|
||||
QVector<QPair<QTime, QTime>> next;
|
||||
for (const auto &segment : segments) {
|
||||
if (begin >= segment.second || end <= segment.first) {
|
||||
next.append(segment);
|
||||
continue;
|
||||
}
|
||||
if (begin > segment.first) next.append(qMakePair(segment.first, begin));
|
||||
if (end < segment.second) next.append(qMakePair(end, segment.second));
|
||||
}
|
||||
segments = next;
|
||||
}
|
||||
for (const auto &segment : segments) {
|
||||
ranges.append(qMakePair(QDateTime(date, segment.first, Qt::LocalTime),
|
||||
QDateTime(date, segment.second, Qt::LocalTime)));
|
||||
periods.append(period.value("id").toString());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool nextPaid(const QString &product, const QDateTime &start,
|
||||
QDateTime &paidStart, QString &period)
|
||||
{
|
||||
for (int day = 0; day < 3660; ++day) {
|
||||
QVector<QPair<QDateTime, QDateTime>> ranges;
|
||||
QStringList periods;
|
||||
if (!intervals(product, start.date().addDays(day), ranges, periods)) return false;
|
||||
for (int i = 0; i < ranges.size(); ++i) {
|
||||
if (ranges[i].second > start) {
|
||||
paidStart = qMax(start, ranges[i].first);
|
||||
period = periods[i];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return fail("No paid period within ten years");
|
||||
}
|
||||
|
||||
bool expiry(const QString &product, const QDateTime &start, int minutes,
|
||||
bool carry, QDateTime &end)
|
||||
{
|
||||
qint64 remaining = qint64(minutes) * 60;
|
||||
for (int day = 0; day < 3660; ++day) {
|
||||
QVector<QPair<QDateTime, QDateTime>> ranges;
|
||||
QStringList periods;
|
||||
if (!intervals(product, start.date().addDays(day), ranges, periods)) return false;
|
||||
for (const auto &range : ranges) {
|
||||
const auto begin = qMax(start, range.first);
|
||||
if (begin >= range.second) continue;
|
||||
const auto available = begin.secsTo(range.second);
|
||||
if (remaining <= available) {
|
||||
end = begin.addSecs(remaining);
|
||||
return true;
|
||||
}
|
||||
remaining -= available;
|
||||
end = range.second;
|
||||
}
|
||||
if (!carry) return end.isValid();
|
||||
}
|
||||
return fail("Requested duration exceeds calendar horizon");
|
||||
}
|
||||
|
||||
bool dayEnd(const QString &product, QDate date, int count, QDateTime &end)
|
||||
{
|
||||
for (int day = 0; day < 3660; ++day, date = date.addDays(1)) {
|
||||
QVector<QPair<QDateTime, QDateTime>> ranges;
|
||||
QStringList periods;
|
||||
if (!intervals(product, date, ranges, periods)) return false;
|
||||
if (!ranges.isEmpty() && --count == 0) {
|
||||
QJsonObject profile;
|
||||
if (!tariff.profileForDate(product, date, profile, error)) return false;
|
||||
const auto periods = profile.value("periods").toArray();
|
||||
const auto last = periods.last().toObject();
|
||||
end = QDateTime(date, QTime::fromString(last.value("to").toString(), "HH:mm"), Qt::LocalTime);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return fail("Cannot resolve stacked day-ticket expiry");
|
||||
}
|
||||
};
|
||||
}
|
||||
#endif
|
||||
Reference in New Issue
Block a user