ArchiveEventLogServerFunctions.cs
21.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Sungero.Core;
using Sungero.CoreEntities;
using Sungero.Domain.Shared;
using DirRX.Storage.ArchiveEventLog;
using Newtonsoft.Json.Linq;
using Ionic.Zip;
namespace DirRX.Storage.Server
{
partial class ArchiveEventLogFunctions
{
[Remote, Public]
public virtual IZip ExportContainer()
{
return this.ExportContainer(string.Empty);
}
/// <summary>
/// Выгрузить контейнер.
/// </summary>
/// <param name="fileName">Имя выгружаемого zip-файла.</param>
/// <returns>Zip-архив в памяти.</returns>
[Remote, Public]
public virtual IZip ExportContainer(string fileName)
{
if (!_obj.DocumentId.HasValue || _obj.DocumentId.Value == 0)
throw new ApplicationException(ArchiveEventLogs.Resources.ErrorExportContainerFormat(_obj.Id));
if (_obj.DestructionAct != null)
throw new ApplicationException(ArchiveEventLogs.Resources.ErrorDocumentIsDestoryedByActFormat(_obj.DestructionAct.DisplayValue));
var document = Sungero.Content.ElectronicDocuments.GetAll(x => x.Id == _obj.DocumentId).SingleOrDefault();
if (document == null)
throw new ApplicationException(ArchiveEventLogs.Resources.ErrorArchiveDocumentNotFoundFormat(_obj.DocumentId));
if (!document.HasVersions)
throw new ApplicationException(ArchiveEventLogs.Resources.ErrorDocumentNotContainVersionFormat(_obj.DocumentId));
var lastVersion = document.LastVersion;
if (lastVersion.Body.Size == 0)
throw new ApplicationException(ArchiveEventLogs.Resources.ErrorLastVersionIsNullFormat(_obj.DocumentId));
// Сформировать имя файла.
var resultFileName = fileName;
if (string.IsNullOrWhiteSpace(resultFileName))
{
var uid = !string.IsNullOrWhiteSpace(_obj.TempGuid) ? _obj.TempGuid :
(!string.IsNullOrEmpty(_obj.SourceDocumentUid) ? string.Format("{0}_{1}", _obj.SourceSystemUid, _obj.SourceDocumentUid) : _obj.DocumentId.ToString());
resultFileName = string.Format(@"container_{0}", uid);
}
// Извлечь и перепаковать zip-контейнер.
var result = Zip.Create();
// Извлечь файлы из архива, сохраненного в теле документа, средствами внешней библиотеки и добавить в zip-модель RX.
using (var body = lastVersion.Body.Read())
{
// HACK. Без промежуточного копирования тела в память содержимое архива почему-то не распаковывается.
using (var bodyMS = new System.IO.MemoryStream())
{
body.CopyTo(bodyMS);
bodyMS.Position = 0;
using (var zipFile = ZipFile.Read(bodyMS))
{
foreach (var entry in zipFile.Entries)
{
// HACK Распаковка нужна чтобы избавиться от архива внутри другого архива. Но от вложенной папки таким образом избавиться все равно не удается.
using (var entryMS = new System.IO.MemoryStream())
{
entry.Extract(entryMS);
var entryFileName = entry.FileName;
result.Add(entryMS.ToArray(), Path.GetFileNameWithoutExtension(entryFileName), Path.GetExtension(entryFileName), resultFileName);
}
}
// Сохранить zip-модель в хранилище.
result.Save(resultFileName + ".zip");
}
}
}
return result;
}
/// <summary>
/// Сбросить статус "Ошибка".
/// </summary>
[Remote]
public virtual void ResetErrorStatus()
{
if (_obj.CurrentState == CurrentState.Error)
{
_obj.CurrentState = null;
_obj.Message = string.Empty;
}
if (_obj.VerificationResult.HasValue && _obj.VerificationResult.Value != VerificationResult.Succeeded)
{
_obj.JobStartDate = null;
_obj.JobEndDate = null;
_obj.VerificationResult = null;
}
// Очистить временную папку для ЭП и док-в из контейнера, если она не пуста
var folder = DirRX.Storage.PublicFunctions.Module.GetContainerFolder(Path.Combine(DirRX.Storage.Constants.Module.Paths.LTAImproveContainersFolder, _obj.TempGuid));
DirRX.Storage.PublicFunctions.Module.ClearDirectory(folder);
PublicFunctions.ArchiveEventLog.AddEventHistory(_obj, DirRX.Storage.ArchiveEventLogs.Resources.Operation_ResetError,
Storage.ArchiveEventLog.CurrentState.Complete, string.Empty);
if (_obj.State.IsChanged)
_obj.Save();
}
/// <summary>
/// Добавить запись в журнал событий.
/// </summary>
/// <param name="operation">Операция.</param>
/// <param name="state">Статус.</param>
/// <param name="comment">Комментарий.</param>
[Public]
public virtual void AddEventHistory(string operation, Sungero.Core.Enumeration state, string comment)
{
if (_obj != null)
{
var record = _obj.EventHistory.AddNew();
record.DateTime = Calendar.Now;
record.User = Sungero.CoreEntities.Users.Current.Name;
record.Host = System.Net.Dns.GetHostName();
record.Operation = operation;
record.OperState = _obj.Info.Properties.CurrentState.GetLocalizedValue(state);
record.Comment = comment;
_obj.CurrentOperation = operation;
_obj.CurrentState = state;
if (state == Storage.ArchiveEventLog.CurrentState.Error)
_obj.Message = string.Format("{0}. {1}", operation, comment);
else
_obj.Message = string.Empty;
_obj.Save();
}
}
/// <summary>
/// Получить статус обработки в виде json-строки.
/// </summary>
/// <returns>Статус.</returns>
[Public]
public virtual Structures.Module.IResultAnswer GetStatus()
{
var result = Structures.Module.ResultAnswer.Create();
result.Guid = _obj.TempGuid;
if (_obj.DocumentId.HasValue)
{
var document = Sungero.Content.ElectronicDocuments.Get(_obj.DocumentId.Value);
if (document != null)
{
result.Document = Hyperlinks.Get(document);
}
else
{
_obj.CurrentState = Storage.ArchiveEventLog.CurrentState.Error;
_obj.Message += Resources.ErrorLTADocumentNotFoundFormat(_obj.DocumentId, _obj.TempGuid);
_obj.Save();
}
}
result.Status = _obj.CurrentState.ToString();
if (!string.IsNullOrWhiteSpace(_obj.Message))
result.Message = _obj.Message;
return result;
}
/// <summary>
/// Установить дату проверки ДА-контейнера.
/// </summary>
/// <param name="date">Планируемая дата проверки.</param>
public virtual void SetVerificationDate(DateTime date)
{
_obj.VerificationDate = date;
var note = ArchiveEventLogs.Resources.MessageSetVerificationDateFormat(_obj.VerificationDate);
this.AddEventHistory(Storage.ArchiveEventLogs.Resources.Operation_Verification, _obj.CurrentState.Value, note);
}
/// <summary>
/// Выполнить проверку ДА-контейнера.
/// </summary>
/// <returns>Результат проверки (true/false).</returns>
[Public, Remote]
public virtual bool VerifyContainer()
{
// Изменить статус на время обработки.
_obj.CurrentState = CurrentState.InProcess;
_obj.Save();
var errorMessage = string.Empty;
var valid = true;
if (_obj.DestructionAct == null)
{
// --------------------------------------------------
// Проверка наличия контейнера в теле документа.
// --------------------------------------------------
var document = _obj.DocumentId.HasValue ? Sungero.Content.ElectronicDocuments.Get(_obj.DocumentId.Value) : Sungero.Content.ElectronicDocuments.Null;
valid = document != null && document.HasVersions && document.LastVersion.Body.Size > 0;
if (valid)
{
// Сохранить контейнер во временный файл.
var checkFolder = Functions.Module.GetContainerFolder("checks");
var checkFile = string.Format(@"{0}{1}.zip", checkFolder, Guid.NewGuid().ToString());
using (var memory = new System.IO.MemoryStream())
{
document.LastVersion.Body.Read().CopyTo(memory);
File.WriteAllBytes(checkFile, memory.ToArray());
}
valid = ZipFile.IsZipFile(checkFile);
if (valid)
{
// --------------------------------------------------
// Проверка целостности контейнера.
// --------------------------------------------------
var container = Storage.PublicFunctions.Module.LoadContainer(checkFile);
if (container.Valid)
Storage.PublicFunctions.Module.CheckContainer(container);
if (container.Valid)
{
// --------------------------------------------------
// Проверка неизменности контейнера.
// --------------------------------------------------
valid = _obj.Hash == container.Hash;
if (valid)
{
_obj.VerificationResult = VerificationResult.Succeeded;
_obj.Message = null;
}
else
{
_obj.VerificationResult = VerificationResult.HashError;
errorMessage = ArchiveEventLogs.Resources.ErrorHashIsDifferent.ToString();
}
}
else
{
_obj.VerificationResult = VerificationResult.IntegrityError;
errorMessage = container.Message;
}
}
else
{
_obj.VerificationResult = VerificationResult.PresenceError;
errorMessage = ArchiveEventLogs.Resources.ErrorNotZip.ToString();
}
File.Delete(checkFile);
}
else
{
_obj.VerificationResult = VerificationResult.PresenceError;
errorMessage = ArchiveEventLogs.Resources.ErrorContainerNotFound.ToString();
}
}
else
{
// --------------------------------------------------
// Проверка отсутствия тела документа, уничтоженного по акту.
// --------------------------------------------------
var document = _obj.DocumentId.HasValue ? Sungero.Content.ElectronicDocuments.GetAll(x => x.Id == _obj.DocumentId.Value).SingleOrDefault() : Sungero.Content.ElectronicDocuments.Null;
valid = document == null || !document.HasVersions;
if (valid)
{
_obj.VerificationResult = VerificationResult.Succeeded;
_obj.Message = null;
}
else
{
_obj.VerificationResult = VerificationResult.PresenceError;
errorMessage = ArchiveEventLogs.Resources.ErrorBodyNotDestroyed.ToString();
}
}
_obj.JobEndDate = Calendar.Now;
if (errorMessage == string.Empty)
{
this.AddEventHistory(Storage.ArchiveEventLogs.Resources.Operation_Verification, CurrentState.Complete, ArchiveEventLogs.Resources.MessageSuccessfullyCompleted.ToString());
}
else
{
var note = string.Format("Storage.ArchiveEventLogFunctions.VerifyContainer(). {0}. {1}", _obj.Info.Properties.VerificationResult.GetLocalizedValue(_obj.VerificationResult), errorMessage);
this.AddEventHistory(Storage.ArchiveEventLogs.Resources.Operation_Verification, CurrentState.Error, note);
}
return valid;
}
/// <summary>
/// Импортировать ДА-контейнер.
/// </summary>
/// <param name="hash">Хэш контейнера, переданный системой источником в запросе.</param>
public virtual void ImportContainer(string hash)
{
Logger.DebugFormat("Storage.ArchiveEventLogFunctions.ImportContainer(). Обработка журнала ИД {0}. Hash {1}", _obj.Id, hash);
var operationImport = Storage.ArchiveEventLogs.Resources.Operation_Import.ToString();
// Извлечь данные из zip-архива.
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.InProcess, ArchiveEventLogs.Resources.MessageExtractingMetadata.ToString());
var container = Storage.PublicFunctions.Module.LoadContainer(_obj.FilePath);
// Проверить по журналу не был ли документ принят ранее.
if (container.Valid)
{
_obj.Name = container.DocumentName;
_obj.SourceSystemUid = container.SourceUid;
_obj.SourceDocumentUid = container.DocumentUid;
_obj.Metadata = container.Metadata;
_obj.Type = container.Type;
_obj.Hash = container.Hash;
_obj.Save();
container.EventId = _obj.Id;
var duplicate = ArchiveEventLogs.GetAll(x => x.Id != _obj.Id &&
x.SourceSystemUid == container.SourceUid &&
x.SourceDocumentUid == container.DocumentUid &&
(x.DocumentId.HasValue ||
x.CurrentState != Storage.ArchiveEventLog.CurrentState.Error))
.FirstOrDefault();
if (duplicate != null)
{
// Если есть дубль, записать в его журнал инфо о попытке повторного импорта.
Functions.ArchiveEventLog.AddEventHistory(duplicate, operationImport, duplicate.CurrentState.Value, ArchiveEventLogs.Resources.MessageAttemptingReImportFormat(_obj.TempGuid));
container.Message = duplicate.DocumentId.HasValue ?
Resources.ErrorContainerAlreadyAcceptedFormat(duplicate.DocumentId.Value) :
Resources.ErrorContainerAlreadуInProcessFormat(duplicate.TempGuid);
container.Valid = false;
}
}
// Проверить совпадают ли хэши.
if (container.Valid)
{
if (string.IsNullOrEmpty(hash))
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.InProcess, ArchiveEventLogs.Resources.MessageHashFormat(_obj.Hash));
else
{
if (hash.ToLower() != _obj.Hash.ToLower())
{
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.Error, ArchiveEventLogs.Resources.ErrorHashMatching.ToString());
container.Message = Resources.ErrorContainerHash;
container.Valid = false;
}
else
{
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.InProcess, ArchiveEventLogs.Resources.MessageHashOkFormat(_obj.Hash));
}
}
}
// Определить дату улучшения ЭП.
if (container.Valid)
{
var improveDateError = Functions.Module.SetNextImproveDate(_obj);
if (!string.IsNullOrEmpty(improveDateError))
{
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.Error, improveDateError);
container.Message = improveDateError;
container.Valid = false;
}
}
// Проверить данные контейнера.
if (container.Valid)
{
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.InProcess, ArchiveEventLogs.Resources.MessageCheckContainer.ToString());
Storage.PublicFunctions.Module.CheckContainer(container);
}
// Синхронизировать реквизиты контейнера.
if (container.Valid)
{
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.InProcess, ArchiveEventLogs.Resources.MessageSynchronizeRequisites.ToString());
container.Requisites = Storage.PublicFunctions.Module.SynchronizeRequisites(container);
if (container.Requisites != null)
{
foreach (var requisite in container.Requisites)
{
var item = _obj.Details.AddNew();
item.ExternalName = requisite.ExternalName;
item.ExternalType = requisite.ExternalUid;
item.ExternalValue = requisite.ExternalValue;
item.EntityType = requisite.EntityType;
item.EntityId = requisite.EntityId;
item.DocumentValue = item.ExternalValue;
}
}
}
// Создать ДА-документ.
if (container.Valid)
{
if (_obj.ArchiveIsModule != true)
{
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.InProcess, ArchiveEventLogs.Resources.MessageCreateDocument.ToString());
var documentCreatingResult = Storage.PublicFunctions.Module.CreateLTADocument(container);
if (documentCreatingResult != null && documentCreatingResult.ErrorMessage == null)
{
_obj.DocumentId = documentCreatingResult.Id;
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.Complete, ArchiveEventLogs.Resources.MessageCreateDocumentFormat(_obj.DocumentId));
}
else
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.Error, ArchiveEventLogs.Resources.ErrorDocumentCreationFormat(documentCreatingResult.ErrorMessage));
}
else
{
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.InProcess, ArchiveEventLogs.Resources.MessageSaveInSourceSystem);
var error = Functions.Module.CreateLTADocumentVersion(container);
if (error == string.Empty)
{
_obj.DocumentId = int.Parse(_obj.SourceDocumentUid);
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.Complete, "Версия в исходной системе создана");
}
else
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.Error, error);
}
// Запланировать проверку документа.
if (_obj.CurrentState != Storage.ArchiveEventLog.CurrentState.Error)
{
var term = (int)Sungero.Docflow.PublicFunctions.Module.Remote.GetDocflowParamsNumbericValue(Constants.Module.DocflowParams.VerificationIntervalKey);
_obj.VerificationDate = _obj.Created.Value.AddDays(term);
}
else
{
container.Valid = false;
container.Message = _obj.Message;
}
}
else
this.AddEventHistory(operationImport, Storage.ArchiveEventLog.CurrentState.Error, container.Message);
// Удалить временный файл контейнера.
if (!string.IsNullOrWhiteSpace(_obj.FilePath) && File.Exists(_obj.FilePath))
{
if (!container.Valid)
{
// Переместить файл в папку с ошибочными контейнерами.
var errorFolder = PublicFunctions.Module.GetContainerFolder("errors");
var errorFilePath = Path.Combine(errorFolder,Path.GetFileName(_obj.FilePath));
File.Copy(_obj.FilePath, errorFilePath);
File.Delete(_obj.FilePath);
_obj.FilePath = errorFilePath;
}
else
{
File.Delete(_obj.FilePath);
_obj.FilePath = string.Empty;
}
}
_obj.Save();
}
/// <summary>
/// Синхронизировать свойства архивного документа.
/// </summary>
[Public]
public virtual void SynchronizeArchiveDocumentProperties()
{
try
{
var document = Storage.ArchiveDocumentBases.Get(_obj.DocumentId.Value);
var properties = document.GetType().GetProperties();
var syncCount = 0;
foreach (var item in _obj.Details)
{
var property = properties.Where(x => x.Name.ToLower() == item.ExternalName.ToLower()).FirstOrDefault();
if (property != null)
{
var oldValue = item.DocumentValue;
var newValue = Sungero.Commons.PublicFunctions.Module.GetValueAsString(property.GetValue(document));
if (oldValue != newValue)
{
item.DocumentValue = newValue;
syncCount++;
Logger.DebugFormat("SynchronizeArchiveDocumentProperties(). Изменено значение свойства {0} с {1} на {2}.", property.Name, oldValue, newValue);
}
}
}
if (_obj.State.IsChanged)
_obj.Save();
else
Logger.Debug("SynchronizeArchiveDocumentProperties(). Значения синхронизируемых свойств не изменились.");
}
catch (Exception e)
{
Logger.DebugFormat("Ошибка синхронизации свойств документа ИД {0}: \n{1}", _obj.DocumentId, e.Message);
}
}
}
}