Use server final price on download without local markup math.

Server now sums price-list, region and buyer markups; desktop must not re-apply discounts.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Exest 2026-07-30 15:40:36 +03:00
parent d68155b8ef
commit 9dfdb913cb

View File

@ -59,23 +59,9 @@ namespace Электронная_Фармация.HelpForms
var allSuppliersSummary = await GetFullPriceSummaryPagedAsync(client); var allSuppliersSummary = await GetFullPriceSummaryPagedAsync(client);
int totalItems = allSuppliersSummary.Summary?.Count ?? 0; int totalItems = allSuppliersSummary.Summary?.Count ?? 0;
AppendStatus("Загружаю скидки покупателя / прайса / региона..."); // Наценки прайса/региона/покупателя считает сервер.
var discountLookup = await DiscountResolver.LoadAsync(client, _login); // Десктоп сохраняет цену из API как есть, без локального пересчёта.
if (!string.IsNullOrWhiteSpace(discountLookup.BuyerId)) AppendStatus("Цена берётся с сервера без локального пересчёта наценок");
{
AppendStatus($"buyer_id: {discountLookup.BuyerId}");
}
else
{
AppendStatus("buyer_id не найден — клиентская скидка будет 0, если не пришла иначе");
}
AppendStatus($"Прайс-листов со скидками: {discountLookup.ByPriceListId.Count}");
ApplyClientMarkupSettings(allSuppliersSummary);
if (allSuppliersSummary.MarkupPercent.HasValue)
{
AppendStatus($"Скидка из summary: {allSuppliersSummary.MarkupPercent.Value:0.##}%");
}
AppendStatus($"Получено {totalItems} позиций"); AppendStatus($"Получено {totalItems} позиций");
SetOverallProgress(DownloadPhaseEnd, $"Получено {totalItems} / {totalItems} позиций (100%)"); SetOverallProgress(DownloadPhaseEnd, $"Получено {totalItems} / {totalItems} позиций (100%)");
@ -88,7 +74,7 @@ namespace Электронная_Фармация.HelpForms
phasePercent, phasePercent,
$"Обработка: {p.Current} / {p.Total} ({PercentOf(p.Current, p.Total)}%)"); $"Обработка: {p.Current} / {p.Total} ({PercentOf(p.Current, p.Total)}%)");
}); });
var tablePrice = await Task.Run(() => BuildPriceTable(allSuppliersSummary, discountLookup, buildProgress)); var tablePrice = await Task.Run(() => BuildPriceTable(allSuppliersSummary, buildProgress));
SetOverallProgress(BuildPhaseEnd, "Сохранение в локальную базу..."); SetOverallProgress(BuildPhaseEnd, "Сохранение в локальную базу...");
var saveProgress = new Progress<CountProgress>(p => var saveProgress = new Progress<CountProgress>(p =>
@ -366,18 +352,6 @@ namespace Электронная_Фармация.HelpForms
} }
} }
private static void ApplyClientMarkupSettings(PriceSummaryResponse response)
{
// Серверный % используем только как стартовое значение для аптек,
// у которых клиент ещё ничего не сохранил. Уже введённые проценты не трогаем.
if (response?.MarkupPercent == null)
{
return;
}
ConsigneeHelper.SeedClientMarkupPercentIfEmpty(response.MarkupPercent);
}
private void ReportTransferProgress(HttpTransferProgress transfer) private void ReportTransferProgress(HttpTransferProgress transfer)
{ {
if (transfer.TotalBytes.HasValue && transfer.TotalBytes.Value > 0) if (transfer.TotalBytes.HasValue && transfer.TotalBytes.Value > 0)
@ -397,7 +371,6 @@ namespace Электронная_Фармация.HelpForms
private static DataTable BuildPriceTable( private static DataTable BuildPriceTable(
PriceSummaryResponse allSuppliersSummary, PriceSummaryResponse allSuppliersSummary,
DiscountLookup discountLookup,
IProgress<CountProgress> progress = null) IProgress<CountProgress> progress = null)
{ {
var tablePrice = new DataTable(); var tablePrice = new DataTable();
@ -447,7 +420,6 @@ namespace Электронная_Фармация.HelpForms
return tablePrice; return tablePrice;
} }
var summaryClientDiscount = allSuppliersSummary.MarkupPercent;
int total = allSuppliersSummary.Summary.Count; int total = allSuppliersSummary.Summary.Count;
int current = 0; int current = 0;
foreach (var item in allSuppliersSummary.Summary) foreach (var item in allSuppliersSummary.Summary)
@ -460,19 +432,9 @@ namespace Электронная_Фармация.HelpForms
row["DrugName"] = item.DrugName ?? string.Empty; row["DrugName"] = item.DrugName ?? string.Empty;
row["SupplierName"] = item.SupplierName ?? string.Empty; row["SupplierName"] = item.SupplierName ?? string.Empty;
var parts = DiscountResolver.ResolveForItem(discountLookup, item); // Цена уже итоговая с сервера — локально не пересчитываем.
// Вешаем только то, что пришло. Нет значения = 0. var serverPrice = item.Price ?? 0m;
// summary.markup_percent / item.markup_percent — доп. источник, если API ещё отдаёт. row["Price"] = serverPrice.ToString(System.Globalization.CultureInfo.InvariantCulture);
var totalDiscount = MarkupHelper.SumDiscountPercents(
parts.PriceListDiscountPct,
parts.RegionDiscountPct,
parts.ClientDiscountPct > 0m ? parts.ClientDiscountPct : (decimal?)null,
parts.ClientDiscountPct <= 0m ? summaryClientDiscount : null,
item.MarkupPercent);
var basePrice = item.Price ?? 0m;
var finalPrice = MarkupHelper.ApplyDiscount(basePrice, totalDiscount);
row["Price"] = finalPrice.ToString(System.Globalization.CultureInfo.InvariantCulture);
row["Quantity"] = item.Quantity?.ToString() ?? string.Empty; row["Quantity"] = item.Quantity?.ToString() ?? string.Empty;
row["ExpiryPeriod"] = item.ExpiryPeriod == null ? (object)DBNull.Value : item.ExpiryPeriod; row["ExpiryPeriod"] = item.ExpiryPeriod == null ? (object)DBNull.Value : item.ExpiryPeriod;
row["Description"] = item.Description == null ? (object)DBNull.Value : item.Description; row["Description"] = item.Description == null ? (object)DBNull.Value : item.Description;
@ -480,7 +442,9 @@ namespace Электронная_Фармация.HelpForms
row["SummaZakaza"] = string.Empty; row["SummaZakaza"] = string.Empty;
row["TradeName"] = string.IsNullOrWhiteSpace(item.TradeName) ? (object)DBNull.Value : item.TradeName.Trim(); row["TradeName"] = string.IsNullOrWhiteSpace(item.TradeName) ? (object)DBNull.Value : item.TradeName.Trim();
row["Dosage"] = string.IsNullOrWhiteSpace(item.Dosage) ? (object)DBNull.Value : item.Dosage.Trim(); row["Dosage"] = string.IsNullOrWhiteSpace(item.Dosage) ? (object)DBNull.Value : item.Dosage.Trim();
row["MarkupPercent"] = totalDiscount; row["MarkupPercent"] = item.MarkupPercent.HasValue && item.MarkupPercent.Value > 0m
? item.MarkupPercent.Value
: 0m;
tablePrice.Rows.Add(row); tablePrice.Rows.Add(row);
current++; current++;