File size: 7,759 Bytes
13240d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
using BakeryErp.Infrastructure.Database;

namespace BakeryErp.Infrastructure.Repositories;

public sealed class PurchaseRepository
{
    private readonly DatabaseOptions _options;

    public PurchaseRepository(DatabaseOptions options)
    {
        _options = options;
    }

    public IReadOnlyList<LocalPurchaseOrder> List()
    {
        return LocalDataStoreFile.Load(_options)
            .PurchaseOrders
            .OrderByDescending(static order => order.OrderDate)
            .ThenBy(static order => order.OrderNumber)
            .ToList();
    }

    public LocalPurchaseOrder? Find(Guid id)
    {
        return LocalDataStoreFile.Load(_options)
            .PurchaseOrders
            .FirstOrDefault(order => order.Id == id);
    }

    public PurchaseReport GetReport()
    {
        var orders = LocalDataStoreFile.Load(_options).PurchaseOrders;
        return new PurchaseReport(
            orders.Count,
            orders.Count(static order => order.Status == LocalPurchaseOrderStatus.PendingApproval),
            orders.Count(static order => order.Status == LocalPurchaseOrderStatus.Approved),
            orders.Count(static order => order.Status == LocalPurchaseOrderStatus.MonthlyClosed),
            orders.Where(static order => order.Status != LocalPurchaseOrderStatus.Cancelled).Sum(static order => order.LineAmount),
            orders.Where(static order => order.Status == LocalPurchaseOrderStatus.Approved).Sum(static order => order.LineAmount),
            orders.Where(static order => order.Status == LocalPurchaseOrderStatus.MonthlyClosed).Sum(static order => order.LineAmount));
    }

    public IReadOnlyList<SupplierPurchaseSummary> GetSupplierSummaries()
    {
        return LocalDataStoreFile.Load(_options)
            .PurchaseOrders
            .Where(static order => order.Status != LocalPurchaseOrderStatus.Cancelled)
            .GroupBy(static order => order.SupplierName)
            .Select(group => new SupplierPurchaseSummary(
                group.Key,
                group.Count(),
                group.Sum(static order => order.LineAmount),
                group.Count(static order => order.Status == LocalPurchaseOrderStatus.MonthlyClosed)))
            .OrderByDescending(static summary => summary.TotalAmount)
            .ToList();
    }

    public SavePurchaseOrderResult Save(LocalPurchaseOrder order)
    {
        var store = LocalDataStoreFile.Load(_options);
        var orderNumber = order.OrderNumber.Trim().ToUpperInvariant();

        if (string.IsNullOrWhiteSpace(orderNumber) ||
            string.IsNullOrWhiteSpace(order.SupplierName) ||
            string.IsNullOrWhiteSpace(order.ItemName) ||
            string.IsNullOrWhiteSpace(order.Unit))
        {
            return SavePurchaseOrderResult.ValidationError("採購單號、供應商、品項與單位為必填。");
        }

        if (order.Quantity <= 0 || order.UnitPrice < 0)
        {
            return SavePurchaseOrderResult.ValidationError("數量需大於 0,單價不可小於 0。");
        }

        var duplicatedNumber = store.PurchaseOrders.Any(existing =>
            existing.Id != order.Id &&
            string.Equals(existing.OrderNumber, orderNumber, StringComparison.OrdinalIgnoreCase));
        if (duplicatedNumber)
        {
            return SavePurchaseOrderResult.ValidationError("採購單號已存在,請改用其他單號。");
        }

        var existingOrder = store.PurchaseOrders.FirstOrDefault(existing => existing.Id == order.Id);
        if (existingOrder is null)
        {
            order.Id = order.Id == Guid.Empty ? Guid.NewGuid() : order.Id;
            order.OrderNumber = orderNumber;
            order.SupplierName = order.SupplierName.Trim();
            order.ItemSku = BlankToEmpty(order.ItemSku).ToUpperInvariant();
            order.ItemName = order.ItemName.Trim();
            order.Unit = order.Unit.Trim();
            order.Note = BlankToNull(order.Note);
            order.Status = LocalPurchaseOrderStatus.PendingApproval;
            order.CreatedAt = DateTime.UtcNow;
            store.PurchaseOrders.Add(order);
        }
        else
        {
            if (existingOrder.Status is LocalPurchaseOrderStatus.Approved or LocalPurchaseOrderStatus.MonthlyClosed)
            {
                return SavePurchaseOrderResult.ValidationError("已審核或已月結的採購單不可編輯。");
            }

            existingOrder.OrderNumber = orderNumber;
            existingOrder.SupplierName = order.SupplierName.Trim();
            existingOrder.OrderDate = order.OrderDate;
            existingOrder.ItemSku = BlankToEmpty(order.ItemSku).ToUpperInvariant();
            existingOrder.ItemName = order.ItemName.Trim();
            existingOrder.Quantity = order.Quantity;
            existingOrder.Unit = order.Unit.Trim();
            existingOrder.UnitPrice = order.UnitPrice;
            existingOrder.Note = BlankToNull(order.Note);
            existingOrder.Status = LocalPurchaseOrderStatus.PendingApproval;
            existingOrder.UpdatedAt = DateTime.UtcNow;
        }

        LocalDataStoreFile.Save(_options, store);
        return SavePurchaseOrderResult.Success();
    }

    public void Approve(Guid id)
    {
        UpdateStatus(id, LocalPurchaseOrderStatus.Approved);
    }

    public void CloseMonthly(Guid id)
    {
        UpdateStatus(id, LocalPurchaseOrderStatus.MonthlyClosed);
    }

    public void Cancel(Guid id)
    {
        UpdateStatus(id, LocalPurchaseOrderStatus.Cancelled);
    }

    public static string GetStatusName(LocalPurchaseOrderStatus status)
    {
        return status switch
        {
            LocalPurchaseOrderStatus.Draft => "草稿",
            LocalPurchaseOrderStatus.PendingApproval => "待審核",
            LocalPurchaseOrderStatus.Approved => "已審核",
            LocalPurchaseOrderStatus.MonthlyClosed => "已月結",
            LocalPurchaseOrderStatus.Cancelled => "已取消",
            _ => status.ToString()
        };
    }

    private void UpdateStatus(Guid id, LocalPurchaseOrderStatus status)
    {
        var store = LocalDataStoreFile.Load(_options);
        var order = store.PurchaseOrders.FirstOrDefault(existing => existing.Id == id);
        if (order is null)
        {
            return;
        }

        if (status == LocalPurchaseOrderStatus.Cancelled && order.Status == LocalPurchaseOrderStatus.MonthlyClosed)
        {
            return;
        }

        order.Status = status;
        order.UpdatedAt = DateTime.UtcNow;
        if (status == LocalPurchaseOrderStatus.Approved)
        {
            order.ApprovedAt = DateTime.UtcNow;
        }
        if (status == LocalPurchaseOrderStatus.MonthlyClosed)
        {
            order.ClosedAt = DateTime.UtcNow;
        }

        LocalDataStoreFile.Save(_options, store);
    }

    private static string BlankToEmpty(string? value)
    {
        return string.IsNullOrWhiteSpace(value) ? string.Empty : value.Trim();
    }

    private static string? BlankToNull(string? value)
    {
        return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
    }
}

public sealed record PurchaseReport(
    int OrderCount,
    int PendingApprovalCount,
    int ApprovedCount,
    int MonthlyClosedCount,
    decimal TotalAmount,
    decimal PayableAmount,
    decimal ClosedAmount);

public sealed record SupplierPurchaseSummary(
    string SupplierName,
    int OrderCount,
    decimal TotalAmount,
    int ClosedCount);

public sealed record SavePurchaseOrderResult(bool IsSuccess, string? ErrorMessage)
{
    public static SavePurchaseOrderResult Success() => new(true, null);
    public static SavePurchaseOrderResult ValidationError(string message) => new(false, message);
}