123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301 |
- @page "/docedit"
- @page "/docedit/{docID:int}"
- @using System.Reflection;
- @using HyperCube.Models;
- @using Console = HyperCube.Utils.AdvConsole;
- @inject NavigationManager NavigationManager;
- @inject IJSRuntime JsRuntime;
- @attribute [Authorize]
- @*@attribute [Authorize(Roles = "admin")]*@
- @inject AuthenticationStateProvider AuthenticationStateProvider
- @using Microsoft.AspNetCore.Identity;
- @inject UserManager<IdentityUser> UserManager;
- <EditForm Model="@articleModel" OnValidSubmit="@HandleValidSubmit">
- <DataAnnotationsValidator />
- <ValidationSummary />
- <h1>@header</h1>
- <br>
- <div style="width: 50%;">
- @if (docID < 1)
- {
- <p><InputFile id="inputDefault" OnChange="@HandleSelection" accept="application/pdf" /></p>
- //accept="application/pdf, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document"
- }
- else
- {
- <p>Исходный документ: <a href=@FOLDER_NAME download="@articleModel.Filename" target="_top">@articleModel.Filename</a></p>
- }
- <p><InputText id="article_name" class="form-control" @bind-Value="articleModel.Name" placeholder="Наименование статьи" /></p>
- <p><InputDate id="date_publish" class="form-control" @bind-Value="articleModel.PublishDate" placeholder="Дата издания" /></p>
- <p><InputText id="author" class="form-control" @bind-Value="articleModel.Authors" placeholder="Автор" /></p>
- <p><InputTextArea id="keywords" class="form-control" @bind-Value="articleModel.Keywords" placeholder="Ключевые слова" /></p>
- <p><InputTextArea rows="5" id="annotation" class="form-control" @bind-Value="articleModel.Annotation" placeholder="Аннотация" /></p>
- <p><InputTextArea rows="10" id="text" class="form-control" @bind-Value="articleModel.Text" placeholder="Текст" /></p>
- @if (docID < 1)
- {
- <p><button class="btn btn-primary" type="submit">Загрузить</button></p>
- }
- else
- {
- <p>
- <InputRadioGroup @bind-Value="articleModel.Rating">
- Оценка:
- <br>
- @for (int i = 1; i < 6; i++)
- {
- <InputRadio Value="i" />
- @i
- <br />
- }
- </InputRadioGroup>
- </p>
- <p>
- <button class="btn btn-danger" type="button" @onclick="@Cancel">Отклонить</button>
- <button class="btn btn-primary" type="submit">Утвердить</button>
- </p>
- }
- <p>Статус: @status</p>
- @*<button class="btn btn-primary" @onclick="() => modal.Open()">Modal!</button>*@
- <Modal @ref="modal">
- <Title>Результат операции</Title>
- <Body>
- <p>
- ID транзакции: @transactionId
- </p>
- <p>
- Инициатор: <mark>@initiatorAcc.Name</mark> Сумма: @(articleModel.Rating*5) <b>WEI</b><br>
- Рейтинг статьи: @articleModel.Rating<br>
- </p>
- <p>
- Верификатор: <mark>@currentAcc.Name</mark> Сумма: @editsCount <b>WEI</b><br>
- Кол-во исправлений: @editsCount
- </p>
- </Body>
- <Footer>
- @*<button type="button" class="btn btn-primary">Save changes</button>*@
- <button type="button" class="btn btn-secondary" data-dismiss="modal" @onclick="() => modal.Close()">Закрыть</button>
- </Footer>
- </Modal>
- </div>
- </EditForm>
- @code {
- [Parameter]
- public int docID { get; set; }
- const string FOLDER_NAME = "articles_storage";
- const long MAX_FILE_SIZE = 5120000; //bytes
- string transactionId;
- ArticleModel articleModelClone = new();
- ArticleModel articleModel = new();
- AccountModel currentAcc = new();
- AccountModel initiatorAcc = new();
- string status;
- string header;
- string storageFolderPath;
- MemoryStream memoryStream;
- Modal modal { get; set; }
- int editsCount;
- async Task<string> Verify()
- {
- try
- {
- VerifyContract verifyContract = SmartContract.Find("Verify") as VerifyContract;
- if (verifyContract != null)
- {
- Console.WriteLine($"VerifyContract found");
- transactionId = await verifyContract.Run(articleModel);
- return transactionId;
- }
- else
- Console.WriteLine($"VerifyContract null");
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message + "stack trace" + e.StackTrace);
- }
- return "Verify failed";
- }
- protected override async Task OnInitializedAsync()
- {
- currentAcc = await GetCurrentAcc();
- string path = AppDomain.CurrentDomain.BaseDirectory;
- storageFolderPath = (Path.Combine(path, FOLDER_NAME));
- if (docID > 0)
- {
- header = "Проверка материала";
- MySQLConnector dbCon = MySQLConnector.Instance();
- string stringSQL = $"SELECT articles.id, filename, article_name, authors, date_publish, annotation, keywords, action_type, rating " +
- $"FROM articles " +
- $"JOIN actions_history ON actions_history.article_id = articles.id " +
- $"WHERE articles.id={docID} " +
- $"ORDER BY actions_history.id DESC LiMIT 1";
- articleModelClone = await dbCon.SQLSelectArticle(stringSQL);
- articleModel = (ArticleModel)articleModelClone.Clone();
- string initiator = await articleModel.GetInitiatorUUID();
- initiatorAcc = AccountModel.Find(initiator);
- status = $"Article ID={docID} loaded, status: {articleModel.Status}, initiator: {initiatorAcc.Name}";
- }
- else
- header = "Загрузка материала";
- await InitializeAccount();
- //int count = await articleModel.GetEditsCount();
- //int countbyid = await articleModel.GetEditsCount(currentAcc.UUID);
- //header += $", uuid:{currentAcc.UUID}, name: {currentAcc.Name}, edits count:{count}, count by accid: {countbyid}";
- }
- private async Task HandleValidSubmit()
- {
- MySQLConnector dbCon = MySQLConnector.Instance();
- long id = 0;
- string stringSQL;
- if (docID > 0)
- {
- id = docID;
- stringSQL = $"UPDATE articles " +
- $"SET filename='{articleModel.Filename}', article_name='{articleModel.Name}', authors='{articleModel.Authors}', " +
- $"date_publish='{articleModel.PublishDate.ToString("yyyy-MM-dd")}', annotation='{articleModel.Annotation}', " +
- $"keywords='{articleModel.Keywords}', rating={articleModel.Rating} " +
- $"WHERE id={docID}";
- dbCon.SQLInsert(stringSQL);
- }
- else
- {
- stringSQL = $"INSERT INTO articles (filename, article_name, authors, date_publish, annotation, keywords) " +
- $"VALUES ('{articleModel.Filename}', '{articleModel.Name}', '{articleModel.Authors}', '{articleModel.PublishDate.ToString("yyyy-MM-dd")}'," +
- $"'{articleModel.Annotation}', '{articleModel.Keywords}')";
- id = dbCon.SQLInsert(stringSQL);
- }
- ///temp
- int action_type = docID > 0 ? 2 : 1;
- stringSQL = $"INSERT INTO actions_history (article_id, action_type, acc_id) " +
- $"VALUES ('{id}', '{action_type}', '{currentAcc.UUID}')";
- dbCon.SQLInsert(stringSQL);
- Dictionary<string, PropertyInfo> propDict = Compare.SimpleCompare<ArticleModel>(articleModel, articleModelClone);
- foreach (KeyValuePair<string, PropertyInfo> prop in propDict)
- {
- //Console.WriteLine($"property name: {prop.Key}, value: {prop.Value.GetValue(articleModel, null)}");
- stringSQL = $"INSERT INTO articles_edit_log (article_id, acc_id, field_name, field_prevvalue, field_newvalue) " +
- $"VALUES ('{id}', '{currentAcc.UUID}', '{prop.Key}', '{prop.Value.GetValue(articleModelClone, null)}', '{prop.Value.GetValue(articleModel, null)}')";
- dbCon.SQLInsert(stringSQL);
- }
- dbCon.Close();
- if (docID > 0)
- {
- status = propDict.Count > 0 ? "All changes saved, article has veryfied." : "Article verifyed without any changes.";
- transactionId = await Verify();
- Console.WriteLine("transactionId found " + transactionId);
- ///tmp
- editsCount = await articleModel.GetEditsCount(currentAcc.UUID);
- modal.Open();
- }
- else
- {
- string fullpath = Path.Combine(storageFolderPath, $"{id}_{articleModel.Filename}");
- Directory.CreateDirectory(storageFolderPath);
- FileStream fs = new(fullpath, FileMode.Create, FileAccess.Write);
- memoryStream.Position = 0;
- await memoryStream.CopyToAsync(fs);
- Console.WriteLine($"User has saved new article data, {id}_{articleModel.Filename}, memory size:{memoryStream.Length}b, file size: {fs.Length}b");
- memoryStream.Close();
- fs.Close();
- status = "New article data saved.";
- bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Хотите загрузить еще статью?");
- if (confirmed)
- NavigationManager.NavigateTo("docedit", true);
- else
- NavigationManager.NavigateTo("");
- }
- }
- private async Task HandleSelection(InputFileChangeEventArgs e)
- {
- IBrowserFile file = e.File;
- if (file != null)
- {
- Stream stream = file.OpenReadStream(MAX_FILE_SIZE);
- memoryStream = new();
- await stream.CopyToAsync(memoryStream);
- status = $"Finished loading {memoryStream.Length} bytes from {file.Name}";
- DocParse docParse = new DocParse();
- articleModelClone = DocParse.ReadPDF(memoryStream);
- articleModelClone.Filename = file.Name;
- articleModel = (ArticleModel)articleModelClone.Clone();
- }
- }
- private async Task Cancel()
- {
- bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Вы уверены, что хотите отклонить статью?");
- if (confirmed)
- {
- ///какая-то логика отмены...
- NavigationManager.NavigateTo("");
- }
- }
- public async Task InitializeAccount()
- {
- AccountModel.Current = await GetCurrentAcc();
- Console.WriteLine("InitializeAccount in DocEdit " + AccountModel.Current.Name);
- }
- private async Task<AccountModel> GetCurrentAcc()
- {
- AccountModel account = new();
- var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
- var user = authState.User;
- if (user.Identity.IsAuthenticated)
- {
- var currentUser = await UserManager.GetUserAsync(user);
- account.UUID = currentUser.Id;
- //account.Name = currentUser.UserName;
- //account.Email = currentUser.Email;
- var acc = AccountModel.Find(account.UUID);
- if (acc != null)
- account = acc;
- ///tmp
- account.AccRole = Role.User;
- return account;
- }
- return null;
- }
- }
|