import { NSIRegistrationStatus, NsiRestService, NSIInstructionDifficulty, NSIInstructionExecutor, NSIInstructionPriority, NSIThematicHeading, NSIInstructionStatus, UserBean } from 'oasi-nsi-rest'; import { OrderDocumentRestService, OrderDocument, OrderDocumentWrapper } from 'orders-rest'; import { LoadingStatus } from 'oasi-widgets'; import * as _ from 'lodash'; import { InstructionExecutor } from '../models/InstructionExecutor'; import { NewOrderModel } from '../models/NewOrderModel'; import * as angular from 'angular'; import { IBpmRestService } from 'oasi-bpm-rest'; import { FileRestService } from 'isogd-file-rest'; import * as jsonpatch from 'fast-json-patch'; class NewOrderController { private document: OrderDocument; private parentDocument: OrderDocument; private loadingStatus: LoadingStatus = LoadingStatus.LOADING; private creators: InstructionExecutor[]; private theme: any; private priority: NSIInstructionPriority[]; private difficulty: NSIInstructionDifficulty[]; private login: string; private executors: InstructionExecutor[]; private model: NewOrderModel; private _blockUI: angular.blockUI.BlockUIService; private _blockSearching: angular.blockUI.BlockUIService; private minDate: Date = new Date((new Date).valueOf() - (24 * 60 * 60 * 1000) * 7); private statuses: NSIInstructionStatus[]; private files: File[] = []; private coExecutors: UserBean[] = []; private coExecutorsSearch: boolean = false; private cancelation: any; static $inject = ['$stateParams', '$timeout', 'blockUI', 'fileRestService', 'activityRestService', '$q', 'nsiRestService', 'orderDocumentRestService', '$state', 'toastr']; constructor(private $stateParams: ng.ui.IStateParamsService, 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) { } public solicitorSearch(search: string, $select: any) { if (search && search.length > 2) { if (this.cancel) { this.$timeout.cancel(this.cancelation); } this.cancelation = this.$timeout(() => { this.nsiRestService.searchUsers({ fio: search }).then(response => { if (response && response.length > 0) { this.coExecutors = response; } }).catch(error => { this.toastr.error('Ошибка при получении информации из справочника!'); }); }, 500); } } $onInit() { this._blockUI = this.blockUI.instances.get('newOrder'); this._blockSearching = this.blockUI.instances.get('coExecutorsSearch'); this.nsiRestService.get('OasiInstructionExecutors').then((resp: NSIInstructionExecutor[]) => { return this.transformInstructionExecutor(resp); }).then(response => { this.executors = response; this.creators = _.filter(this.executors, r => { return r.creator.accountName === this.login; }).concat(_.filter(this.executors, r => { return _.findIndex(r.assistant, e => { return e.accountName === this.login; }) !== -1; })); return this.nsiRestService.get('OasiThematicHeading'); }).then(response => { this.theme = response; return this.nsiRestService.get('OasiInstructionPriority'); }).then(response => { this.priority = response; return this.nsiRestService.get('OasiInstructionDifficulty'); }).then(response => { this.difficulty = response; return this.nsiRestService.get('OasiInstructionStatus'); }).then(response => { this.statuses = response; return this.getParentDocument(); }).then(response => { this.parentDocument = response; this.model = new NewOrderModel(); if (this.creators.length === 1) { this.model.creator = this.creators[0]; } this.document = new OrderDocument(); if (this.$stateParams['parentId']) { this.document.parentId = this.$stateParams['parentId']; } this.loadingStatus = LoadingStatus.SUCCESS; }).catch(error => { this.loadingStatus = LoadingStatus.ERROR; }); } private getParentDocument(): ng.IPromise { let defer: ng.IDeferred = this.$q.defer(); if (this.$stateParams['parentId']) { this.orderDocumentRestService.get(this.$stateParams['parentId']).then(response => { defer.resolve(response.document); }).catch(error => { defer.reject(error); }); } else { defer.resolve(null); } return defer.promise; } transformInstructionExecutor(nsiInstructionExecutors: NSIInstructionExecutor[]): ng.IPromise { let defer: ng.IDeferred = this.$q.defer(); let logins: string[] = []; nsiInstructionExecutors.forEach(e => { logins = logins.concat(e.assistant); logins.push(e.creator); logins = logins.concat(e.executor); }); logins = _.uniq(logins); if (logins.length > 0) { let promises: ng.IPromise[] = []; logins.forEach(l => { promises.push(this.nsiRestService.ldapUser(l)); }); this.$q.all(promises).then(response => { let result: InstructionExecutor[] = _.map(nsiInstructionExecutors, n => { return { creator: _.find(response, r => { return r.accountName === n.creator; }), executor: _.filter(response, r => { return _.findIndex(n.executor, e => { return e === r.accountName; }) !== -1; }), assistant: _.filter(response, r => { return _.findIndex(n.assistant, e => { return e === r.accountName; }) !== -1; }) }; }); defer.resolve(result); }).catch(error => { defer.reject(error); }); } else { defer.resolve([]); } return defer.promise; } onCreatorChange() { this.model.executor = null; } upload(files: File[]) { this.files = files; } delete(file: File) { let index = _.findIndex(this.files, f => { return f === file; }); this.files.splice(index, 1); } saveFile(folderId: string): ng.IPromise { let defer: ng.IDeferred = this.$q.defer(); if (this.files.length > 0) { let fd = new FormData(); let _file = this.files[0]; fd.append('file', _file); fd.append('folderGuid', folderId); fd.append('fileType', 'MkaDocOrder'); this.fileRestService.handleFileUpload(fd).then(response => { defer.resolve(response.guid); }).catch(error => { defer.reject(error); }); } else { defer.resolve(null); } return defer.promise; } create() { console.log(this.model); if (this.model.isValid()) { this._blockUI.start(); this.model.upatedocumentFromModel(this.document, this.priority, this.difficulty); let status = _.find(this.statuses, s => { return s.code === 'inwork'; }); this.document.statusId.code = status.code; this.document.statusId.name = status.name; this.document.statusId.color = status.color; let data = new OrderDocumentWrapper(); data.document = this.document.min(); this.orderDocumentRestService.create(data).then(response => { this.document.documentId = response.document.documentId; this.document.folderId = response.document.folderId; this.document.instruction.number = response.document.instruction.number; this.toastr.success('Поручение успешно создано!'); return this.$timeout(1500); }).then(response => { return this.saveFile(this.document.folderId); }).then(response => { if (response) { this.toastr.success('Файл успешно сохранен!'); let _document = angular.copy(this.document); this.document.instruction.fileId.push(response); let left = new OrderDocumentWrapper(); left.document = _document.min(); let right = new OrderDocumentWrapper(); right.document = this.document.min(); let diff: any = JSON.stringify(jsonpatch.compare(left, right)); return this.orderDocumentRestService.patch(this.document.documentId, diff); } else { return this.$q.when(null); } }).then(response => { return this.$timeout(1500); }).then(response => { return this.activityRestService.getProcessDefinitions({ key: 'assign_issueAssignment_prc', latest: true }); }).then(response => { return this.activityRestService.initProcess({ processDefinitionId: response.data[0].id, variables: [ { 'name': 'EntityIdVar', 'value': this.document.documentId }, { 'name': 'ResponsibleExecutor_VAR', 'value': this.document.instruction.executor.login }, { 'name': 'TaskTime_VAR', 'value': this.buildTime(data.document.instruction.planDate) } ] }); }).then(response => { this.toastr.success('Процесс успешно запущен!'); return this.$timeout(1500); }).then(response => { this.$state.go('app.main'); this._blockUI.stop(); }).catch(error => { console.log(error); this.toastr.error('Ошибка при создании поручения!!'); this._blockUI.stop(); }); } else { this.toastr.warning('Не заполнены обязательные поля!'); } } 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; } cancel() { this.$state.go('app.main'); } } export const NewOrderComponent: angular.IComponentOptions = { controller: NewOrderController, template: require('./newOrder.html'), bindings: { login: '<' } };