import { FileRestService, IFolderInfo, IFileInFolderInfo } from 'isogd-file-rest'; import { IBpmRestService, IUpdateTaskPutData, ITaskVariable } from 'oasi-bpm-rest'; import { LoadingStatus, AlertService } from 'oasi-widgets'; import { OrderDocument, OrderDocumentRestService, OrderDocumentWrapper } from 'orders-rest'; import { NsiRestService, NSIInstructionStatus, NSIInstructionPriority } from 'oasi-nsi-rest'; import { ActivityProcessHistoryManager } from 'oasi-bpm-history'; import * as _ from 'lodash'; import * as angular from 'angular'; import * as jsonpatch from 'fast-json-patch'; import { ISessionStorage } from 'oasi-security'; import { OasiSolarRestService } from 'oasi-solar-rest'; import { SearchExtData } from 'oasi-solar-rest'; import { SearchExtDataItem } from 'oasi-solar-rest'; import { SearchResult } from 'oasi-solar-rest'; import { SearchResultDocument } from 'oasi-solar-rest'; import { InstructionExecutor } from '../models/InstructionExecutor'; class OrderCardController { private document: OrderDocument; private loadingStatus: LoadingStatus = LoadingStatus.LOADING; private _blockUI: angular.blockUI.BlockUIService; private login: string; private id: string; private init: any; private log: any[]; private folderInfo: IFolderInfo; private statuses: NSIInstructionStatus[]; private subTasks: SearchResultDocument[]; private parentDocument: OrderDocument; private priority: NSIInstructionPriority[]; private executors: any[]; private showSubTask: boolean; private showDelete: boolean; static $inject = ['$stateParams', 'oasiSolarRestService', 'alertService', 'session', '$uibModal', 'activityProcessHistoryManager', '$timeout', 'blockUI', 'fileRestService', 'activityRestService', '$q', 'nsiRestService', 'orderDocumentRestService', '$state', 'toastr']; constructor(private $stateParams: ng.ui.IStateParamsService, private oasiSolarRestService: OasiSolarRestService, private alertService: AlertService, private session: ISessionStorage, private $uibModal: ng.ui.bootstrap.IModalService, private activityProcessHistoryManager: ActivityProcessHistoryManager, private $timeout: ng.ITimeoutService, private blockUI: any, private fileRestService: FileRestService, private activityRestService: IBpmRestService, private $q: ng.IQService, private nsiRestService: NsiRestService, private orderDocumentRestService: OrderDocumentRestService, private $state: ng.ui.IStateService, private toastr: Toastr) { } edit() { let modalInstance = this.$uibModal.open({ template: require('../editOrder/editOrder.html'), controller: 'EditOrderController as $ctrl', backdrop: 'static', keyboard: false, size: 'lg', resolve: { document: () => { return angular.copy(this.document); }, login: () => { return this.login; }, folderInfo: () => { return this.folderInfo; } } }); modalInstance.result.then((result: any) => { let editedDocument: OrderDocument = result.document; let files: IFileInFolderInfo[] = result.files; let filesForDownloding: File[] = result.filesForDownloding; let id = (editedDocument.instruction.fileId.length > 0 && files.length === 0) ? editedDocument.instruction.fileId[0] : null; this._blockUI.start(); let _f = this.getFileByIds(editedDocument.instruction.fileId); let name = (_f.length > 0) ? _f[0].fileName : undefined; this.deleteFile(id, name).then(response => { if (id) { editedDocument.instruction.fileId = []; } return this.saveFile(filesForDownloding, editedDocument.folderId); }).then(resp => { if (resp) { editedDocument.instruction.fileId.push(resp); } return this.updateTask(editedDocument); }).then(response => { return this.updateProcess(editedDocument); }).then(response => { let left = new OrderDocumentWrapper(); left.document = this.document.min(); let right = new OrderDocumentWrapper(); right.document = editedDocument.min(); let diff: any = JSON.stringify(jsonpatch.compare(left, right)); return this.orderDocumentRestService.patch(this.document.documentId, diff); }).then(response => { this.toastr.success('Документ успешно сохранен!'); this._blockUI.stop(); this.$state.reload(); }).catch(error => { console.log(error); this.toastr.error('Ошибка при изменении документа!!'); this._blockUI.stop(); }); // tslint:disable-next-line:no-empty }).catch(error => { }); } buildTime(date): string { let result = date; result += 'T23:59:00.000'; let _date = new Date(result); let pad = (value) => { return value < 10 ? '0' + value : value; }; let createOffset = (date) => { let sign = (date.getTimezoneOffset() > 0) ? '-' : '+'; let offset = Math.abs(date.getTimezoneOffset()); let hours = pad(Math.floor(offset / 60)); let minutes = pad(offset % 60); return sign + hours + ':' + minutes; }; let offset = createOffset(_date); result += offset; return result; } updateProcess(editedDocument: OrderDocument): ng.IPromise { let defer: ng.IDeferred = this.$q.defer(); let executor = (this.document.instruction.executor.login !== editedDocument.instruction.executor.login) ? editedDocument.instruction.executor.login : null; let planDate = (this.document.instruction.planDate.toString() !== editedDocument.instruction.planDate.toString()) ? editedDocument.instruction.planDate : null; let p = this.init.processes[this.init.processes.length - 1]; let id = p.tasks[ p.tasks.length - 1].id; if (executor === null && planDate === null) { defer.resolve(null); } else { let p = this.init.processes[this.init.processes.length - 1]; let id = p.id; let vars: ITaskVariable[] = []; if (executor) { vars.push({ name: 'ResponsibleExecutor_VAR', value: executor }); } if (planDate) { vars.push({ name: 'TaskTime_VAR', value: (this.buildTime(editedDocument.min().instruction.planDate)) }); } this.activityRestService.updateProcessVars(id, vars).then(response => { this.toastr.success('Состояние процесса успешно изменено!'); defer.resolve(); }).catch(error => { defer.reject(error); }); } return defer.promise; } updateTask(editedDocument: OrderDocument): ng.IPromise { let defer: ng.IDeferred = this.$q.defer(); let executor = (this.document.instruction.executor.login !== editedDocument.instruction.executor.login) ? editedDocument.instruction.executor.login : null; let planDate = (this.document.instruction.planDate.toString() !== editedDocument.instruction.planDate.toString()) ? editedDocument.instruction.planDate : null; let p = this.init.processes[this.init.processes.length - 1]; let id = p.tasks[ p.tasks.length - 1].id; let account = p.tasks[ p.tasks.length - 1].assigne.account; if ((executor === null && planDate === null) || this.session.login() === account) { defer.resolve(null); } else { let p = this.init.processes[this.init.processes.length - 1]; let id = p.tasks[ p.tasks.length - 1].id; let updateTaskPutData: IUpdateTaskPutData = { }; if (executor) { updateTaskPutData['assignee'] = executor; } if (planDate) { updateTaskPutData['dueDate'] = (this.buildTime(editedDocument.min().instruction.planDate)); } this.activityRestService.updateTask(id, updateTaskPutData).then(response => { this.toastr.success('Состояние задачи успешно изменено!'); defer.resolve(); }).catch(error => { defer.reject(error); }); } return defer.promise; } saveFile(files: File[], folderId: string): ng.IPromise { let defer: ng.IDeferred = this.$q.defer(); if (files.length > 0) { let fd = new FormData(); let _file = files[0]; fd.append('file', _file); fd.append('folderGuid', folderId); fd.append('fileType', 'MkaDocOrder'); this.fileRestService.handleFileUpload(fd).then(response => { this.toastr.success('Файл ' + files[0].name + ' успешно загружен!'); defer.resolve(response.guid); }).catch(error => { defer.reject(error); }); } else { defer.resolve(null); } return defer.promise; } deleteFile(id: string, name?: string): ng.IPromise { let defer: ng.IDeferred = this.$q.defer(); if (id) { this.fileRestService.deleteFile(id).then(response => { this.toastr.success('Файл ' + name + ' успешно удален!'); defer.resolve(); }).catch(error => { defer.reject(error); }); } else { defer.resolve(null); } return defer.promise; } delete() { let modalInstance = this.$uibModal.open({ template: require('../cancel/cancel.html'), controller: 'СancellController as $ctrl', backdrop: 'static', keyboard: false, size: 'md' }); modalInstance.result.then(response => { this._blockUI.start(); let documentCopy = angular.copy(this.document); let status = (response === 'Отменено') ? _.find(this.statuses, s => { return s.code === 'refused'; }) : _.find(this.statuses, s => { return s.code === 'notExecuted'; }); this.document.statusId.code = status.code; this.document.statusId.name = status.name; this.document.statusId.color = status.color; this.document.instruction.factDate = new Date(); let left = new OrderDocumentWrapper(); left.document = documentCopy.min(); let right = new OrderDocumentWrapper(); right.document = this.document.min(); let diff: any = JSON.stringify(jsonpatch.compare(left, right)); this.orderDocumentRestService.patch(this.document.documentId, diff).then(response => { this.toastr.success('Документ успешно сохранен!'); let processId = this.init.processes[this.init.processes.length - 1].processInstanceId; return this.activityRestService.deleteProcess(processId); }).then(response => { this.toastr.success('Процесс успешно удален!'); return this.orderDocumentRestService.notify(this.document.documentId); }).then(response => { this.toastr.success('Письмо с уведомлением отправлено!'); this.$state.reload(); }).catch(error => { console.log(error); this.toastr.error('Ошибка в процессе снятия поручения!!'); this._blockUI.stop(); this.$state.reload(); }); }); } $onInit() { this._blockUI = this.blockUI.instances.get('cardOrder'); this.nsiRestService.get('OasiInstructionStatus').then(response => { this.statuses = response; return this.nsiRestService.get('OasiInstructionPriority'); }).then(response => { this.priority = response; return this.nsiRestService.get('OasiInstructionExecutors'); }).then(response => { this.executors = response; return this.orderDocumentRestService.get(this.id); }).then(response => { this.document = new OrderDocument(response.document); return this.loadProcessHistory(this.document); }).then(response => { this.init = response; if (this.document.folderId) { return this.fileRestService.getFullFolderInfo(this.document.folderId, false); } else { this.$q.when(null); } }).then(response => { this.folderInfo = response; return this.orderDocumentRestService.log(this.document.documentId); }).then(response => { this.log = response; return this.getSubTasks(); }).then(response => { this.subTasks = response; return this.getParentTask(); }).then(response => { this.parentDocument = response; let isAssistant = false; let e = _.find(this.executors, e => { return e.creator === this.document.instruction.executor.login; }); if (e) { let a = _.find(e.assistant, a => { return a === this.login; }); if (a) { isAssistant = true; } } this.showSubTask = (!this.document.parentId) && (this.document.instruction.executor.login === this.login || isAssistant) && !this.document.instruction.factDate && (this.document.statusId.code === 'inwork' || this.document.statusId.code === 'check'); this.showDelete = (this.document.instruction.creator.login === this.login) && !this.document.instruction.factDate && (this.document.statusId.code === 'inwork' || this.document.statusId.code === 'check'); this.loadingStatus = LoadingStatus.SUCCESS; }).catch(error => { this.loadingStatus = LoadingStatus.ERROR; }); } private getParentTask(): ng.IPromise { let defer: ng.IDeferred = this.$q.defer(); if (this.document.parentId) { this.orderDocumentRestService.get(this.document.parentId).then(response => { defer.resolve(response.document); }).catch(error => { defer.reject(error); }); } else { defer.resolve(null); } return defer.promise; } private getSubTasks(): ng.IPromise { let deferred: ng.IDeferred = this.$q.defer(); let _fields = []; _fields.push(new SearchExtDataItem('parentIdInst', this.document.documentId)); this.oasiSolarRestService.searchExt({ page: 0, pageSize: 10000, fields: _fields }).then(response => { deferred.resolve(response.docs); }, () => { deferred.reject(); }); return deferred.promise; } loadProcessHistory(document: any): ng.IPromise { let deferred: ng.IDeferred = this.$q.defer(); let categories: any[] = []; categories.push({ name: 'Исполнение поручения', key: 'assign_', compareType: 'startsWith' }); let defaulVars: any[] = []; defaulVars.push({ name: 'EntityIdVar', value: this.document.documentId }); defaulVars.push({ name: 'ResponsibleExecutor_VAR', value: this.document.instruction.executor.login }); this.activityProcessHistoryManager.init('assign', categories, this.document.documentId, 'EntityIdVar', defaulVars).then(response => { deferred.resolve(response); }, () => { deferred.reject(); }); return deferred.promise; } openDiagram(id: string, type: any, name: string) { window.open(this.activityProcessHistoryManager.getDiagram(id, type), '_blank'); } getFileByIds(ids: string[]): IFileInFolderInfo[] { return _.filter(this.folderInfo.files, f => { return _.findIndex(ids, i => { return i === f.versionSeriesGuid; }) !== -1; }); } } export const OrderCardComponent: angular.IComponentOptions = { controller: OrderCardController, template: require('./orderCard.html'), bindings: { login: '<', id: '<' } };