DocEdit.razor 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. @page "/docedit"
  2. @page "/docedit/{docID:int}"
  3. @using System.Reflection;
  4. @using HyperCube.Models;
  5. @using Console = HyperCube.Utils.AdvConsole;
  6. @inject NavigationManager NavigationManager;
  7. @inject IJSRuntime JsRuntime;
  8. @attribute [Authorize]
  9. @*@attribute [Authorize(Roles = "admin")]*@
  10. @inject AuthenticationStateProvider AuthenticationStateProvider
  11. @using Microsoft.AspNetCore.Identity;
  12. @inject UserManager<IdentityUser> UserManager;
  13. <p>
  14. ID транзакции: @transactionId
  15. </p>
  16. <EditForm Model="@articleModel" OnValidSubmit="@HandleValidSubmit">
  17. <DataAnnotationsValidator />
  18. <ValidationSummary />
  19. <h1>@header</h1>
  20. <br>
  21. <div style="width: 50%;">
  22. @if (docID < 1)
  23. {
  24. <p><InputFile id="inputDefault" OnChange="@HandleSelection" accept="application/pdf" /></p>
  25. //accept="application/pdf, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  26. }
  27. else
  28. {
  29. <p>Исходный документ: <a href=@FOLDER_NAME download="@articleModel.Filename" target="_top">@articleModel.Filename</a></p>
  30. }
  31. <p><InputText id="article_name" class="form-control" @bind-Value="articleModel.Name" placeholder="Наименование статьи" /></p>
  32. <p><InputDate id="date_publish" class="form-control" @bind-Value="articleModel.PublishDate" placeholder="Дата издания" /></p>
  33. <p><InputText id="author" class="form-control" @bind-Value="articleModel.Authors" placeholder="Автор" /></p>
  34. <p><InputTextArea id="keywords" class="form-control" @bind-Value="articleModel.Keywords" placeholder="Ключевые слова" /></p>
  35. <p><InputTextArea rows="5" id="annotation" class="form-control" @bind-Value="articleModel.Annotation" placeholder="Аннотация" /></p>
  36. <p><InputTextArea rows="10" id="text" class="form-control" @bind-Value="articleModel.Text" placeholder="Текст" /></p>
  37. @if (docID < 1)
  38. {
  39. <p><button class="btn btn-primary" type="submit">Загрузить</button></p>
  40. }
  41. else
  42. {
  43. <p>
  44. <InputRadioGroup @bind-Value="articleModel.Rating">
  45. Оценка:
  46. <br>
  47. @for (int i = 1; i < 6; i++)
  48. {
  49. <InputRadio Value="i" />
  50. @i
  51. <br />
  52. }
  53. </InputRadioGroup>
  54. </p>
  55. <p>
  56. <button class="btn btn-danger" type="button" @onclick="@Cancel">Отклонить</button>
  57. <button class="btn btn-danger" type="button" @onclick="@Verify">Утвердить</button>
  58. @*<button class="btn btn-primary" type="submit">Утвердить</button>*@
  59. </p>
  60. }
  61. <p>Статус: @status</p>
  62. @*<button class="btn btn-primary" @onclick="() => modal.Open()">Modal!</button>*@
  63. <Modal @ref="modal">
  64. <Title>Результат операции</Title>
  65. <Body>
  66. <p>
  67. ID транзакции: @transactionId
  68. </p>
  69. <p>
  70. Инициатор: <mark>@initiatorAcc.Name</mark> Сумма: овердофига <b>ETH</b><br>
  71. Рейтинг статьи: @articleModel.Rating<br>
  72. </p>
  73. <p>
  74. Верификатор: <mark>@currentAcc.Name</mark> Сумма: овердофига <b>ETH</b><br>
  75. Кол-во исправлений: @editsCount
  76. </p>
  77. <p>
  78. Вознаграждение системы: овердофига <b>ETH</b>.
  79. </p>
  80. </Body>
  81. <Footer>
  82. @*<button type="button" class="btn btn-primary">Save changes</button>*@
  83. <button type="button" class="btn btn-secondary" data-dismiss="modal" @onclick="() => modal.Close()">Закрыть</button>
  84. </Footer>
  85. </Modal>
  86. </div>
  87. </EditForm>
  88. @code {
  89. [Parameter]
  90. public int docID { get; set; }
  91. const string FOLDER_NAME = "articles_storage";
  92. const long MAX_FILE_SIZE = 5120000; //bytes
  93. string transactionId;
  94. ArticleModel articleModelClone = new();
  95. ArticleModel articleModel = new();
  96. AccountModel currentAcc = new();
  97. AccountModel initiatorAcc = new();
  98. string status;
  99. string header;
  100. string storageFolderPath;
  101. MemoryStream memoryStream;
  102. Modal modal { get; set; }
  103. int editsCount;
  104. async Task<string> Verify()
  105. {
  106. try
  107. {
  108. VerifyContract verifyContract = SmartContract.Find("Verify") as VerifyContract;
  109. if (verifyContract != null)
  110. {
  111. Console.WriteLine($"VerifyContract found");
  112. transactionId = await verifyContract.Run(articleModel);
  113. return transactionId;
  114. }
  115. else
  116. Console.WriteLine($"VerifyContract null");
  117. }
  118. catch (Exception e)
  119. {
  120. Console.WriteLine(e.Message + "stack trace" + e.StackTrace);
  121. }
  122. return "Verify failed";
  123. }
  124. protected override async Task OnInitializedAsync()
  125. {
  126. currentAcc = await GetCurrentAcc();
  127. string path = AppDomain.CurrentDomain.BaseDirectory;
  128. storageFolderPath = (Path.Combine(path, FOLDER_NAME));
  129. if (docID > 0)
  130. {
  131. header = "Проверка материала";
  132. MySQLConnector dbCon = MySQLConnector.Instance();
  133. string stringSQL = $"SELECT articles.id, filename, article_name, authors, date_publish, annotation, keywords, action_type, rating " +
  134. $"FROM articles " +
  135. $"JOIN actions_history ON actions_history.article_id = articles.id " +
  136. $"WHERE articles.id={docID} " +
  137. $"ORDER BY actions_history.id DESC LiMIT 1";
  138. articleModelClone = await dbCon.SQLSelectArticle(stringSQL);
  139. articleModel = (ArticleModel)articleModelClone.Clone();
  140. string initiator = await articleModel.GetInitiatorUUID();
  141. initiatorAcc = AccountModel.Find(initiator);
  142. status = $"Article ID={docID} loaded, status: {articleModel.Status}, initiator: {initiatorAcc.Name}";
  143. }
  144. else
  145. header = "Загрузка материала";
  146. InitializeAccount();
  147. //int count = await articleModel.GetEditsCount();
  148. //int countbyid = await articleModel.GetEditsCount(currentAcc.UUID);
  149. //header += $", uuid:{currentAcc.UUID}, name: {currentAcc.Name}, edits count:{count}, count by accid: {countbyid}";
  150. }
  151. private async void HandleValidSubmit()
  152. {
  153. MySQLConnector dbCon = MySQLConnector.Instance();
  154. long id = 0;
  155. string stringSQL;
  156. if (docID > 0)
  157. {
  158. id = docID;
  159. stringSQL = $"UPDATE articles " +
  160. $"SET filename='{articleModel.Filename}', article_name='{articleModel.Name}', authors='{articleModel.Authors}', " +
  161. $"date_publish='{articleModel.PublishDate.ToString("yyyy-MM-dd")}', annotation='{articleModel.Annotation}', " +
  162. $"keywords='{articleModel.Keywords}', rating={articleModel.Rating} " +
  163. $"WHERE id={docID}";
  164. dbCon.SQLInsert(stringSQL);
  165. }
  166. else
  167. {
  168. stringSQL = $"INSERT INTO articles (filename, article_name, authors, date_publish, annotation, keywords) " +
  169. $"VALUES ('{articleModel.Filename}', '{articleModel.Name}', '{articleModel.Authors}', '{articleModel.PublishDate.ToString("yyyy-MM-dd")}'," +
  170. $"'{articleModel.Annotation}', '{articleModel.Keywords}')";
  171. id = dbCon.SQLInsert(stringSQL);
  172. }
  173. ///temp
  174. int action_type = docID > 0 ? 2 : 1;
  175. stringSQL = $"INSERT INTO actions_history (article_id, action_type, acc_id) " +
  176. $"VALUES ('{id}', '{action_type}', '{currentAcc.UUID}')";
  177. dbCon.SQLInsert(stringSQL);
  178. Dictionary<string, PropertyInfo> propDict = Compare.SimpleCompare<ArticleModel>(articleModel, articleModelClone);
  179. foreach (KeyValuePair<string, PropertyInfo> prop in propDict)
  180. {
  181. //Console.WriteLine($"property name: {prop.Key}, value: {prop.Value.GetValue(articleModel, null)}");
  182. stringSQL = $"INSERT INTO articles_edit_log (article_id, acc_id, field_name, field_prevvalue, field_newvalue) " +
  183. $"VALUES ('{id}', '{currentAcc.UUID}', '{prop.Key}', '{prop.Value.GetValue(articleModelClone, null)}', '{prop.Value.GetValue(articleModel, null)}')";
  184. dbCon.SQLInsert(stringSQL);
  185. }
  186. dbCon.Close();
  187. if (docID > 0)
  188. {
  189. status = propDict.Count > 0 ? "All changes saved, article has veryfied." : "Article verifyed without any changes.";
  190. transactionId = await Verify();
  191. Console.WriteLine("transactionId found " + transactionId);
  192. ///tmp
  193. //editsCount = await articleModel.GetEditsCount(currentAcc.UUID);
  194. modal.Open();
  195. }
  196. else
  197. {
  198. string fullpath = Path.Combine(storageFolderPath, $"{id}_{articleModel.Filename}");
  199. Directory.CreateDirectory(storageFolderPath);
  200. FileStream fs = new(fullpath, FileMode.Create, FileAccess.Write);
  201. memoryStream.Position = 0;
  202. await memoryStream.CopyToAsync(fs);
  203. Console.WriteLine($"User has saved new article data, {id}_{articleModel.Filename}, memory size:{memoryStream.Length}b, file size: {fs.Length}b");
  204. memoryStream.Close();
  205. fs.Close();
  206. status = "New article data saved.";
  207. bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Хотите загрузить еще статью?");
  208. if (confirmed)
  209. NavigationManager.NavigateTo("docedit", true);
  210. else
  211. NavigationManager.NavigateTo("");
  212. }
  213. }
  214. private async Task HandleSelection(InputFileChangeEventArgs e)
  215. {
  216. IBrowserFile file = e.File;
  217. if (file != null)
  218. {
  219. Stream stream = file.OpenReadStream(MAX_FILE_SIZE);
  220. memoryStream = new();
  221. await stream.CopyToAsync(memoryStream);
  222. status = $"Finished loading {memoryStream.Length} bytes from {file.Name}";
  223. DocParse docParse = new DocParse();
  224. articleModelClone = DocParse.ReadPDF(memoryStream);
  225. articleModelClone.Filename = file.Name;
  226. articleModel = (ArticleModel)articleModelClone.Clone();
  227. }
  228. }
  229. private async void Cancel()
  230. {
  231. bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Вы уверены, что хотите отклонить статью?");
  232. if (confirmed)
  233. {
  234. ///какая-то логика отмены...
  235. NavigationManager.NavigateTo("");
  236. }
  237. }
  238. public async void InitializeAccount()
  239. {
  240. AccountModel.Current = await GetCurrentAcc();
  241. Console.WriteLine("InitializeAccount in DocEdit " + AccountModel.Current.Name);
  242. }
  243. private async Task<AccountModel> GetCurrentAcc()
  244. {
  245. AccountModel account = new();
  246. var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
  247. var user = authState.User;
  248. if (user.Identity.IsAuthenticated)
  249. {
  250. var currentUser = await UserManager.GetUserAsync(user);
  251. account.UUID = currentUser.Id;
  252. //account.Name = currentUser.UserName;
  253. //account.Email = currentUser.Email;
  254. var acc = AccountModel.Find(account.UUID);
  255. if (acc != null)
  256. account = acc;
  257. ///tmp
  258. account.AccRole = Role.User;
  259. return account;
  260. }
  261. return null;
  262. }
  263. }