From c4ad676b86389491230d5866fd39940dfd603632 Mon Sep 17 00:00:00 2001 From: Siegfried Siegert Date: Wed, 2 Dec 2026 11:02:15 +0100 Subject: [PATCH] add compact tariff tests --- library/include/mobilisis/compact_api.h | 15 + library/include/mobilisis/compact_calendar.h | 191 +++++ library/include/mobilisis/compact_engine.h | 726 +++++++++++++++++++ library/include/mobilisis/compact_tariff.h | 179 +++++ library/src/compact_api.cpp | 23 + tests/compact/compact.pro | 7 + tests/compact/compact_checks.cpp | 90 +++ tests/postpaid/postpaid.pro | 7 + tests/postpaid/postpaid_checks.cpp | 50 ++ 9 files changed, 1288 insertions(+) create mode 100644 library/include/mobilisis/compact_api.h create mode 100644 library/include/mobilisis/compact_calendar.h create mode 100644 library/include/mobilisis/compact_engine.h create mode 100644 library/include/mobilisis/compact_tariff.h create mode 100644 library/src/compact_api.cpp create mode 100644 tests/compact/compact.pro create mode 100644 tests/compact/compact_checks.cpp create mode 100644 tests/postpaid/postpaid.pro create mode 100644 tests/postpaid/postpaid_checks.cpp diff --git a/library/include/mobilisis/compact_api.h b/library/include/mobilisis/compact_api.h new file mode 100644 index 0000000..8b83ac4 --- /dev/null +++ b/library/include/mobilisis/compact_api.h @@ -0,0 +1,15 @@ +#ifndef MOBILISIS_COMPACT_API_H +#define MOBILISIS_COMPACT_API_H +#include "calculate_price.h" +#include "compact_engine.h" +namespace Mobilisis { +CALCULATE_LIBRARY_API bool compactStayQuote(CompactEngine &engine, const QString &product, + const QDateTime &entry, const QDateTime &end, CompactChoice "e, qint64 &paidSeconds); +CALCULATE_LIBRARY_API bool loadCompactTariff(CompactEngine &engine, const QString &path); +CALCULATE_LIBRARY_API bool compactTicketChoices(CompactEngine &engine, const QString &product, + const QDateTime &start, QVector &choices); +CALCULATE_LIBRARY_API bool compactPaymentChoice(CompactEngine &engine, const QString &product, + const QDateTime &start, const QVector &choices, qint64 amount, + CompactChoice &choice, int &index, bool &dayTicket); +} +#endif diff --git a/library/include/mobilisis/compact_calendar.h b/library/include/mobilisis/compact_calendar.h new file mode 100644 index 0000000..3271d7d --- /dev/null +++ b/library/include/mobilisis/compact_calendar.h @@ -0,0 +1,191 @@ +#ifndef MOBILISIS_COMPACT_CALENDAR_H +#define MOBILISIS_COMPACT_CALENDAR_H + +#include +#include +#include +#include +#include +#include +#include + +namespace Mobilisis { + +// Date-level profile selection. The caller resolves the weekday when the +// returned profile is empty, and handles paid periods within that profile. +class CompactCalendar { +public: + bool load(const QString &path, const QString &defaultProfile, + const QStringList &profiles, QString &error) + { + QFile file(path); + if (!file.open(QIODevice::ReadOnly)) { + error = file.errorString(); + return false; + } + + QJsonParseError parseError; + const auto document = QJsonDocument::fromJson(file.readAll(), &parseError); + const auto root = document.object(); + if (parseError.error != QJsonParseError::NoError || + root.value("schemaVersion").toDouble() != 1 || + !root.value("holidays").isArray() || + (root.contains("exceptions") && !root.value("exceptions").isArray())) { + error = QStringLiteral("Invalid compact holiday file: %1").arg(path); + return false; + } + + CompactCalendar candidate; + for (const auto &entry : root.value("holidays").toArray()) { + const auto rule = entry.toObject(); + const auto profile = rule.contains("workingDayProfileId") + ? rule.value("workingDayProfileId").toString() : defaultProfile; + if (!profiles.contains(profile) || !validRule(rule)) { + error = QStringLiteral("Invalid holiday rule in %1").arg(path); + return false; + } + candidate.rules.append(rule); + candidate.ruleProfiles.append(profile); + } + + for (const auto &entry : root.value("exceptions").toArray()) { + const auto exception = entry.toObject(); + const auto date = parseDate(exception.value("date").toString()); + const auto profile = exception.value("workingDayProfileId").toString(); + if (!date.isValid() || !profiles.contains(profile) || + candidate.exceptions.contains(date)) { + error = QStringLiteral("Invalid or duplicate workday exception in %1").arg(path); + return false; + } + candidate.exceptions.insert(date, profile); + } + + *this = candidate; + error.clear(); + return true; + } + + bool resolve(const QDate &date, QString &profile, QString &error) const + { + profile.clear(); + error.clear(); + if (!date.isValid()) { + error = QStringLiteral("Invalid parking date"); + return false; + } + const auto exception = exceptions.constFind(date); + if (exception != exceptions.constEnd()) { + profile = exception.value(); + return true; + } + + for (int i = 0; i < rules.size(); ++i) { + if (!matches(rules.at(i).toObject(), date)) + continue; + if (!profile.isEmpty()) { + profile.clear(); + error = QStringLiteral("Overlapping holiday rules on %1").arg(date.toString(Qt::ISODate)); + return false; + } + profile = ruleProfiles.at(i); + } + return true; + } + +private: + static QDate parseDate(const QString &value) + { + const auto date = QDate::fromString(value, Qt::ISODate); + return date.isValid() && date.toString(Qt::ISODate) == value ? date : QDate(); + } + + static int weekday(const QJsonObject &rule) + { + const QStringList days = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"}; + return days.indexOf(rule.value("weekday").toString()) + 1; + } + + static bool integerInRange(const QJsonValue &value, int min, int max) + { + const double number = value.toDouble(max + 1); + return number >= min && number <= max && number == static_cast(number); + } + + static bool validRule(const QJsonObject &rule) + { + const auto type = rule.value("type").toString(); + if (type == "annual_fixed" || type == "once") { + const auto dates = rule.value(type == "once" ? "dates" : "monthDays").toArray(); + QStringList seen; + for (const auto &value : dates) { + const auto date = value.toString(); + if (seen.contains(date) || + !parseDate(type == "once" ? date : QStringLiteral("2000-") + date).isValid()) + return false; + seen.append(date); + } + return !dates.isEmpty(); + } + if (type != "annual_rule") + return false; + if (rule.value("rule") == "easter_offset") { + const auto offsets = rule.value("days").toArray(); + QList seen; + for (const auto &offset : offsets) { + if (!integerInRange(offset, -366, 366) || seen.contains(offset.toInt())) + return false; + seen.append(offset.toInt()); + } + return !offsets.isEmpty(); + } + const auto occurrence = rule.value("occurrence"); + return rule.value("rule") == "nth_weekday_of_month" && weekday(rule) > 0 && + integerInRange(rule.value("month"), 1, 12) && + (occurrence.toDouble() == -1 || integerInRange(occurrence, 1, 5)); + } + + static QDate easterSunday(int year) + { + const int golden = year % 19; + const int century = year / 100; + const int remainder = year % 100; + const int correction = (century - (century + 8) / 25 + 1) / 3; + const int epact = (19 * golden + century - century / 4 - correction + 15) % 30; + const int weekdayOffset = (32 + 2 * (century % 4) + 2 * (remainder / 4) + - epact - remainder % 4) % 7; + const int adjustment = (golden + 11 * epact + 22 * weekdayOffset) / 451; + const int dayIndex = epact + weekdayOffset - 7 * adjustment + 114; + return QDate(year, dayIndex / 31, dayIndex % 31 + 1); + } + + static bool matches(const QJsonObject &rule, const QDate &date) + { + const auto type = rule.value("type").toString(); + if (type == "once") + return rule.value("dates").toArray().contains(QJsonValue(date.toString(Qt::ISODate))); + if (type == "annual_fixed") + return rule.value("monthDays").toArray().contains(QJsonValue(date.toString("MM-dd"))); + if (rule.value("rule") == "easter_offset") { + for (const auto &offset : rule.value("days").toArray()) { + for (int year = date.year() - 1; year <= date.year() + 1; ++year) { + if (easterSunday(year).addDays(offset.toInt()) == date) + return true; + } + } + return false; + } + if (date.month() != rule.value("month").toInt() || date.dayOfWeek() != weekday(rule)) + return false; + const int occurrence = rule.value("occurrence").toInt(); + return occurrence == -1 ? date.day() + 7 > date.daysInMonth() + : (date.day() - 1) / 7 + 1 == occurrence; + } + + QJsonArray rules; + QStringList ruleProfiles; + QHash exceptions; +}; + +} // namespace Mobilisis + +#endif diff --git a/library/include/mobilisis/compact_engine.h b/library/include/mobilisis/compact_engine.h new file mode 100644 index 0000000..6b5aeda --- /dev/null +++ b/library/include/mobilisis/compact_engine.h @@ -0,0 +1,726 @@ +#ifndef MOBILISIS_COMPACT_ENGINE_H +#define MOBILISIS_COMPACT_ENGINE_H +#include "compact_tariff.h" +#include +#include +#include +#include +#include +#include + +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> 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 &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 rows = expanded.value(plan.value("id").toString()); + const int productLimit = tariff.products.value(productId) + .value("maximumStayMinutes").toInt(std::numeric_limits::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 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( + 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( + 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 &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( + 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> 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 &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 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(price))) + return fail("Invalid or duplicate preset step"); + steps.insert(static_cast(price), static_cast(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(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(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(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 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> 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 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(price); + choice.minutes = static_cast(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> 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 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> &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> 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> 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> 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> 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> 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 diff --git a/library/include/mobilisis/compact_tariff.h b/library/include/mobilisis/compact_tariff.h new file mode 100644 index 0000000..4974be6 --- /dev/null +++ b/library/include/mobilisis/compact_tariff.h @@ -0,0 +1,179 @@ +#ifndef MOBILISIS_COMPACT_TARIFF_H +#define MOBILISIS_COMPACT_TARIFF_H + +#include "compact_calendar.h" +#include +#include +#include +#include + +namespace Mobilisis { + +class CompactTariff { +public: + bool load(const QString &path, QString &error) + { + QFile file(path); + if (!file.open(QIODevice::ReadOnly)) { + error = file.errorString(); + return false; + } + + QJsonParseError parseError; + const auto root = QJsonDocument::fromJson(file.readAll(), &parseError).object(); + if (parseError.error != QJsonParseError::NoError || + root.value("schemaVersion").toDouble() != 2) { + error = QStringLiteral("Expected compact tariff schemaVersion 2"); + return false; + } + + CompactTariff next; + if (!index(root.value("products"), next.products) || + !index(root.value("ratePlans"), next.plans) || + !index(root.value("workingDayProfiles"), next.profiles)) { + error = QStringLiteral("Missing, empty or duplicate compact tariff IDs"); + return false; + } + next.seasons = root.value("seasons").toArray(); + + const auto settings = root.value("calendar").toObject(); + // Tariff calendars always follow the machine's local clock. + // Ignore timezone fields retained in older compact tariff files. + + for (const auto &product : next.products) { + for (const auto &id : product.value("workingDayProfileIds").toArray()) { + if (!next.profiles.contains(id.toString())) { + error = QStringLiteral("Unknown product working-day profile: %1").arg(id.toString()); + return false; + } + } + if (product.contains("holidayProfileId") && + !next.profiles.contains(product.value("holidayProfileId").toString())) { + error = QStringLiteral("Unknown product holiday profile"); + return false; + } + if (!next.validMapping(product.value("ratePlansByPeriod").toObject())) { + error = QStringLiteral("Invalid base rate-plan mapping"); + return false; + } + for (const auto &override : product.value("seasonalRatePlansByPeriod").toObject()) { + if (!next.validMapping(override.toObject())) { + error = QStringLiteral("Invalid seasonal rate-plan mapping"); + return false; + } + } + } + + if (settings.contains("holidayFile")) { + const auto name = settings.value("holidayFile").toString(); + if (name.isEmpty() || QDir::isAbsolutePath(name)) { + error = QStringLiteral("holidayFile must be a relative path"); + return false; + } + if (!next.calendar.load(QFileInfo(path).dir().filePath(name), + settings.value("holidayProfileId").toString(), + next.profiles.keys(), error)) + return false; + } + *this = next; + error.clear(); + return true; + } + + QString vehicleType(const QString &productId) const + { + return products.value(productId).value("vehicleType").toString(); + } + + bool profileForDate(const QString &productId, const QDate &date, + QJsonObject &profile, QString &error) const + { + profile = QJsonObject(); + if (!products.contains(productId)) { + error = QStringLiteral("Unknown tariff product: %1").arg(productId); + return false; + } + QString profileId; + if (!calendar.resolve(date, profileId, error)) + return false; + if (!profileId.isEmpty()) { + profile = profiles.value(profileId); + return true; + } + + const QStringList weekdays = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"}; + const auto day = weekdays.at(date.dayOfWeek() - 1); + for (const auto &id : products.value(productId).value("workingDayProfileIds").toArray()) { + const auto candidate = profiles.value(id.toString()); + if (candidate.value("weekdays").toArray().contains(QJsonValue(day))) { + if (!profile.isEmpty()) { + error = QStringLiteral("Multiple weekday profiles for %1 on %2").arg(productId, day); + return false; + } + profile = candidate; + } + } + return true; + } + + QDateTime localTime(const QDateTime &instant) const + { + return instant.toLocalTime(); + } + + QJsonObject planForPeriod(const QString &productId, const QString &periodId, + const QDateTime &parkingStart) const + { + const auto product = products.value(productId); + const auto monthDay = localTime(parkingStart).date().toString("MM-dd"); + const auto overrides = product.value("seasonalRatePlansByPeriod").toObject(); + for (const auto &item : seasons) { + const auto season = item.toObject(); + const auto from = season.value("from").toString(); + const auto to = season.value("to").toString(); + const bool matches = from <= to ? from <= monthDay && monthDay <= to + : from <= monthDay || monthDay <= to; + if (matches) { + const auto planId = overrides.value(season.value("id").toString()) + .toObject().value(periodId).toString(); + if (!planId.isEmpty()) + return plans.value(planId); + break; + } + } + return plans.value(product.value("ratePlansByPeriod").toObject().value(periodId).toString()); + } + +public: + static bool index(const QJsonValue &value, QMap &result) + { + const auto entries = value.toArray(); + for (const auto &entry : entries) { + const auto object = entry.toObject(); + const auto id = object.value("id").toString(); + if (id.isEmpty() || result.contains(id)) + return false; + result.insert(id, object); + } + return !entries.isEmpty(); + } + + bool validMapping(const QJsonObject &mapping) const + { + for (const auto &value : mapping) { + if (!plans.contains(value.toString())) + return false; + } + return !mapping.isEmpty(); + } + + CompactCalendar calendar; + QJsonArray seasons; + QMap products; + QMap plans; + QMap profiles; +}; + +} // namespace Mobilisis + +#endif diff --git a/library/src/compact_api.cpp b/library/src/compact_api.cpp new file mode 100644 index 0000000..db7d504 --- /dev/null +++ b/library/src/compact_api.cpp @@ -0,0 +1,23 @@ +#include "mobilisis/compact_api.h" +namespace Mobilisis { +bool compactStayQuote(CompactEngine &engine, const QString &product, + const QDateTime &entry, const QDateTime &end, CompactChoice "e, qint64 &paidSeconds) +{ + return engine.quoteStay(product, entry, end, quote, paidSeconds); +} +bool loadCompactTariff(CompactEngine &engine, const QString &path) +{ + return engine.load(path); +} +bool compactTicketChoices(CompactEngine &engine, const QString &product, + const QDateTime &start, QVector &choices) +{ + return engine.choices(product, start, choices); +} +bool compactPaymentChoice(CompactEngine &engine, const QString &product, + const QDateTime &start, const QVector &choices, qint64 amount, + CompactChoice &choice, int &index, bool &dayTicket) +{ + return engine.paymentChoice(product, start, choices, amount, choice, index, dayTicket); +} +} diff --git a/tests/compact/compact.pro b/tests/compact/compact.pro new file mode 100644 index 0000000..5fbe4b9 --- /dev/null +++ b/tests/compact/compact.pro @@ -0,0 +1,7 @@ +QT = core +CONFIG += console c++17 +CONFIG -= app_bundle +TEMPLATE = app +TARGET = compact_tariff_checks +INCLUDEPATH += ../../library/include +SOURCES += compact_checks.cpp diff --git a/tests/compact/compact_checks.cpp b/tests/compact/compact_checks.cpp new file mode 100644 index 0000000..2967f51 --- /dev/null +++ b/tests/compact/compact_checks.cpp @@ -0,0 +1,90 @@ +#include +#include +#include +#include + +static void require(bool success, const QString &message) +{ + if (!success) { + qCritical().noquote() << message; + std::exit(1); + } +} + +int main(int argc, char **argv) +{ + QCoreApplication app(argc, argv); + require(argc == 2, "Pass the path to examples/tariff.json"); + Mobilisis::CompactEngine engine; + require(engine.load(QString::fromLocal8Bit(argv[1])), engine.error); + QVector rows; + const auto fixed = engine.tariff.plans.value("weiden_short_term"); + require(engine.expand(fixed, rows), engine.error); + require(rows.size() == 10, "Ten steps including anchors"); + for (int i = 0; i < rows.size(); ++i) + require(rows[i].price == (i + 1) * 100 && rows[i].minutes == (i + 1) * 120, + "Fixed-step interpolation differs from agreed example"); + + QJsonObject overlap = fixed; + auto steps = overlap.value("steps").toArray(); + QJsonObject preset; + preset["priceMinor"] = 500; + preset["durationMinutes"] = 650; + steps.append(preset); + overlap["steps"] = steps; + require(engine.expand(overlap, rows), engine.error); + require(rows[4].price == 500 && rows[4].minutes == 650, "Preset must win collision"); + + const Qt::TimeSpec zone = Qt::LocalTime; + QVector choices; + require(engine.choices("SHORT_TERM_PARKING", QDateTime(QDate(2027, 6, 7), QTime(11, 0), zone), + choices), engine.error); + require(choices.first().end == QDateTime(QDate(2027, 6, 7), QTime(15, 0), zone), + "120 paid minutes starting 11:00 must skip lunch"); + + require(engine.choices("DAY_TICKET", QDateTime(QDate(2027, 6, 5), QTime(10, 0), zone), + choices), engine.error); + require(choices.size() == 3 && choices[1].end.date() == QDate(2027, 6, 7), + "Stacked day ticket must skip Sunday"); + + require(engine.choices("SHORT_TERM_PARKING_CAR", + QDateTime(QDate(2027, 6, 7), QTime(13, 0), zone), choices), engine.error); + require(choices.last().end == QDateTime(QDate(2027, 6, 8), QTime(14, 0), zone), + "24-hour cap purchased in lunch break begins at 14:00"); + Mobilisis::CompactChoice paid; + int index = -1; + bool dayTicket = false; + const QDateTime monday(QDate(2027, 6, 7), QTime(11, 0), zone); + require(engine.choices("SHORT_TERM_PARKING", monday, choices), engine.error); + require(engine.paymentChoice("SHORT_TERM_PARKING", monday, choices, 150, + paid, index, dayTicket), engine.error); + require(paid.price == 150 && paid.minutes == 180 && !dayTicket && + paid.end == QDateTime(monday.date(), QTime(16, 0), zone), + "Intermediate coin amount must buy 180 paid minutes across lunch"); + require(engine.paymentChoice("SHORT_TERM_PARKING", monday, choices, 151, + paid, index, dayTicket), engine.error); + require(paid.price == 151 && paid.minutes == 182 && + paid.end == QDateTime(monday.date(), QTime(16, 17), zone), + "Round duration upward and skip the second break"); + require(engine.paymentChoice("SHORT_TERM_PARKING", monday, choices, 200, + paid, index, dayTicket), engine.error); + require(paid.price == 200 && paid.minutes == 240, "Exact preset remains exact"); + require(!engine.paymentChoice("SHORT_TERM_PARKING", monday, choices, 99, + paid, index, dayTicket), "No extrapolation below minimum"); + + const QDateTime saturday(QDate(2027, 6, 5), QTime(10, 0), zone); + require(engine.choices("DAY_TICKET", saturday, choices), engine.error); + require(engine.paymentChoice("DAY_TICKET", saturday, choices, 750, + paid, index, dayTicket), engine.error); + require(dayTicket && paid.price == 500 && paid.end.date() == saturday.date(), + "750 buys one 500 day ticket and leaves 250 change"); + require(engine.paymentChoice("DAY_TICKET", saturday, choices, 1250, + paid, index, dayTicket), engine.error); + require(dayTicket && paid.price == 1000 && paid.end.date() == QDate(2027, 6, 7), + "1250 buys two paid days, skips Sunday, and leaves 250 change"); + require(engine.paymentChoice("DAY_TICKET", saturday, choices, 1000, + paid, index, dayTicket), engine.error); + require(paid.price == 1000 && index == 1, "Exact stacked price has no remainder"); + + qInfo() << "Compact tariff checks passed"; +} diff --git a/tests/postpaid/postpaid.pro b/tests/postpaid/postpaid.pro new file mode 100644 index 0000000..9a5c781 --- /dev/null +++ b/tests/postpaid/postpaid.pro @@ -0,0 +1,7 @@ +QT = core +CONFIG += console c++17 +CONFIG -= app_bundle +TEMPLATE = app +TARGET = postpaid_checks +INCLUDEPATH += ../../library/include +SOURCES += postpaid_checks.cpp diff --git a/tests/postpaid/postpaid_checks.cpp b/tests/postpaid/postpaid_checks.cpp new file mode 100644 index 0000000..1d0c8f4 --- /dev/null +++ b/tests/postpaid/postpaid_checks.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +static void check(bool ok, const QString &why) { + if (!ok) { qCritical().noquote() << why; std::exit(1); } +} +int main(int argc, char **argv) { + QCoreApplication app(argc, argv); + check(argc >= 2, "Usage: postpaid_checks tariff_start_to_now.json [exit ISO timestamp]"); + Mobilisis::CompactEngine e; + check(e.load(QString::fromLocal8Bit(argv[1])), e.error); + const QDateTime start(QDate(2026,11,17), QTime(12,0), Qt::LocalTime); + Mobilisis::CompactChoice q; + qint64 paid = 0; + auto quote = [&](qint64 secs) { + check(e.quoteStay("SHORT_TERM_PARKING",start,start.addSecs(secs),q,paid),e.error); + check(q.end == start.addSecs(secs),"Billing end must not move"); + }; + e.postpaid["billingMode"] = "exact"; + quote(0); check(q.price == 0,"Zero stay"); + quote(60); check(q.price == 10,"One minute rounds up to ten cents"); + quote(3600); check(q.price == 200,"Exact hour"); + quote(3660); check(q.price == 210,"61 minutes exact"); + quote(3601); check(q.price == 210,"Started minute"); + e.postpaid["billingMode"] = "started_hours"; + quote(3600); check(q.price == 200,"Exact hour must not become two"); + quote(3601); check(q.price == 400,"One second beyond an hour"); + e.postpaid["billingMode"] = "exact"; + e.postpaid["exitGraceMinutes"] = 15; + quote(3600); check(q.price == 200,"Grace must not reduce charge"); + check(!e.quoteStay("SHORT_TERM_PARKING",start,start.addSecs(-1),q,paid),"Reject future entry"); + check(!e.quoteStay("UNKNOWN",start,start,q,paid),"Reject unknown product"); + auto profile=e.tariff.profiles["all"]; + profile["breaks"]=QJsonArray{QJsonObject{{"from","12:30"},{"to","13:00"}}}; + e.tariff.profiles["all"]=profile; + quote(5400); check(paid==3600 && q.price==200,"Exclude lunch break"); + profile["breaks"]=QJsonArray{}; e.tariff.profiles["all"]=profile; + quote(13*3600); check(paid==13*3600-60,"Respect configured 23:59 end across midnight"); + check(!e.quoteStay("SHORT_TERM_PARKING",start,start.addDays(9),q,paid),"Reject uncovered long stay"); + e.postpaid["moneyIncrementMinor"]=0; + check(!e.quoteStay("SHORT_TERM_PARKING",start,start,q,paid),"Reject invalid rounding"); + e.postpaid["moneyIncrementMinor"]=10; + const auto end=argc>2 ? QDateTime::fromString(QString::fromLocal8Bit(argv[2]),Qt::ISODate) + : QDateTime::currentDateTime(); + const QDateTime entry(end.date(),QTime(12,0),Qt::LocalTime); + check(e.quoteStay("SHORT_TERM_PARKING",entry,end,q,paid),e.error); + qInfo()<<"entry"<