using Microsoft.EntityFrameworkCore; using PLCSharp.VVMs.Recipe; using PLCSharp.VVMs.Workflows; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; namespace PLCSharp.Models; internal sealed record DocumentDelta(string Path, string Before, string After); public sealed record OwnedRow(string Kind, Guid Id, string Name, [property: JsonIgnore] JsonObject Row, bool Restore = false); public sealed partial class ProjectDirectory { private static void RemoveOwned(JsonNode document, string table, Func match, List owned) { var rows = document[table].AsArray(); foreach (var row in rows.Where(match).ToList()) { owned.Add(new(table, Guid.Parse((string)row["ID"]), (string)row["Name"], row.AsObject())); rows.Remove(row); } } private ObjectEdit WithOwnedImpact(ObjectEdit edit, List owned) { foreach (var child in owned) { var impact = InspectEdit("delete", child.Kind, child.Id, ConfigPath(ObjectGroup(child.Kind)), child.Row, null, null, null); MergeImpact(edit, impact); } return edit with { OwnedRows = owned }; } private static void MergeImpact(ObjectEdit target, ObjectEdit child) { foreach (var (list, hits) in new[] { (target.WorkflowReferences, child.WorkflowReferences), (target.ManualReferences, child.ManualReferences), (target.ConfigReferences, child.ConfigReferences) }) foreach (var hit in hits) { var entry = hit.DeepClone(); entry["affectedKind"] = child.Kind; entry["affectedId"] = child.Id.ToString(); list.Add(entry); } foreach (var flow in child.Workflows) if (target.Workflows.All(w => w.Id != flow.Id)) target.Workflows.Add(flow); } private void ApplyOwnedRows(IEnumerable rows) { foreach (var row in rows) { if (row.Restore) ProjectConfiguration.Restore(Data, [row.Kind], new JsonObject { [row.Kind] = new JsonArray(row.Row.DeepClone()) }); else { var type = ProjectConfiguration.Entity(Data, row.Kind); if (Data.ChangeTracker.Entries().Any(e => e.Metadata == type && (Guid)e.Property("ID").CurrentValue == row.Id && e.State != EntityState.Unchanged)) throw new ProjectConflictException($"子对象 {row.Kind}/{row.Id} 有未保存的编辑。"); string sql = $"DELETE FROM \"{type.GetTableName()}\" WHERE ID = {{0}}"; if (Data.Database.ExecuteSqlRaw(sql, row.Id) != 1) throw new ProjectConflictException("所属配置已改变。"); } } } private void DetachDeletedRows(IEnumerable rows) { var removed = rows.Where(r => !r.Restore).Select(r => (r.Kind, r.Id)).ToHashSet(); if (removed.Count == 0) return; foreach (var entry in Data.ChangeTracker.Entries().ToList()) if (entry.Metadata.FindProperty("ID")?.ClrType == typeof(Guid) && removed.Contains((entry.Metadata.GetTableName(), (Guid)entry.Property("ID").CurrentValue))) entry.State = EntityState.Detached; } private static JsonObject FlowRow(Workflow flow) => new() { ["ID"] = flow.ID.ToString(), ["RecipeID"] = flow.RecipeID.ToString(), ["Name"] = flow.Name, ["Comment"] = flow.Comment, ["Code"] = flow.Code ?? "", ["AutomaticExecution"] = flow.AutomaticExecution, ["CycleDelayTime"] = flow.CycleDelayTime }; private static JsonObject RecipeRow(Recipe r) => new() { ["ID"] = r.ID.ToString(), ["Name"] = r.Name, ["Comment"] = r.Comment }; private ObjectEdit PlanStructureEdit(string action, string kind, Guid id, JsonObject patch) { bool recipe = kind == "Recipes"; var targetRecipe = Recipes.SingleOrDefault(r => r.ID == id); var targetFlow = recipe ? null : Recipes.SelectMany(r => Flows(r.ID)).SingleOrDefault(w => w.ID == id); JsonObject before = recipe ? targetRecipe == null ? null : RecipeRow(targetRecipe) : targetFlow == null ? null : FlowRow(targetFlow); if ((action == "create") != (before == null)) throw new ArgumentException("工程对象不存在或 ID 已占用。"); Guid owner = recipe ? id : targetFlow?.RecipeID ?? Guid.Parse((string)patch["RecipeID"]); if (!recipe && !Recipes.Any(r => r.ID == owner)) throw new ArgumentException("所属配方不存在。"); string path = recipe ? "project.json" : RecipePath(owner); JsonObject after = null; if (action != "delete") { after = before?.DeepClone().AsObject() ?? (recipe ? RecipeRow(new Recipe { ID = id }) : FlowRow(new Workflow { ID = id, RecipeID = owner })); foreach (var (key, value) in patch) { if (!after.ContainsKey(key) || key == "ID" || action == "update" && key is "RecipeID" or "Name") throw new ArgumentException($"不能通过属性修改 {key}。"); after[key] = value?.DeepClone(); } var name = (string)after["Name"]; var names = recipe ? Recipes.Where(r => r.ID != id).Select(r => r.Name) : Flows(owner).Where(w => w.ID != id).Select(w => w.Name); if (string.IsNullOrWhiteSpace(name) || name != name.Trim() || names.Contains(name)) throw new ArgumentException("工程对象名称无效或重复。"); _ = (string)after["Comment"]; if (!recipe) { double delay = (double)after["CycleDelayTime"]; if (!double.IsFinite(delay) || delay < 0 || delay > int.MaxValue / 1000.0) throw new ArgumentException("循环间隔超出范围。"); _ = (bool)after["AutomaticExecution"]; string code = (string)after["Code"]; if (action == "create") code = patch.ContainsKey("Code") ? code?.Replace("__WORKFLOW_ID__", id.ToString("N")) : $"using PLCSharp.Models;\nusing PLCSharp.Core.Common;\npublic class Extension_{id:N} {{ public void Run(GlobalModel model, FlowModel flow) {{ }} }}\n"; after["Code"] = code ?? ""; } if (JsonNode.DeepEquals(before, after)) throw new ArgumentException("属性没有变化。"); } if (recipe && action == "delete" && Recipes.Count == 1) throw new ArgumentException("工程必须保留一个配方。"); var files = new Dictionary(baseline); var recipePath = RecipePath(owner); var meta = action == "create" && recipe ? new JsonObject { ["id"] = id.ToString(), ["workflows"] = new JsonArray() } : JsonNode.Parse(files[recipePath]).AsObject(); List owned = []; var review = InspectEdit(action, kind, id, path, before, after, baseline[path], null); if (recipe) { var manifest = JsonNode.Parse(files[path]); var ids = manifest["recipes"].AsArray(); if (action == "delete") { foreach (var flow in Flows(owner)) { string script = ScriptPath(owner, flow.ID); review.ConfigReferences.Add(new JsonObject { ["path"] = script, ["table"] = "Workflows", ["id"] = flow.ID.ToString(), ["field"] = "RecipeID" }); MergeImpact(review, InspectEdit("delete", "Workflows", flow.ID, script, FlowRow(flow), null, null, null)); CheckFlowCode(review, flow.ID, flow.Name, script, flow.Code, flow.Code); files.Remove(script); } files.Remove(recipePath); ids.Remove(ids.Single(v => Guid.Parse((string)v) == id)); if (DefaultRecipeId == id) manifest["defaultRecipeId"] = (string)ids[0]; var functions = Data.VisionFunctions.Where(f => f.RecipeID == id).Select(f => f.ID).ToHashSet(); foreach (var (group, tables) in ProjectConfiguration.Groups) { var config = ConfigPath(group); var doc = JsonNode.Parse(files[config]); int count = owned.Count; foreach (var table in tables) RemoveOwned(doc, table, r => Guid.TryParse((string)r["RecipeID"], out var rid) && rid == id || table == "LocalImageDatas" && functions.Contains(Guid.Parse((string)r["FuncID"])), owned); if (count != owned.Count) files[config] = Serialize(doc); } } else { if (action == "create") ids.Add(id.ToString()); meta["name"] = (string)after["Name"]; meta["comment"] = (string)after["Comment"]; files[recipePath] = Serialize(meta); } if (action != "update") files[path] = Serialize(manifest); } else { var flows = meta["workflows"].AsArray(); var entry = flows.SingleOrDefault(v => Guid.Parse((string)v["id"]) == id); var script = ScriptPath(owner, id); if (action == "delete") { flows.Remove(entry); files.Remove(script); CheckFlowCode(review, id, targetFlow.Name, script, targetFlow.Code, targetFlow.Code); } else { var header = JsonSerializer.SerializeToNode(new FlowFile(id, (string)after["Name"], (string)after["Comment"], (bool)after["AutomaticExecution"], (double)after["CycleDelayTime"]), Json); if (entry == null) flows.Add(header); else flows[flows.IndexOf(entry)] = header; files[script] = (string)after["Code"]; CheckFlowCode(review, id, name: (string)after["Name"], script, (string)before?["Code"], files[script]); } files[recipePath] = Serialize(meta); } var changes = files.Keys.Union(baseline.Keys).Select(p => new DocumentDelta(p, baseline.GetValueOrDefault(p), files.GetValueOrDefault(p))) .Where(d => d.Before != d.After).ToList(); return WithOwnedImpact(review, owned) with { Destination = files.GetValueOrDefault(path), Documents = changes }; } private static void CheckFlowCode(ObjectEdit edit, Guid id, string name, string path, string before, string after) { var review = WorkflowScriptReview.Create(id, before, after); edit.Workflows.RemoveAll(f => f.Id == id); edit.Workflows.Add(new(id, name, path, review.Compiled, review.Diagnostics)); } private void ApplyStructureEdit(ObjectEdit edit) { bool recipe = edit.Kind == "Recipes"; var row = edit.Before ?? edit.After; Guid owner = recipe ? edit.Id : Guid.Parse((string)row["RecipeID"]); var collection = Flows(owner); var affected = collection.Where(f => recipe ? edit.Action == "delete" : f.ID == edit.Id).ToArray(); if (Recipes.Any(r => r.ID == owner)) { var stored = JsonNode.Parse(baseline[RecipePath(owner)]); var live = Recipes.Single(r => r.ID == owner); if (live.Name != (string)stored["name"] || live.Comment != (string)stored["comment"] || !stored["workflows"].AsArray().Select(n => Guid.Parse((string)n["id"])).SequenceEqual(collection.Select(f => f.ID))) throw new ProjectConflictException("配方或工作流列表有未保存编辑。"); foreach (var f in affected) { var header = stored["workflows"].AsArray().Single(n => Guid.Parse((string)n["id"]) == f.ID); if (f.Name != (string)header["name"] || f.Comment != (string)header["comment"] || f.AutomaticExecution != (bool)header["automaticExecution"] || f.CycleDelayTime != (double)header["cycleDelayTime"] || (f.Code ?? "") != baseline[ScriptPath(owner, f.ID)]) throw new ProjectConflictException("工作流有未保存编辑。"); } } var files = new Dictionary(baseline); foreach (var d in edit.Documents) { if (files.GetValueOrDefault(d.Path) != d.Before) throw new ProjectConflictException("工程文件已改变。"); if (d.After == null) files.Remove(d.Path); else files[d.Path] = d.After; } Workflow.SaveReviewedBatch(affected.Select(f => (f, f.Code ?? "", f.Code ?? "")).ToArray(), () => { using var tx = Data.Database.BeginTransaction(); ApplyOwnedRows(edit.OwnedRows); WriteFiles(Root, files, baseline.Keys.Union(files.Keys).ToArray(), tx.Commit); DetachDeletedRows(edit.OwnedRows); foreach (var d in edit.Documents.Where(d => configuration.ContainsKey(d.Path))) configuration[d.Path] = d.After; if (edit.Action == "delete") foreach (var f in affected) f.Stop(); var manifest = JsonSerializer.Deserialize(files["project.json"], Json); DefaultRecipeId = manifest.DefaultRecipeId; if (recipe && edit.Action == "delete") { Recipes.Remove(Recipes.Single(r => r.ID == owner)); workflows.Remove(owner); } else { var meta = JsonSerializer.Deserialize(files[RecipePath(owner)], Json); if (recipe) { var item = Recipes.SingleOrDefault(r => r.ID == owner); if (item == null) { item = new Recipe { ID = owner }; Recipes.Insert(Array.IndexOf(manifest.Recipes, owner), item); } item.Name = meta.Name; item.Comment = meta.Comment; item.Prompt = ""; } if (!recipe && edit.Action == "delete") collection.Remove(affected.Single()); else foreach (var header in meta.Workflows.Where(h => recipe ? edit.Action == "create" : h.Id == edit.Id)) { var flow = collection.SingleOrDefault(f => f.ID == header.Id); bool add = flow == null; flow ??= new Workflow { ID = header.Id, RecipeID = owner }; flow.Name = header.Name; flow.Comment = header.Comment; flow.CycleDelayTime = header.CycleDelayTime; flow.AutomaticExecution = header.AutomaticExecution; flow.Code = files[ScriptPath(owner, header.Id)]; flow.Prompt = ""; if (add) collection.Insert(Array.IndexOf(meta.Workflows, header), flow); } } }); edit.SavedScope = ObjectScope(); } }