invoiceModule.controller('issuedInvoiceBdViewController', ['$scope', '$log', '$document', '$uibModal', 'SweetAlert', '$translate', '$q', 'apiInterceptor', '$interval', 'region', '$timeout', '$location', 'vatOutputInvoiceManageService', 'enums', '$state', 'loginContext', 'modalAdapterService', 'Upload', function ($scope, $log, $document, $uibModal, SweetAlert, $translate, $q, apiInterceptor, $interval, region, $timeout, $location, vatOutputInvoiceManageService, enums, $state, loginContext, modalAdapterService, Upload) { 'use strict'; //-----------------搜索对象定义-----------------//start var isShowClearButton = true; $scope.searchOptions = {}; $scope.searchEntity = {}; var gdStatusList = _.chain(enums.GDBDStatusEnum) .invert().pairs().map(function (x) { return [x[0], $translate.instant(x[1])]; }).value(); $scope.searchOptions.InvoiceNo = { width: "100%", placeholder: $translate.instant('InputPlaceholder'), showClearButton: isShowClearButton, bindingOptions: { value: 'searchEntity.invoiceNo', } }; $scope.searchOptions.VIN = { width: "100%", placeholder: $translate.instant('InputPlaceholder'), showClearButton: isShowClearButton, bindingOptions: { value: 'searchEntity.VIN', } }; $scope.searchOptions.IssuedPeriodStart = { type: 'date', width: "100%", placeholder: $translate.instant("ChoosePlaceholder"), showClearButton: isShowClearButton, bindingOptions: { value: 'searchEntity.startTime', }, displayFormat: 'yyyy-MM-dd', }; $scope.searchOptions.IssuedPeriodEnd = { type: 'date', width: '100%', placeholder: $translate.instant("ChoosePlaceholder"), showClearButton: isShowClearButton, bindingOptions: { value: 'searchEntity.endTime', }, displayFormat: 'yyyy-MM-dd', }; //$scope.searchOptions.VehicleModel = { // width: "100%", // placeholder: $translate.instant('InputPlaceholder'), // showClearButton: isShowClearButton, // bindingOptions: { // value: 'searchEntity.vehicleModel' // } //}; $scope.searchOptions.gdStatus = { dataSource: gdStatusList, displayExpr: '1', valueExpr: '0', multiline: false, width: "100%", placeholder: $translate.instant("ChoosePlaceholder"), showDropButton: true, showClearButton: isShowClearButton, bindingOptions: { value: 'searchEntity.gdStatus' } }, $scope.searchOptions.IssuanceType = { width: "100%", valueExpr: 'id', displayExpr: 'name', placeholder: $translate.instant("ChoosePlaceholder"), showClearButton: isShowClearButton, items: [{ name: '' }, { id: 1, name: 'Salesforce' }, { id: 2, name: 'Smart Tax' }, { id: 3, name: 'Local' }], bindingOptions: { value: 'searchEntity.issuanceType', } }; $scope.toggleSearchContent = function () { if ($("#toggle-search-tr").css("display") == "none") { $(".hide-search-btn").addClass("fa-angle-up").html(' Collapse'); $(".hide-search-btn").removeClass("fa-angle-down"); } else { $(".hide-search-btn").addClass("fa-angle-down").html(' Expand'); $(".hide-search-btn").removeClass("fa-angle-up"); } $("#toggle-search-tr").toggle(200); $timeout(function () { $scope.setInvoiceGridHeight(); }, 300); }; //-----------------搜索对象定义-----------------//end //-----------------表格对象定义-----------------//start $scope.selectedIssuedInvoiceCount = 0; $scope.selectedIssuedInvoiceData = []; $scope.selectedIssuedInvoiceAmount = '0.00'; $scope.dataGridOption = { keyExpr: 'id', showRowLines: true, showColumnLines: true, showBorders: true, allowColumnResizing: true, columnAutoWidth: true, // hoverStateEnabled: true, //rowAlternationEnabled: true, // allowColumnReordering: true, columnFixing: { enabled: true }, paging: { enabled: false }, columnChooser: { enabled: true }, selection: { mode: 'multiple', showCheckBoxesMode: 'always' }, bindingOptions: { dataSource: 'invoiceGridDataSource', height: 'dataGridHeight' }, onSelectionChanged: function (e) { if (e && e.selectedRowsData) { $scope.selectedIssuedInvoiceCount = e.selectedRowsData.length; $scope.selectedIssuedInvoiceData = e.selectedRowsData; var amount = 0; _.each(e.selectedRowsData, function (item) { if (item.subtotalforFinalPayment) { amount += item.subtotalforFinalPayment; } }); $scope.selectedIssuedInvoiceAmount = amount.formatAmount(2); } } }; $scope.dataGridOption.columns = [ { dataField: 'invoiceNo', caption: $translate.instant('InvoiceNo'),fixed:true }, { dataField: 'invoiceCode', caption: $translate.instant('InvoiceCode'), fixed: true }, { dataField: 'vin', caption: $translate.instant('VIN') }, { dataField: 'caseNumber', caption: $translate.instant('InvoiceCaseNum') }, { dataField: 'vehicleModel', caption: $translate.instant('ModelSeriesG') }, { dataField: 'cabinConfiguration', caption: $translate.instant('CabinConfig') }, { dataField: 'registrationLocalName', caption: $translate.instant('RegistrationLocalName') }, { dataField: 'issuedDate', caption: $translate.instant('IssuedDate')}, { dataField: 'subtotalforFinalPayment', caption: $translate.instant('SubtotalForFinalPayment'), format: { type: 'fixedPoint', precision: 2 } }, { dataField: 'issuranceType', caption: $translate.instant('IssuranceType') }, { dataField: 'bdStatus', caption: $translate.instant('BDStatus')}, { dataField: 'gdBdStatus', caption: $translate.instant('GDBDStatus'), cellTemplate: function (ele, info) { if (info && info.value) { if (info.value === 'Issued') { $('<span>') .html(info.value + ' <i style="color: #b22;font-size: 22px; vertical-align: middle; cursor: pointer;" class="fa fa-arrow-circle-o-left"></i>') .appendTo(ele) .on('dxclick', function (e) { //执行红冲GD-BD发票操作 if (e.target.localName === 'i') { $scope.redLetterGdBdInvoice(info.data); } }); } else { $('<span>').text(info.value).appendTo(ele); } } } }, { caption: $translate.instant('Action'), alignment: 'left', cellTemplate: function (ele, info) { $('<a/>').css({ 'color': '#6699cc', 'cursor': 'pointer' }).text($translate.instant('View')).on('dxclick', function () { $scope.invoiceOperateType = constant.Operation.Query; $scope.invoiceModel = info.data; }).appendTo(ele); var checkDateStart = new Date().dateAdd('d', -1 * (new Date().getDate() + 180)).dateTimeToString('yyyyMMdd'); var checkDateEnd = new Date().dateAdd('d', -1 * new Date().getDate()).dateTimeToString('yyyyMMdd'); if (info.data.bdStatus != 'Red-lettered' && info.data.bdStatus != 'Cancelled' && info.data.issuedDate >= checkDateStart && info.data.issuedDate <= checkDateEnd) { var element = $('<a/>'); element.css({ 'color': '#6699cc', 'cursor': 'pointer', 'margin-left': '10px' }).text($translate.instant('Red Letter')).on('dxclick', function () { $scope.redLetterBdUserInvoice(info.data, element); }).appendTo(ele); } } } ]; //获取数据服务 $scope.getOutputInvoicePrintedList = function () { var deferred = $q.defer(); var invoiceParams = { QueryParam: $scope.searchEntity, PagingParam: $scope.pagingOptions, }; vatOutputInvoiceManageService.getIssuedVehicleBdList(invoiceParams).success(function (data) { if (data && data.list) { $scope.pagingOptions.totalItems = data.pageInfo && data.pageInfo.totalCount; data.list.forEach(function (item) { item.invoiceNo = item.invoiceNumber; item.invoiceCase = ''; item.issuedDate = item.bdIssuedDate ? (new Date(item.bdIssuedDate)).dateTimeToString('yyyyMMdd') : ''; item.caseCollectionDate = item.caseCollectionDate ? (new Date(item.caseCollectionDate)).dateTimeToString('yyyyMMdd') : ''; item.issuranceType = $translate.instant(PWC.getEnumKeyByValue(enums.IssuanceType, item.issuranceType)); item.bdStatus = $translate.instant(PWC.getEnumKeyByValue(enums.BDStatusEnum, item.bdStatus)); if (PWC.getEnumKeyByValue(enums.GDBDStatusEnum, item.gdBdStatus) === 'readyToIssue') { item.gdBdStatus = ''; }else{ item.gdBdStatus = $translate.instant(PWC.getEnumKeyByValue(enums.GDBDStatusEnum, item.gdBdStatus)); } if (!item.cabinConfiguration) { item.cabinConfiguration = $translate.instant('FiveSeatInterior'); } }); $scope.invoiceGridDataSource = data.list; //清除选中状态 $("#dxIssuedInvoiceDataGridContainer").dxDataGrid('instance').clearSelection(); deferred.resolve(data); }; }); return deferred.promise; }; //设置dataGrid分页 $scope.pagingOptions = { pageIndex: 1, //当前页码 totalItems: 100, //总数据 totalPages: 10,//总页数 maxSize: 10, //分页数字的限制。 pageSize: 20, //每页多少条数据 pageSizeString: '20', firstPage: $translate.instant('PagingFirstPage'), previousPage: $translate.instant('PagingPreviousPage'), nextPage: $translate.instant('PagingNextPage'), lastPage: $translate.instant('PagingLastPage'), }; //分页里面的处理 $scope.pagingService = { setPage: function (pageNo) { }, //分页的时候改变数字 pageIndexChanging: function () { if ($scope.pagingOptions.pageIndex > $scope.pagingOptions.totalPages) { $scope.pagingOptions.pageIndex = $scope.pagingOptions.totalPages; } $log.log('Page changed to: ' + $scope.pagingOptions.pageIndex); $scope.getOutputInvoicePrintedList(); }, //每页显示的数据下拉改变 pageSizeSelectionChanged: function () { $scope.pagingOptions.pageSize = parseInt($scope.pagingOptions.pageSizeString); $scope.getOutputInvoicePrintedList(); } }; //-----------------表格对象定义-----------------//end //-----------------发票操作定义-----------------//start //红冲BD-User Invoice $scope.redLetterBdUserInvoice = function (data,element) { var redLetterBdUserPopController = function ($scope) { $scope.redLetterData = {}; $scope.redLetterData.needReasonRdio = 1; $scope.redLetterData.inputReasonOption = { width: '100%', height: 60, bindingOptions: { value: 'redLetterData.inputReason' } }; $scope.validateOption = {}; $scope.validateOption.inputReasonOption = { validationRules: [{ type: "required", message: $translate.instant('BdUserRedLetterWarningInfoInputRequired') }, { type: 'stringLength', max: 500, message: $translate.instant('BdUserRedLetterWarningInfoInputLengthCheck') }] }; var addBdUserRedLetterReason = function (files) { var reasonData = {}; reasonData.invoicingReasonIndex = $scope.redLetterData.needReasonRdio; if ($scope.redLetterData.needReasonRdio == 2) { reasonData.inputReason = $scope.redLetterData.inputReason; } reasonData.isRecievingAll = $scope.redLetterData.isRevievingAll ? 1 : 0; reasonData.invoiceID = data.id; reasonData.caseNumber = data.caseNumber; //用户首字母大写 var tmpChar = loginContext.userName.substring(0, 1).toUpperCase(); var postString = loginContext.userName.substring(1, loginContext.userName.length); var tmpStr = tmpChar + postString; reasonData.createBy = tmpStr; //设置附件 if (files && files.length > 0) { var fileIds = []; _.each(files, function (item) { fileIds.push(item.data.fileID); }); reasonData.evidenceDocuments = fileIds.join(','); } var deffered = $q.defer(); vatOutputInvoiceManageService.addBdUserRedLetterReason(reasonData).success(function (data) { deffered.resolve(data); }); return deffered.promise; }; //BD红冲检查。 var checkDataAvailable = function (files) { if ($scope.redLetterData.needReasonRdio == 2) { var dxResult = DevExpress.validationEngine.validateGroup($('#reasonModalForm').dxValidationGroup("instance")).isValid; if (!dxResult) { return; } if (!$scope.redLetterData.inputReason) { SweetAlert.warning($translate.instant('BdUserRedLetterWarningInfoInputRequired')); return false; } else if ($scope.redLetterData.inputReason.length > 500) { SweetAlert.warning($translate.instant('BdUserRedLetterWarningInfoInputLengthCheck')); return false; } } if (!files || files.length < 1 || !$scope.redLetterData.isRevievingAll) { //检查证明文件 if (!files || files.length < 1) { $('#UploadFileCheckTipId').show(); } else { $('#UploadFileCheckTipId').hide(); } if (!$scope.redLetterData.isRevievingAll) { $('#CancelDialogTextTipId').show(); } else { $('#CancelDialogTextTipId').hide(); } return false; } else { $('#UploadFileCheckTipId').hide(); $('#CancelDialogTextTipId').hide(); } return true; }; $scope.$watch('$parent.uploadFileOption.files', function (newValue, oldValue) { if (newValue && newValue != oldValue) { var files = $scope.$parent.uploadFileOption.files; } }); //上传文件 $scope.uploadFile = function () { $scope.$parent.uploadFileType = 'multiple'; $scope.$parent.uploadFileOption = { title: 'Upload Evidence Document', uploadButtonText: 'Select Upload Files', files: $scope.$parent.uploadFileOption.files || [] }; } //关闭弹窗口 $scope.hidePopPanel = function () { $scope.$parent.uploadFileOption = {}; $scope.$dismiss({ $value: 'cancel' }); }; //删除证据文件 $scope.deleteEvidenceFile = function (fileId) { var fileList = [fileId]; vatOutputInvoiceManageService.deleteEvidenceFile(fileList).then(function () { $scope.$parent.uploadFileOption.files = _.filter($scope.$parent.uploadFileOption.files, function (item) { return item.data.fileID != fileId; }); }); } //下载证据文件 $scope.downloadEvidenceFile = function (data) { var queryDto = {}; queryDto.fileName = data.fileName; queryDto.filePath = data.filePath; vatOutputInvoiceManageService.downloadEvidenceFile(queryDto); }; //执行红冲发票 $scope.confirmRedLetterInvoice = function (files) { if (checkDataAvailable(files)) { //调用红冲接口 vatOutputInvoiceManageService.redLetterInvoice(data.id).then(function () { //保存红冲原因及附件。 var promise = addBdUserRedLetterReason(files); promise.then(function (data) { //红冲结束隐藏红冲按钮。 element.hide(); $scope.$parent.uploadFileOption = {}; $scope.$dismiss({ $value: 'cancel' }); $scope.getOutputInvoicePrintedList(); }); }); } }; }; var parentElem = angular.element($document[0].querySelector('#red-letter-bd-user-pop')); var modalInstance = $uibModal.open({ ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', backdrop: 'static', templateUrl: 'red-letter-bd-user-page.html', controller: redLetterBdUserPopController, windowClass: 'data-table', appendTo: parentElem, scope: $scope }); }; //红冲GD-BD Invoice (只改GD-BD发票中的该车的状态为Pending For Approval) $scope.redLetterGdBdInvoice = function (data) { //vatOutputInvoiceManageService.sendEmail(data.vin); //vatOutputInvoiceManageService.receiveEmail(); var redLetterGdBdInvoiceController = function ($scope) { $scope.data = data; if (data.vin) { vatOutputInvoiceManageService.getOutputInvoiceImportedByVin(data.vin).success(function (result) { //排除自己 result = _.filter(result, function (item) { return item.bdFapiaoEntity != data.bdFapiaoEntity || item.registrationLocalName != data.registrationLocalName || item.companyVATIDTaxID != data.companyVATIDTaxID || item.organizationCode != data.organizationCode; }); $scope.data.BDList = result; }); } $scope.data = data; //关闭弹窗口 $scope.hidePopPanel = function () { $scope.$dismiss({ $value: 'cancel' }); }; //执行更新GD-BD车辆 invoice status $scope.confirmRedLetterInvoice = function () { vatOutputInvoiceManageService.updateInvoiceVichelGdBdStatus(data.id, enums.GDBDStatusEnum.pendingForApproval).success(function () { $scope.$dismiss({ $value: 'cancel' }); $scope.getOutputInvoicePrintedList(); vatOutputInvoiceManageService.sendEmail(data.vin,data.id); }); }; $scope.dataGridGdBdOptions = { showRowLines: true, showColumnLines: true, showBorders: true, allowColumnResizing: true, hoverStateEnabled: true, rowAlternationEnabled: true, bindingOptions: { dataSource: 'data.BDList' }, columns: [ { dataField: 'bdFapiaoEntity', caption: 'Entity', width: '25%' }, { dataField: 'registrationLocalName', caption: 'Customer name', width: '25%' }, { dataField: 'companyVATIDTaxID', caption: 'Customer tax ID or National ID', width: '25%' }, { dataField: 'organizationCode', caption: 'Organization Code (if applicable)', width: '25%' } ] }; $timeout(function () { $scope.dataGridGdBdOptions.height = 130; }, 500); }; var parentElem = angular.element($document[0].querySelector('#red-letter-gd-bd-pop')); var modalInstance = $uibModal.open({ ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', backdrop: 'static', templateUrl: 'red-letter-gd-bd-page.html', controller: redLetterGdBdInvoiceController, windowClass: 'data-table', appendTo: parentElem, scope: $scope }); }; $scope.cancelCore = function () { //调用取消发票接口执行取消发票功能。 var promiss = []; var data = $scope.selectedIssuedInvoiceData; //已红冲和已取消的发票不能再做取消操作。 var canCancelDatas = []; var negativeDatas = []; _.each(data, function (item) { if (item.bdStatus == enums.BDStatusEnum.Cancelled || item.bdStatus == enums.BDStatusEnum.RedLettered) { canCancelDatas.push(item); } }); _.each(data, function (item) { if (item.subtotalforFinalPayment < 0) { negativeDatas.push(item); } }); if (canCancelDatas.length > 0) { SweetAlert.warning($translate.instant('BDFapiaoCancelCheck') .replace('{0}', _.pluck(canCancelDatas, 'invoiceNumber').join(','))); return; } if (negativeDatas.length > 0) { SweetAlert.warning($translate.instant('NegativeFapiaoCheck') .replace('{0}', _.pluck(negativeDatas, 'invoiceNumber').join(','))); return; } _.each(data, function (item) { var cancelPromiss = vatOutputInvoiceManageService.cancelInvoice(item.id, $scope.isReprint); promiss.push(cancelPromiss); }); $q.all(promiss).then(function () { modalAdapterService.close(constant.OutputInvoiceCancalDialog, "issued-invoice-bd-view-container"); $scope.getOutputInvoicePrintedList(); }, //可能有错误的时候 function (err) { SweetAlert.error('', $translate.instant('CommonFail')); }); }; //取消发票 $scope.CancelInvoice = function (data, reprint) { if (!data || data.length < 1) { SweetAlert.warning($translate.instant('SelectBdInvoiceCheck')); return; } $scope.title = reprint ? $translate.instant("CancelReprintInvoiceBDTitle") : $translate.instant("CancelInvoiceBDTitle") $scope.isReprint = reprint ? reprint : false; modalAdapterService.open(constant.OutputInvoiceCancalDialog, "issued-invoice-bd-view-container"); }; //-----------------发票操作定义-----------------//end //Upload Vin file define -->start var resumable = true; $scope.chunkSize = 500 * 1024; $scope.uploadOption = {}; $scope.uploadOption.uploadFiles = []; $scope.$watch('uploadOption.uploadFiles', function (newValue, oldValue) { if (newValue && newValue !== oldValue) { uploadfile($scope.uploadOption.uploadFiles); } }); //执行上传文件操作。 var uploadfile = function (file) { if (file) { var uploadSuccessCallBack = function (data) { var result = data; }; var uploadSuccess = function (data) { //根据上传的vin勾选发票 var result = data; var gridInstance = $('#dxIssuedInvoiceDataGridContainer').dxDataGrid('instance'); var selectedInvoices = _.filter($scope.invoiceGridDataSource, function (item) { return result.data.indexOf(item.vin) >= 0; }); var selectedKeys = _.pluck(selectedInvoices, 'id'); gridInstance.selectRows(selectedKeys,true); }; if (!file.$error) { var tempFileName = PWC.newGuid() + '.dat'; var token = $('input[name="__RequestVerificationToken"]').val(); Upload.upload({ url: apiInterceptor.webApiHostUrl + '/outputInvoicePrinted/uploadVinFile', data: { cancel: false, filename: file.name, tempFileName: tempFileName, file: file, period: $scope.period }, resumeChunkSize: resumable ? $scope.chunkSize : null, headers: { 'Access-Control-Allow-Origin': '*', Authorization: apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken() }, __RequestVerificationToken: token, withCredentials: true }).then(uploadSuccess, uploadSuccessCallBack); } } };//Upload Vin file define -->end $scope.$on('teslaOutputInvoiceMenuClick', function (event, data) { //设置表格高度 $timeout(function () { $scope.setInvoiceGridHeight(); }, 500); }); $scope.printGDInvoice = function () { if (!$scope.selectedIssuedInvoiceData || $scope.selectedIssuedInvoiceData.length === 0) { SweetAlert.warning($translate.instant('SelectBdInvoiceCheck')); return; }; $state.go('outputInvoiceManage.gdInvoicePrint', { invoiceList: $scope.selectedIssuedInvoiceData }); }; (function () { var promise = $scope.getOutputInvoicePrintedList(); $scope.uploadFileType = null; $scope.uploadFileOption = {}; promise.then(function () { //设置表格高度 $timeout(function () { $scope.setInvoiceGridHeight(); }, 500); }); })(); } ]);