plcsharp/PLCSharpWpf/Models/ProjectBatch.cs

204 lines
11 KiB
C#

using Microsoft.EntityFrameworkCore;
using PLCSharp.VVMs.Recipe;
using PLCSharp.VVMs.Workflows;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
namespace PLCSharp.Models;
public sealed record ProjectBatch(List<ProjectChange> Steps, List<CheckedFlow> Workflows, string[] ChangedFiles, Guid? UndoOf = null)
{
public bool Compiled => Steps.All(s => s.Status == "pending") && Workflows.All(f => f.Compiled);
[JsonIgnore] internal Dictionary<string,string> From { get; init; }
[JsonIgnore] internal Dictionary<string,string> To { get; init; }
[JsonIgnore] internal Dictionary<string,byte[]> OriginalBytes { get; init; }
[JsonIgnore] internal List<ObjectEdit> Rows { get; init; }
}
public sealed partial class ProjectDirectory
{
internal ProjectBatch PlanBatch(JsonArray operations)
{
if (operations == null || operations.Count == 0) throw new ArgumentException("批次不能为空。");
var temp = Directory.CreateTempSubdirectory("plcsharp-preview-");
try
{
foreach (var (path, value) in baseline)
{
string full = ProjectFile(temp.FullName, path);
Directory.CreateDirectory(Path.GetDirectoryName(full));
File.WriteAllText(full, value);
}
using var stage = Open(temp.FullName);
var before = stage.BatchRows();
var aliases = new Dictionary<string, Guid>();
var preview = new ProjectChanges();
var steps = new List<ProjectChange>();
foreach (var input in operations)
{
var args = input.DeepClone().AsObject();
void Resolve(JsonObject obj, string key)
{
if (obj?[key] is JsonValue v && v.TryGetValue<string>(out var s) && s.StartsWith('$'))
obj[key] = aliases.TryGetValue(s[1..], out var id) ? id.ToString() : throw new ArgumentException($"未知批次对象 {s}");
}
Resolve(args, "id");
foreach (string field in new[]{"RecipeID","RobotID","FuncID"}) Resolve(args["properties"]?.AsObject(), field);
var operation = (string)args["action"] == "rename" ? "previewObjectRename" : "previewObjectEdit";
var result = preview.Execute(stage, operation, args, false);
var draft = preview.PendingOrInvalid(Guid.Parse((string)result["DraftId"]));
steps.Add(draft);
if (draft.Status == "invalid") break;
if ((string)args["alias"] is string alias && !aliases.TryAdd(alias,draft.ObjectId)) throw new ArgumentException("批次别名重复。");
if (draft.Edit != null) stage.ApplyObjectEdit(draft.Edit);
else stage.ApplyRename(draft.Rename);
}
var paths = baseline.Keys.Union(stage.baseline.Keys).Where(p => baseline.GetValueOrDefault(p) != stage.baseline.GetValueOrDefault(p)).ToArray();
var after = stage.BatchRows();
var rows = new List<ObjectEdit>();
foreach (var key in before.Keys.Union(after.Keys))
{
var old = before.GetValueOrDefault(key);
var next = after.GetValueOrDefault(key);
if (JsonNode.DeepEquals(old,next)) continue;
rows.Add(new(old == null ? "create" : next == null ? "delete" : "update",key.Kind,key.Id,"",old,next,[],[],[],[]));
}
var flows = steps.SelectMany(s => s.Edit?.Workflows ?? s.Rename.Scripts.Select(f => new CheckedFlow(f.Id,f.Name,f.Path,f.Review.Compiled,f.Review.Diagnostics)).ToList())
.GroupBy(f=>f.Id).Select(g=>g.Last()).ToList();
foreach (var flow in flows.ToArray())
{
if (after.GetValueOrDefault(("Workflows",flow.Id)) is not { } row) continue;
var check = WorkflowScriptReview.Create(flow.Id, (string)row["Code"], (string)row["Code"]);
flows[flows.IndexOf(flow)] = flow with { Compiled = check.Compiled, Diagnostics = check.Diagnostics };
}
return new(steps,flows,paths) { From = new(baseline), To = new(stage.baseline), Rows = rows,
OriginalBytes = paths.Where(baseline.ContainsKey).ToDictionary(p=>p,p=>File.ReadAllBytes(ProjectFile(Root,p))) };
}
finally { temp.Delete(true); }
}
private Dictionary<(string Kind, Guid Id),JsonObject> BatchRows()
{
var rows = new Dictionary<(string,Guid),JsonObject>();
foreach (var recipe in Recipes)
{
rows.Add(("Recipes",recipe.ID),RecipeRow(recipe));
foreach (var flow in Flows(recipe.ID)) rows.Add(("Workflows",flow.ID),FlowRow(flow));
}
foreach (var (group,tables) in ProjectConfiguration.Groups)
{
var doc = JsonNode.Parse(configuration[ConfigPath(group)]);
foreach (var table in tables)
foreach (var row in doc[table].AsArray()) rows.Add((table,Guid.Parse((string)row["ID"])),row.AsObject());
}
return rows;
}
internal ProjectBatch UndoBatch(Guid id, ProjectBatch batch)
{
CheckBatchState(batch.To);
var restoredFlows = new List<CheckedFlow>();
foreach (var flow in batch.Workflows)
{
if (!batch.From.TryGetValue(flow.Path, out var code)) continue;
var review = WorkflowScriptReview.Create(flow.Id, batch.To.GetValueOrDefault(flow.Path), code);
restoredFlows.Add(flow with { Compiled = review.Compiled, Diagnostics = review.Diagnostics });
}
return batch with { From = batch.To, To = batch.From, UndoOf = id, Workflows = restoredFlows,
Rows = batch.Rows.AsEnumerable().Reverse().Select(e=>e with { Before=e.After, After=e.Before,
Action=e.Action=="update"?"update":e.Action=="create"?"delete":"create" }).ToList() };
}
private void CheckBatchState(Dictionary<string,string> expected)
{
if (!baseline.OrderBy(p=>p.Key).SequenceEqual(expected.OrderBy(p=>p.Key)))
throw new ProjectConflictException("工程已经改变,请重新预览整批操作。");
}
internal void ApplyBatch(ProjectBatch batch)
{
lock (Data.Sync)
{
CheckBatchState(batch.From);
var previousManifest = JsonSerializer.Deserialize<Manifest>(batch.From["project.json"], Json);
if (!Recipes.Select(r => r.ID).SequenceEqual(previousManifest.Recipes) || DefaultRecipeId != previousManifest.DefaultRecipeId)
throw new ProjectConflictException("配方列表有未保存修改。");
foreach (var rid in previousManifest.Recipes)
{
var order = JsonSerializer.Deserialize<RecipeFile>(batch.From[RecipePath(rid)], Json).Workflows;
if (!Flows(rid).Select(f => f.ID).SequenceEqual(order.Select(f => f.Id)))
throw new ProjectConflictException("工作流列表有未保存修改。");
}
var current = BatchRows();
var configRows = batch.Rows.Where(r=>r.Kind is not ("Workflows" or "Recipes")).ToList();
var touched = configRows.Select(r=>(r.Kind,r.Id)).ToHashSet();
var tracked = Data.ChangeTracker.Entries().Where(e=>e.Metadata.FindProperty("ID")?.ClrType==typeof(Guid) &&
touched.Contains((e.Metadata.GetTableName(),(Guid)e.Property("ID").CurrentValue))).ToArray();
if (tracked.Any(e=>e.State!=EntityState.Unchanged) || batch.Rows.Any(r=>!JsonNode.DeepEquals(current.GetValueOrDefault((r.Kind,r.Id)),r.Before)))
throw new ProjectConflictException("批次涉及的对象有未保存修改。");
var flowRows = batch.Rows.Where(r=>r.Kind=="Workflows").ToList();
var gates = flowRows.Where(r=>r.Before!=null).Select(r=>(Flows(Guid.Parse((string)r.Before["RecipeID"])).Single(f=>f.ID==r.Id),
(string)r.Before["Code"], (string)(r.After??r.Before)["Code"])).ToArray();
Workflow.SaveReviewedBatch(gates, () =>
{
using var tx = Data.Database.BeginTransaction();
foreach (var row in configRows)
{
if (row.After == null)
{
if (Data.Database.ExecuteSqlRaw($"DELETE FROM \"{row.Kind}\" WHERE ID = {{0}}",row.Id)!=1)
throw new ProjectConflictException("配置记录已改变。");
}
else ProjectConfiguration.Restore(Data,[row.Kind],new(){[row.Kind]=new JsonArray(row.After.DeepClone())},row.Before!=null);
}
var expectedBytes = batch.UndoOf.HasValue ? batch.ChangedFiles.Where(batch.From.ContainsKey)
.ToDictionary(p=>p,p=>Encoding.UTF8.GetBytes(batch.From[p])) : batch.OriginalBytes;
WriteFiles(Root,new(batch.To),batch.From.Keys.Union(batch.To.Keys).ToArray(),tx.Commit,
batch.UndoOf.HasValue ? batch.OriginalBytes : null, expectedBytes);
foreach (var entry in tracked) entry.Reload();
foreach (string path in configuration.Keys.ToList()) configuration[path]=baseline[path];
var manifest=JsonSerializer.Deserialize<Manifest>(baseline["project.json"],Json);
DefaultRecipeId=manifest.DefaultRecipeId;
foreach (var row in flowRows)
{
var collection=Flows(Guid.Parse((string)(row.After??row.Before)["RecipeID"]));
var flow=collection.SingleOrDefault(f=>f.ID==row.Id);
if (row.After==null) { flow.Stop(); collection.Remove(flow); continue; }
var a=row.After;
bool add=flow==null;
flow??=new Workflow { ID=row.Id, RecipeID=Guid.Parse((string)a["RecipeID"]) };
flow.Name=(string)a["Name"]; flow.Comment=(string)a["Comment"]; flow.Code=(string)a["Code"];
flow.CycleDelayTime=(double)a["CycleDelayTime"]; flow.AutomaticExecution=(bool)a["AutomaticExecution"]; flow.Prompt="";
if (add) collection.Add(flow);
}
foreach (var row in batch.Rows.Where(r=>r.Kind=="Recipes"))
{
var recipe=Recipes.SingleOrDefault(r=>r.ID==row.Id);
if(row.After==null) { Recipes.Remove(recipe); workflows.Remove(row.Id); continue; }
bool add=recipe==null;
recipe??=new Recipe { ID=row.Id };
recipe.Name=(string)row.After["Name"]; recipe.Comment=(string)row.After["Comment"]; recipe.Prompt="";
if(add) Recipes.Add(recipe);
}
for(int i=0;i<manifest.Recipes.Length;i++)
{
var rid=manifest.Recipes[i];
var index=Recipes.IndexOf(Recipes.Single(r=>r.ID==rid));
if(index!=i) Recipes.Move(index,i);
var list=Flows(rid);
var order=JsonSerializer.Deserialize<RecipeFile>(baseline[RecipePath(rid)],Json).Workflows;
for(int j=0;j<order.Length;j++)
{
int at=list.IndexOf(list.Single(f=>f.ID==order[j].Id));
if(at!=j) list.Move(at,j);
}
}
});
}
}
}