XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

STHApplication

【MAUI】寄当家——安卓端交易管理系统

公开
关注 0 Fork 0 Star 0
UTF-8
using Microsoft.Data.Sqlite;
using System.Reflection;
using System.Text.Json;

namespace JiDangJia.Core;

public sealed class Database
{
    private readonly object sync = new();
    public string FilePath { get; }
    public Action? BeforeWrite {get;set;}
    public event Action? Committed;
    private bool retired;
    public void Retire(){lock(sync)retired=true;}
    private void Available(){if(retired)throw new InvalidOperationException("此账户数据已清除,请重新进入账户");}
    public static readonly string[] Tables = ["Shop", "PawnItemTypeRate", "User", "Customer", "PawnTicket", "PawnItem", "RedeemRecord", "RenewRecord", "FinanceCategory", "FinanceRecord", "Reminder", "OperationLog", "PrintTemplate", "RecycleOrder", "RecycleItem", "SaleRecord", "BusinessOrder", "Advertisement", "FundingAccount", "FundingSettlement"];
    public Database(string filePath)
    {
        FilePath = filePath;
        Directory.CreateDirectory(Path.GetDirectoryName(filePath)!);
        using var c = Open();
        using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("JiDangJia.Core.Schema.sql")!;
        Execute(c, new StreamReader(stream).ReadToEnd());
        if(!Query(c,"PRAGMA table_info(RecycleOrder)").Any(r=>r.Text("name")=="source"))
            Execute(c,"ALTER TABLE RecycleOrder ADD COLUMN source TEXT NOT NULL DEFAULT 'RECYCLE'");
        // Additive migrations preserve legacy type codes and imported item attributes.
        foreach(var table in new[]{"PawnItem","RecycleItem"})
        {
            AddColumn(c,table,"material","TEXT");AddColumn(c,table,"unitPrice","REAL NOT NULL DEFAULT 0");AddColumn(c,table,"itemCode","TEXT");
        }
        AddColumn(c,"BusinessOrder","items","TEXT");AddColumn(c,"BusinessOrder","expectedAmount","TEXT");
        AddColumn(c,"BusinessOrder","serviceFeeMode","TEXT NOT NULL DEFAULT ''");
        AddColumn(c,"BusinessOrder","serviceFeeValue","REAL NOT NULL DEFAULT 0");AddColumn(c,"BusinessOrder","storageFee","REAL NOT NULL DEFAULT 0");
        foreach(var table in RecordLifecycle.Tables)
        {
            AddColumn(c,table,"deletedAt","TEXT");AddColumn(c,table,"trashGroup","TEXT");
        }
        AddColumn(c,"RecycleItem","rentalOrderId","TEXT");AddColumn(c,"RecycleItem","originBusinessId","TEXT");
        AddColumn(c,"RecycleItem","costKnown","INTEGER NOT NULL DEFAULT 1");
        AddColumn(c,"SaleRecord","rentalOrderId","TEXT");
        AddColumn(c,"BusinessOrder","rentalOutcome","TEXT");AddColumn(c,"BusinessOrder","saleAmount","REAL NOT NULL DEFAULT 0");
        AddColumn(c,"FinanceRecord","majorClass","TEXT");AddColumn(c,"FinanceRecord","detailClass","TEXT");AddColumn(c,"FinanceRecord","allocations","TEXT");
        Execute(c,"BEGIN IMMEDIATE");
        try {RentalInventory.Migrate(c);FinanceAnalytics.EnsureSnapshots(c);Execute(c,"COMMIT");}
        catch {Execute(c,"ROLLBACK");throw;}
        Execute(c, "PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;");
        if (Query(c, "SELECT id FROM Shop LIMIT 1").Count == 0)
            Upsert(c, "Shop", new DbRow { ["id"]="shop_default", ["name"]="我的店铺", ["createdAt"]=Now, ["updatedAt"]=Now });
        if (Query(c,"SELECT id FROM User LIMIT 1").Count == 0)
            Upsert(c,"User",new DbRow { ["id"]="user_owner", ["name"]="店长", ["role"]="店长", ["active"]=1, ["createdAt"]=Now, ["updatedAt"]=Now });
        if (Query(c,"SELECT id FROM PawnItemTypeRate LIMIT 1").Count == 0)
            foreach (var p in Display.ItemTypes.Select((p,i)=>(p,i)))
                Upsert(c,"PawnItemTypeRate",new DbRow { ["id"]=Id("type"), ["shopId"]="shop_default", ["itemType"]=p.p.Key, ["label"]=p.p.Value, ["sortOrder"]=p.i, ["createdAt"]=Now, ["updatedAt"]=Now });
        foreach(var shop in Query(c,"SELECT id FROM Shop"))foreach(var type in new[]{"METAL","LUXURY"})
            if(Query(c,"SELECT id FROM PawnItemTypeRate WHERE shopId=@p0 AND itemType=@p1",shop.Id,type).Count==0)
                Upsert(c,"PawnItemTypeRate",new DbRow{["id"]=Id("type"),["shopId"]=shop.Id,["itemType"]=type,["label"]=ItemCatalog.Categories[type],["sortOrder"]=type=="METAL"?0:4,["createdAt"]=Now,["updatedAt"]=Now});
        foreach (var p in Display.Categories)
        {
            if (Query(c,"SELECT id FROM FinanceCategory WHERE code=@p0",p.Key).Count > 0) continue;
            Upsert(c,"FinanceCategory",new DbRow { ["id"]=Id("fc"), ["shopId"]="shop_default", ["code"]=p.Key, ["label"]=p.Value, ["type"]=Display.ExpenseCategories.Contains(p.Key) ? "EXPENSE" : "INCOME", ["createdAt"]=Now, ["updatedAt"]=Now });
        }
    }
    private static void AddColumn(SqliteConnection c,string table,string name,string definition)
    {
        if(!Query(c,$"PRAGMA table_info([{table}])").Any(r=>r.Text("name")==name))Execute(c,$"ALTER TABLE [{table}] ADD COLUMN [{name}] {definition}");
    }
    public static string Now => DateTime.UtcNow.ToString("O");
    public static string Id(string prefix) => prefix+"_"+Guid.NewGuid().ToString("N");
    public SqliteConnection Open()
    {
        var c = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource=FilePath, Pooling=false }.ToString());
        c.Open();
        return c;
    }
    public T Read<T>(Func<SqliteConnection,T> action) { lock(sync) { Available();using var c=Open(); return action(c); } }
    public T Write<T>(Func<SqliteConnection,T> action)
    {
        BeforeWrite?.Invoke();
        T result;
        lock(sync)
        {
            Available();using var c=Open(); Execute(c,"BEGIN IMMEDIATE");
            try { result=action(c); Execute(c,"COMMIT"); }
            catch { Execute(c,"ROLLBACK"); throw; }
        }
        if(Committed is { } subscribers)foreach(Action subscriber in subscribers.GetInvocationList())
            try{subscriber();}catch(Exception ex){System.Diagnostics.Debug.WriteLine("Database commit observer: "+ex.GetType().Name);}
        return result;
    }
    public List<DbRow> Query(string sql, params object?[] args) => Read(c=>Query(c,sql,args));
    public DbRow? Find(string table, string id) { EnsureTable(table); return Query($"SELECT * FROM [{table}] WHERE id=@p0",id).FirstOrDefault(); }
    public void Save(string table, DbRow row) => Write(c=> { Upsert(c,table,row); Log(c,"SAVE",table,row.Id,row.Text("name",row.Text("label"))); return 0; });
    public static void EnsureTable(string table) { if (!Tables.Contains(table,StringComparer.Ordinal)) throw new ArgumentException("未知数据表"); }
    public static List<DbRow> Query(SqliteConnection c,string sql,params object?[] args)
    {
        using var cmd=Command(c,sql,args); using var reader=cmd.ExecuteReader(); var list=new List<DbRow>();
        while(reader.Read()) { var row=new DbRow(); for(int i=0;i<reader.FieldCount;i++) row[reader.GetName(i)]=reader.IsDBNull(i)?null:reader.GetValue(i); list.Add(row); }
        return list;
    }
    public static int Execute(SqliteConnection c,string sql,params object?[] args) { using var cmd=Command(c,sql,args); return cmd.ExecuteNonQuery(); }
    private static SqliteCommand Command(SqliteConnection c,string sql,object?[] args)
    {
        var cmd=c.CreateCommand(); cmd.CommandText=sql;
        for(int i=0;i<args.Length;i++) cmd.Parameters.AddWithValue("@p"+i,args[i]??DBNull.Value);
        return cmd;
    }
    public static void Upsert(SqliteConnection c,string table,DbRow row)
    {
        EnsureTable(table);
        var columns=Query(c,$"PRAGMA table_info([{table}])").Select(r=>r.Text("name")).ToHashSet(StringComparer.OrdinalIgnoreCase);
        var fields=row.Where(p=>columns.Contains(p.Key)).ToArray();
        if (!fields.Any(p=>p.Key=="id") || string.IsNullOrWhiteSpace(row.Id)) throw new ArgumentException("记录缺少编号");
        var names=string.Join(",",fields.Select(p=>$"[{p.Key}]"));
        var parms=string.Join(",",fields.Select((_,i)=>"@p"+i));
        var updates=string.Join(",",fields.Where(p=>p.Key!="id").Select(p=>$"[{p.Key}]=excluded.[{p.Key}]"));
        Execute(c,$"INSERT INTO [{table}] ({names}) VALUES ({parms}) ON CONFLICT(id) DO {(updates.Length>0?"UPDATE SET "+updates:"NOTHING")}",fields.Select(p=>p.Value).ToArray());
    }
    public static void Log(SqliteConnection c,string action,string table,string id,string name,string? detail=null) =>
        Upsert(c,"OperationLog",new DbRow { ["id"]=Id("log"), ["action"]=action, ["targetType"]=table, ["targetId"]=id, ["targetName"]=name, ["detail"]=detail, ["createdAt"]=Now });
    public string ExportBackup() => Read(c=>JsonSerializer.Serialize(new { version=1, exportedAt=Now, tables=Tables.ToDictionary(t=>t,t=>Query(c,$"SELECT * FROM [{t}]")) },new JsonSerializerOptions { WriteIndented=true }));
    public int ImportBackup(string json)
    {
        using var doc=JsonDocument.Parse(json);
        if (!doc.RootElement.TryGetProperty("tables",out var tables) || tables.ValueKind!=JsonValueKind.Object) throw new ArgumentException("请选择旧版导出的 JSON 备份文件");
        if (!tables.EnumerateObject().Any(p=>Tables.Contains(p.Name)&&p.Value.ValueKind==JsonValueKind.Array)) throw new ArgumentException("备份中没有可导入的数据");
        return Write(c=>
        {
            int count=0;
            // On a fresh account, replace the generated shop rather than displaying it over the imported shop.
            if(tables.TryGetProperty("Shop",out var importedShops)&&importedShops.ValueKind==JsonValueKind.Array&&importedShops.GetArrayLength()>0
                && !importedShops.EnumerateArray().Any(r=>r.TryGetProperty("id",out var id)&&id.GetString()=="shop_default")
                && Query(c,"SELECT id FROM Shop WHERE id='shop_default' AND name='我的店铺'").Count>0
                && Query(c,"SELECT id FROM Customer UNION ALL SELECT id FROM PawnTicket UNION ALL SELECT id FROM RecycleOrder UNION ALL SELECT id FROM FinanceRecord LIMIT 1").Count==0)
            {
                Execute(c,"DELETE FROM PawnItemTypeRate WHERE shopId='shop_default'");Execute(c,"DELETE FROM FinanceCategory WHERE shopId='shop_default'");Execute(c,"DELETE FROM Shop WHERE id='shop_default'");
            }
            foreach (var table in Tables)
            {
                if (!tables.TryGetProperty(table,out var rows) || rows.ValueKind!=JsonValueKind.Array) continue;
                foreach (var element in rows.EnumerateArray())
                {
                    var row=DbRow.FromJson(element);
                    // Rates and categories are identified by their business key as well as the legacy row id.
                    if(table=="PawnItemTypeRate")Execute(c,"DELETE FROM PawnItemTypeRate WHERE shopId=@p0 AND itemType=@p1 AND id<>@p2",row.Text("shopId"),row.Text("itemType"),row.Id);
                    if(table=="FinanceCategory")Execute(c,"DELETE FROM FinanceCategory WHERE shopId=@p0 AND type=@p1 AND code=@p2 AND id<>@p3",row.Text("shopId"),row.Text("type"),row.Text("code"),row.Id);
                    Upsert(c,table,row); count++;
                }
            }
            RentalInventory.Migrate(c);FinanceAnalytics.EnsureSnapshots(c);
            Log(c,"BACKUP_IMPORT","Shop","","合并导入备份",count+" 条记录");
            return count;
        });
    }
    public void Snapshot(string path) { Read(c=> { Directory.CreateDirectory(Path.GetDirectoryName(path)!); using var dest=new SqliteConnection("Data Source="+path); dest.Open(); c.BackupDatabase(dest); return 0; }); }
}