angular.module('twoBookApp.book-entries',['ui.router','ui.grid','ui.bootstrap']).component('bookEntries',{templateUrl:'book-entries/book-entries.template.html',bindings:{tboPeriod:'<',tboChartDetail:'<',},controller:['Upload','$http','$timeout','RequestsErrorHandler','SessionService','$filter','$scope','$rootScope',"$injector","ErrorDialogEmbedded",'$state','$stateParams','$q','$compile',function BookEntriesController(Upload,$http,$timeout,RequestsErrorHandler,SessionService,$filter,$scope,$rootScope,$injector,ErrorDialogEmbedded,$state,$stateParams,$q,$compile){var self=this var showErrorMessage=false;var tboChartDetail=false;var _pdfInProgress=false var tboPeriod;var _isAdded;var _isUploaded;var _isInEditMode=false;this._showUnclearOnly=$stateParams.showUnclearOnly;self._months=[{text:decodeHtml("Jänner"),value:1},{text:"Februar",value:2},{text:decodeHtml("März"),value:3},{text:"April",value:4},{text:"Mai",value:5},{text:"Juni",value:6},{text:"Juli",value:7},{text:"August",value:8},{text:"September",value:9},{text:"Oktober",value:10},{text:"November",value:11},{text:"Dezember",value:12}];self._isAdded=false;self._isUploaded=false;self.categoryHint="";self.vatHint="";self.amountHint="" $(window).resize(function(){DEBUG&&console.log("window resize");resizeWrapper();resizeGrid();self.autoFitGrid();});$scope.$on("kendoWidgetCreated",function(event,widget){if(widget===self.bookentriesGrid){self.bookentriesGrid.element.on("dblclick","tbody>tr>td",function(evt){if((($(this).closest('tr').find('span[ng-bind="dataItem.EditedHH"]')[0].textContent!="true")||(self.userInfo.IsHH==true))&&(self.tboChartDetail==false||self.tboChartDetail==undefined)){var elem=this;self.checkIfNotInEditMode().then(function(response){self.bookentriesGrid.editRow($(elem));$(elem).find("input").focus();});}});} $(function(){var grid=$("#BookentriesGrid").data("kendoGrid");grid.table.on("focusout",".k-invalid",function(){var content=grid.content;var height=content.height();var cell=$(this).closest("td");var message=cell.find(".k-invalid-msg");var callout=message.find(".k-callout");var position=message.position();var top=position.top+callout.outerHeight()+message.outerHeight();if(top>height){content.scrollTop(content.scrollTop()+top-height);}});});self.bookentriesGrid.resizable.bind("start",function(e){});self.bookentriesGrid.resizable.bind("resize",function(e){});});this.$onChanges=function(changesObj){if(changesObj.tboPeriod){if(self.bookentriesGrid!==undefined){self.bookentriesGrid.dataSource.read();self.bookentriesGrid.setOptions({editable:false});self.gridDataSource.filter({tbomarker:"InvoiceDate1",logic:"and",filters:[{field:"InvoiceDate",operator:"gte",value:new Date(self.tboPeriod.Year,self.tboPeriod.Month-1,1)},{field:"InvoiceDate",operator:"lte",value:new Date(self.tboPeriod.Year,self.tboPeriod.Month,0)},]});}}};this.enterInlineEdit=function(){self._isInEditMode=true;var filterBtns=$("a.k-grid-filter");filterBtns.each(function(index){if(!$(this).hasClass("tbo-link-inactive")){$(this).addClass("tbo-link-inactive");} if(!$(this).siblings("a.k-link").hasClass("tbo-link-inactive")){$(this).siblings("a.k-link").addClass("tbo-link-inactive");}});var commandBtns=$("a.k-grid-edit");commandBtns.each(function(index){if(!$(this).hasClass("tbo-link-inactive")){$(this).addClass("tbo-link-inactive");} if(!$(this).siblings("a.k-grid-Delete").hasClass("tbo-link-inactive")){$(this).siblings("a.k-grid-Delete").addClass("tbo-link-inactive");}});} this.leaveInlineEdit=function(){self._isInEditMode=false;var filterBtns=$("a.k-grid-filter");filterBtns.each(function(index){if($(this).hasClass("tbo-link-inactive")){$(this).removeClass("tbo-link-inactive");} if($(this).siblings("a.k-link").hasClass("tbo-link-inactive")){$(this).siblings("a.k-link").removeClass("tbo-link-inactive");}});var commandBtns=$("a.k-grid-edit");commandBtns.each(function(index){if($(this).hasClass("tbo-link-inactive")){$(this).removeClass("tbo-link-inactive");} if($(this).siblings("a.k-grid-Delete").hasClass("tbo-link-inactive")){$(this).siblings("a.k-grid-Delete").removeClass("tbo-link-inactive");}});} this.alert=function(){self.showErrorMessage=true;tboAlert(self.errorMessage);self.resize();};this.create=function(){self.checkIfNotInEditMode().then(function(response){self._copyFromDataItem=null;var datasource=$("#BookentriesGrid").data("kendoGrid").dataSource;if(datasource.filter()!==undefined&&datasource.filter().filters.length>0){datasource.filter([]);} if(datasource.sort()!==undefined&&datasource.sort().length>0){datasource.sort([]);} self._isAdded=true;self.bookentriesGrid.addRow();self.bookentriesGrid.select("tr:eq(1)");});} this.copy=function(){self.checkIfNotInEditMode().then(function(response){self._copyFromDataItem=self.bookentriesGrid.dataItem(self.bookentriesGrid.select());if(self.gridDataSource.filter()!==undefined&&self.gridDataSource.filter().filters.length>0){self.gridDataSource.filter([]);} if(self.gridDataSource.sort()!==undefined&&self.gridDataSource.sort().length>0){self.gridDataSource.sort([]);} self.bookentriesGrid.addRow();self.bookentriesGrid.select("tr:eq(1)");self._isAdded=false;});} this.removeFilter=function(){self.checkIfNotInEditMode().then(function(response){var datasource=$("#BookentriesGrid").data("kendoGrid").dataSource;if(datasource.filter()!==undefined&&datasource.filter().filters.length>0){datasource.filter([]);} $('#tboFocus').focus();});} this.pdf=function(){self.checkIfNotInEditMode().then(function(response){self._pdfInProgress=true;self.bookentriesGrid.options.pdf.template='
'+'
'+'
'+self.currentBookKeeping.ClientName+'
'+'
2book Eingaben '+(self.tboPeriod==undefined?self.currentBookKeeping.Year:self.tboPeriod.Year)+'
'+'
'+''+'
';self.bookentriesGrid.setOptions({navigatable:false});$timeout(function(){self.bookentriesGrid.saveAsPDF({}).done(function(data){self._pdfInProgress=false;self.bookentriesGrid.setOptions({navigatable:true});$scope.$apply();}).fail(function(data){self._pdfInProgress=false;self.bookentriesGrid.setOptions({navigatable:true});});});$('#tboFocus').focus();});} self.downloadFile=function(lea,year,attachmentId){if(self._isInEditMode)return;RequestsErrorHandler.specificallyHandled(function(){$http({method:'GET',url:SessionService.getApiUrl()+'/api/file',headers:{'lea':lea,'year':year,'id':attachmentId},responseType:'arraybuffer'}).then(function(response){var fileName=response.headers('Content-Disposition').split(';')[1].trim().split('=')[1];fileName=fileName.replace(/"/g,'');var file=new Blob([response.data],{type:'application/pdf'});var fileURL=URL.createObjectURL(file);if(navigator.appVersion.toString().indexOf('.NET')>0) window.navigator.msSaveOrOpenBlob(file,fileName);else window.open(fileURL);},function(response){var decodedString=String.fromCharCode.apply(null,new Uint8Array(response.data));self.errorMessage=response.statusText+': '+decodedString;self.alert();})});} self.deleteFile=function(lea,year,entryId,attachmentId){if(self._isInEditMode)return;self._isUploaded=true;dataItem=self.gridDataSource.get(entryId);var tr=self.bookentriesGrid.tbody.find("tr[data-uid='"+dataItem.uid+"']");tr.addClass('tbo-state-selected-to-delete');ErrorDialogEmbedded.show('Willst Du den Anhang zu der rot markierten Eingabe wirklich löschen?',btnOk|btnCancel,iconUser,"AlertMessageWrapper").then(function(){tr.removeClass('tbo-state-selected-to-delete');SessionService.progressSymbol(true);RequestsErrorHandler.specificallyHandled(function(){$http({method:'DELETE',url:SessionService.getApiUrl()+'/api/file/'+attachmentId,headers:{'lea':lea,'year':year,'id':entryId}}).then(function(response){dataItem=self.gridDataSource.get(entryId);for(var key in response.data){if(response.data.hasOwnProperty(key)){dataItem.set(key,response.data[key]);}} SessionService.progressSymbol(false);},function(response){var x=typeof(response.data)==='object'?response.data.Message:response.data;self.errorMessage=response.statusText+': '+(typeof(response.data)==='object'?response.data.Message:response.data);self.alert();SessionService.progressSymbol(false);});});},function(){tr.removeClass('tbo-state-selected-to-delete');});self.bookentriesGrid.element.find(".k-grid-content").animate({scrollTop:tr.offset().top-self.bookentriesGrid.content.offset().top+self.bookentriesGrid.content.scrollTop()-(tr.offset().top-self.bookentriesGrid.content.offset().top)/2},400);} self.uploadFiles=function(file,errFiles,lea,year,entryId,attachmentId){self._isUploaded=true;dataItem=self.gridDataSource.get(entryId);if(attachmentId!==null&&attachmentId!=0){var tr=self.bookentriesGrid.tbody.find("tr[data-uid='"+dataItem.uid+"']");tr.addClass('tbo-state-selected-to-delete');ErrorDialogEmbedded.show('Willst Du den Anhang zu der rot markierten Eingabe wirklich überschreiben?',btnOk|btnCancel,iconUser,"AlertMessageWrapper").then(function(){tr.removeClass('tbo-state-selected-to-delete');self.uploadFiles(file,errFiles,lea,year,entryId,0);},function(){tr.removeClass('tbo-state-selected-to-delete');});self.bookentriesGrid.element.find(".k-grid-content").animate({scrollTop:tr.offset().top-self.bookentriesGrid.content.offset().top+self.bookentriesGrid.content.scrollTop()-(tr.offset().top-self.bookentriesGrid.content.offset().top)/2},400);return;} if(errFiles.length>0){switch(errFiles[0].$error){case'maxFiles':self.errorMessage=decodeHtml("Es kann nur ein PDF-Dokument je Eingabe angefügt werden. Maximale Größe 1,5 MB.");self.alert();break;case'pattern':self.errorMessage=decodeHtml("Es kann nur ein PDF-Dokument angefügt werden.");self.alert();break;case'maxSize':self.errorMessage=decodeHtml("Das Dokument überschreitet die maximale Größe von 1,5 MB.");self.alert();break;default:self.errorMessage=decodeHtml("Unbekannter Fehler beim Upload: "+errFiles[0].$error);self.alert();break;} return;} self.f=file;self.fileProgress=0;self.fileProgressId=entryId;if(file){SessionService.progressSymbol(true);RequestsErrorHandler.specificallyHandled(function(){file.upload=Upload.upload({url:SessionService.getApiUrl()+'/api/file',headers:{'lea':lea,'year':year,'id':entryId},data:{file:file}});});file.upload.then(function(response){dataItem=self.gridDataSource.get(entryId);for(var key in response.data){if(response.data.hasOwnProperty(key)){dataItem.set(key,response.data[key]);}} self.fileProgress=0;self.fileProgressId=0;SessionService.progressSymbol(false);},function(response){self.errorMessage=response.statusText+': '+(typeof(response.data)==='object'?response.data.Message:response.data);self.alert();SessionService.progressSymbol(false);self.fileProgress=0;self.fileProgressId=0;},function(evt){self.fileProgressId=entryId;self.fileProgress=Math.min(100,parseInt(100.0*evt.loaded/evt.total));});}} this.initCheckboxFilter=function initCheckboxFilter(e){var popup=e.container.data("kendoPopup");var dataSource=this.dataSource;var field=e.field;var checkboxesDataSource=new kendo.data.DataSource({data:self.uniqueForField(dataSource,field),});var displayField="" switch(field){case'CategoryId':displayField='CategoryDesc';e.container.data("kendoPopup").bind("open",function(){self.updateCheckboxFilter(e,field);});break;case'IncomeExpenseId':displayField='IEDesc';e.container.data("kendoPopup").bind("open",function(){self.updateCheckboxFilter(e,field);});break;case'TypeId':displayField='TypeDesc';e.container.data("kendoPopup").bind("open",function(){self.updateCheckboxFilter(e,field);});break;default:displayField=field;} var helpTextElement=e.container.children(":first").children(":first");helpTextElement.nextUntil(":has(.k-button)").remove();var element=$("
").insertAfter(helpTextElement).kendoListView({dataSource:checkboxesDataSource,pageable:true,template:"
#:"+displayField+"#
",});e.container.find("[type='submit']").click(function(e){e.preventDefault();e.stopPropagation();var filter=dataSource.filter()||{logic:"and",filters:[]};var fieldFilters=$.map(element.find(":checkbox:checked"),function(input){return{field:field,operator:"eq",value:input.value};});if(fieldFilters.length){self.removeFiltersForField(filter,field);filter.filters.push({logic:"or",filters:fieldFilters});dataSource.filter(filter);} popup.close();});} this.updateCheckboxFilter=function updateCheckboxFilter(e,field){var popup=e.container.data("kendoPopup");var dataSource=e.sender.dataSource;var checkboxesDataSource=new kendo.data.DataSource({data:self.uniqueForField(dataSource,field),});switch(field){case'CategoryId':checkboxesDataSource.sort({field:"CategoryDesc",dir:"asc"});break;case'IncomeExpenseId':checkboxesDataSource.sort({field:"Order",dir:"asc"});break;case'TypeId':checkboxesDataSource.sort({field:"TypeDesc",dir:"asc"});break;} var listView=e.container.find(".k-listview").data("kendoListView");listView.setDataSource(checkboxesDataSource);listView.refresh();} this.removeFiltersForField=function removeFiltersForField(expression,field){if(expression.filters){expression.filters=$.grep(expression.filters,function(filter){self.removeFiltersForField(filter,field);if(filter.filters){return filter.filters.length;}else{return filter.field!=field;}});}} this.uniqueForField=function uniqueForField(datasource,field){var map={};var result=[];var data=datasource.data();var item;for(var i=0;i
OK
"+"
nicht OK
"+"
nur H&H geprüfte
").insertAfter(helpTextElement) e.container.find("[type='reset']").click(function(e){var filter=dataSource.filter();if(filter) self.removeFiltersForField(filter,'EditedHH');});e.container.find("[type='submit']").click(function(e){e.preventDefault();e.stopPropagation();var filter=dataSource.filter()||{logic:"and",filters:[]};var isOK=element.find("input:checkbox[id='isOK']:checked");var isNotOK=element.find("input:checkbox[id='isNotOK']:checked");var isHh=element.find("input:checkbox[id='isHh']:checked");var isOkFilter=[];if(isOK.length)isOkFilter.push({field:'IsOK',operator:"eq",value:true});if(isNotOK.length)isOkFilter.push({field:'IsOK',operator:"eq",value:false});self.removeFiltersForField(filter,field);if(isOkFilter.length){filter.filters.push({logic:"or",filters:isOkFilter});} dataSource.filter(filter);var isHhFilter=[];if(isHh.length)isHhFilter.push({field:'EditedHH',operator:"eq",value:true});self.removeFiltersForField(filter,'EditedHH');if(isHhFilter.length){filter.filters.push({logic:"or",filters:isHhFilter});if(!isOkFilter.length){isOkFilter.push({field:'IsOK',operator:"neq",value:'x'});filter.filters.push({logic:"or",filters:isOkFilter});}} dataSource.filter(filter);popup.close();});} this.updateIsOkFilter=function(e){var popup=e.container.data("kendoPopup");var dataSource=e.sender.dataSource;var checkBoxes=e.container.find(".tbo-filter-checkbox-container");var isOK=e.container.find("input:checkbox[id='isOK']");var isNotOK=e.container.find("input:checkbox[id='isNotOK']");var isHh=e.container.find("input:checkbox[id='isHh']");var filter=dataSource.filter() if(!filter){isOK.attr('checked',false);isNotOK.attr('checked',false);isHh.attr('checked',false);}} this.initInvoiceDateFilter=function(e){var popup=e.container.data("kendoPopup");var dataSource=this.dataSource;e.container.data("kendoPopup").bind("open",function(){self.updateInvoiceDateFilter(e);});var filterElement=e.container;e.container.find("[type='submit']").click(function(e){e.preventDefault();e.stopPropagation();var filter=dataSource.filter()||{logic:"and",filters:[]};var operator=[];var month=[];var logic;operator.push(filterElement.find("select[data-bind$='filters[0].operator']"));operator.push(filterElement.find("select[data-bind$='filters[1].operator']"));month.push(filterElement.find("input[data-bind$='filters[0].value']"));month.push(filterElement.find("input[data-bind$='filters[1].value']"));logic=filterElement.find("select[data-bind$='logic']");var totalInvoiceDateFilter;var invoiceDateFilter1=[];var invoiceDateFilter2=[];if(month[0][0].value!=""){switch(operator[0][0].value){case'eq':invoiceDateFilter1.push({field:'InvoiceDate',operator:"gte",value:new Date(self.currentBookKeeping.Year,month[0][0].value-1,1)});invoiceDateFilter1.push({field:'InvoiceDate',operator:"lte",value:new Date(self.currentBookKeeping.Year,month[0][0].value,0)});break;case'gte':invoiceDateFilter1.push({field:'InvoiceDate',operator:"gte",value:new Date(self.currentBookKeeping.Year,month[0][0].value-1,1)});break;case'lte':invoiceDateFilter1.push({field:'InvoiceDate',operator:"lte",value:new Date(self.currentBookKeeping.Year,month[0][0].value,0)});break;} totalInvoiceDateFilter={tbomarker:'InvoiceDate1',logic:"and",filters:invoiceDateFilter1};if(month[1][0].value!=""){switch(operator[1][0].value){case'eq':invoiceDateFilter2.push({field:'InvoiceDate',operator:"gte",value:new Date(self.currentBookKeeping.Year,month[1][0].value-1,1)});invoiceDateFilter2.push({field:'InvoiceDate',operator:"lte",value:new Date(self.currentBookKeeping.Year,month[1][0].value,0)});break;case'gte':invoiceDateFilter2.push({field:'InvoiceDate',operator:"gte",value:new Date(self.currentBookKeeping.Year,month[1][0].value-1,1)});break;case'lte':invoiceDateFilter2.push({field:'InvoiceDate',operator:"lte",value:new Date(self.currentBookKeeping.Year,month[1][0].value,0)});break;} totalInvoiceDateFilter={tbomarker:'InvoiceDate',logic:logic[0].value,filters:[{tbomarker:'InvoiceDate1',logic:"and",filters:invoiceDateFilter1},{tbomarker:'InvoiceDate2',logic:"and",filters:invoiceDateFilter2}]};}} self.removeFiltersForField(filter,'InvoiceDate');if(invoiceDateFilter1.length){filter.filters.push(totalInvoiceDateFilter);} dataSource.filter(filter);popup.close();});} this.updateInvoiceDateFilter=function(e){var popup=e.container.data("kendoPopup");var dataSource=e.sender.dataSource;var operator=[];var operatorText=[];var month=[];var monthText=[];var logic;var logicText;operator.push(e.container.find("select[data-bind$='filters[0].operator']"));operator.push(e.container.find("select[data-bind$='filters[1].operator']"));operatorText.push(operator[0].parent().find("span[class$='k-input']"));operatorText.push(operator[1].parent().find("span[class$='k-input']"));month.push(e.container.find("input[data-bind$='filters[0].value']"));month.push(e.container.find("input[data-bind$='filters[1].value']"));monthText.push(month[0].parent().find("span[class$='k-input']"));monthText.push(month[1].parent().find("span[class$='k-input']"));logic=e.container.find("select[data-bind$='logic']");logicText=logic.parent().find("span[class$='k-input']");month[0].val('');monthText[0].text('-- Monat --');month[1].val('');monthText[1].text('-- Monat --');var filter=dataSource.filter()||{logic:"and",filters:[]};var filter1=self.getFiltersWithMarker(filter,'InvoiceDate1');if(filter1){DEBUG&&console.log("Filter InvoiceDate1 found.");var filter1parameter=self.parseInvoiceDateFilter(filter1);month[0].val(filter1parameter.month+1);monthText[0].text(self._months[filter1parameter.month].text);if(filter1parameter.operator=='eq'){operator[0].val('eq');operatorText[0].text('ist gleich');} var filter2=self.getFiltersWithMarker(filter,'InvoiceDate2');if(filter2){DEBUG&&console.log("Filter InvoiceDate2 found.");var filter2parameter=self.parseInvoiceDateFilter(filter2);month[1].val(filter2parameter.month+1);monthText[1].text(self._months[filter2parameter.month].text);if(filter2parameter.operator=='eq'){operator[1].val('eq');operatorText[1].text('ist gleich');} var filterLogic=self.getFiltersWithMarker(filter,'InvoiceDate');if(filterLogic){DEBUG&&console.log("Filter InvoiceDate found.");logic.val(filterLogic.logic);switch(filterLogic.logic){case'or':logicText.text('oder');break;case'and':logicText.text('und');break;default:logicText.text('');break;}}}}} this.parseInvoiceDateFilter=function(filter){if(filter.filters.length==1){if(filter.filters[0].operator=='gte'){return{operator:'gte',month:filter.filters[0].value.getMonth()};} if(filter.filters[0].operator=='lte'){return{operator:'gte',month:filter.filters[0].value.getMonth()};} return null;}else{return{operator:'eq',month:filter.filters[0].value.getMonth()};}} this.getFiltersWithMarker=function(filter,marker){if(filter.filters){if(filter.tbomarker==marker){return filter;} for(var i=0;i{{dataItem.InvoiceDate | date:'dd.MM.yy'}}"},{field:"TypeId",title:"Typ",editor:self.typeDropDownEditor,template:"{{($ctrl.bookEntryTypes | filter:{Id: dataItem.TypeId})[0].Type}}"},{field:"CustomerSupplier",title:"Kunde/Lieferant",editor:self.autoCompleteEditor,template:"{{dataItem.CustomerSupplier}}"},{field:"Note",title:"Notiz",editor:self.autoCompleteEditor,template:"{{dataItem.Note}}"},{field:"Info1",title:"Info1",editor:self.autoCompleteEditor,template:"{{dataItem.Info1}}"},{field:"Info2",title:"Info2",editor:self.autoCompleteEditor,template:"{{dataItem.Info2}}"},{field:"IncomeExpenseId",title:"Einnahme/Ausgabe",editor:self.incomeExpenseDropDownEditor,template:"{{($ctrl.incomeExpensesWithCategories | getIncomeExpenseById : dataItem.IncomeExpenseId).IEDescription}}"},{field:"CategoryId",title:"Kategorie",editor:self.categoryDropDownEditor,template:"{{($ctrl.incomeExpensesCategories | filter : {CategoryId : dataItem.CategoryId} : true)[0].CatDescription}}"},{field:"Amount",title:"Rechnungsbetrag
[EUR]",editor:self.amountEditor,footerTemplate:'
{{$ctrl.sumFooter("SignedAmount") | currency:"":2}}
',template:'
{{dataItem.Amount | currency:"":2}}
'},{field:"Vat",title:"USt [%]",editor:self.vatEditor,template:'
{{dataItem.Vat | currency:"":2}}
'},{field:"IsOK",title:"OK",editor:self.okEditor,template:''},{field:"Net",title:"Netto",footerTemplate:'
{{$ctrl.sumFooter("SignedNet") | currency:"":2}}
',template:'
{{dataItem.Net | currency:"":2}}
',filterable:false},{field:"Tax",title:"Steuer",footerTemplate:'
{{$ctrl.sumFooter("SignedTax") | currency:"":2}}
',template:'
{{dataItem.Tax | currency:"":2}}
',filterable:false},{field:"Attachment",title:"Anhang",template:'
'+'
'+'
'+'
'+'
',filterable:false},{field:"EditedHH",title:"HH",hidden:true},{field:"Command",command:[{name:"edit",text:{edit:"",update:"",cancel:""}},{name:"Delete",text:"",click:function(e){e.preventDefault();var tr=$(e.target).closest("tr");var data=this.dataItem(tr);var grid=this;tr.addClass('tbo-state-selected-to-delete');ErrorDialogEmbedded.show('Willst Du den rot markierten Datensatz wirklich l\öschen?',btnOk|btnCancel,iconUser,"AlertMessageWrapper").then(function(){grid.dataSource.remove(data) grid.dataSource.sync()},function(){tr.removeClass('tbo-state-selected-to-delete');});grid.element.find(".k-grid-content").animate({scrollTop:tr.offset().top-grid.content.offset().top+grid.content.scrollTop()-(tr.offset().top-grid.content.offset().top)/2},400);}}],title:" "}]};self.kendoGridOptionsPdf={editable:false,dataSource:self.gridDataSource,dataBound:this.onDataBound,pdf:{allPages:true,repeatHeaders:true,scale:0.4,paperSize:"A4",margin:{top:"3cm",right:"1cm",bottom:"1cm",left:"1cm"},landscape:true,title:"2book",fileName:"2book"},columns:[{field:"EntryNumber",title:"Nr",template:"{{dataItem.EntryNumber}}"},{field:"InvoiceDate",title:"Datum",format:"{0:dd.MM.yy}",template:"{{dataItem.InvoiceDate | date:'dd.MM.yy'}}"},{field:"TypeId",title:"Typ",template:"{{($ctrl.bookEntryTypes | filter:{Id: dataItem.TypeId})[0].Type}}"},{field:"CustomerSupplier",title:"Kunde/Lieferant",template:"{{dataItem.CustomerSupplier}}"},{field:"Note",title:"Notiz",template:"{{dataItem.Note}}"},{field:"Info1",title:"Info1",template:"{{dataItem.Info1}}"},{field:"Info2",title:"Info2",template:"{{dataItem.Info2}}"},{field:"IncomeExpenseId",title:"Einnahme/Ausgabe",template:"{{($ctrl.incomeExpensesWithCategories | getIncomeExpenseById : dataItem.IncomeExpenseId).IEDescription}}"},{field:"CategoryId",title:"Kategorie",template:"{{($ctrl.incomeExpensesCategories | filter : {CategoryId : dataItem.CategoryId} : true)[0].CatDescription}}"},{field:"Amount",title:"Rechnungsbetrag
[EUR]",footerTemplate:'
{{$ctrl.sumFooter("SignedAmount") | currency:"":2}}
',template:'
{{dataItem.Amount | currency:"":2}}
'},{field:"Vat",title:"USt [%]",template:'
{{dataItem.Vat | currency:"":2}}
'},{field:"IsOK",title:"OK",template:''},{field:"Net",title:"Netto",footerTemplate:'
{{$ctrl.sumFooter("SignedNet") | currency:"":2}}
',template:'
{{dataItem.Net | currency:"":2}}
'},{field:"Tax",title:"Steuer",footerTemplate:'
{{$ctrl.sumFooter("SignedTax") | currency:"":2}}
',template:'
{{dataItem.Tax | currency:"":2}}
',filterable:false},{field:"Attachment",title:"Anhang",template:'
',filterable:false},]};} this.getIncomeExpensesWithCategories=function getIncomeExpensesWithCategories(){console.log('getIncomeExpensesWithCategories');SessionService.progressSymbol(true);RequestsErrorHandler.specificallyHandled(function(){$http({method:'get',url:SessionService.getApiUrl()+'/api/incomeexpenses',headers:{'content-type':'text/xml'}}).then(function(response){SessionService.progressSymbol(false);self.incomeExpensesWithCategories=response.data;self.setKendoGridOptions();},function(response){SessionService.progressSymbol(false);self.errorMessage=response.statustext;self.alert();});})};this.getSettings=function getSettings(){DEBUG&&console.log('getSettings');SessionService.progressSymbol(true);SessionService.getSettings().then(function(response){self.Settings=response;self.showColumns();SessionService.progressSymbol(false);},function(response){SessionService.progressSymbol(false);self.errorMessage=response.statusText+': '+(typeof(response.data)==='object'?response.data.Message:response.data);self.alert();});};this.getIncomeExpensesWithCategories();this.getSettings();this.sumFooter=function(field){var allData=self.gridDataSource.data();var query=new kendo.data.Query(allData);var data;if(self.gridDataSource.filter()){data=query.filter(self.gridDataSource.filter()).data;}else{data=query.data;} var item,sum=0;for(var idx=0;idx0?0:addToFirstColumn;addToFirstColumn=self.setColumnWidth("Note",0)>0?0:addToFirstColumn;addToFirstColumn=self.setColumnWidth("Info1",0)>0?0:addToFirstColumn;addToFirstColumn=self.setColumnWidth("Info2",0)>0?0:addToFirstColumn;self.bookentriesGrid.autoFitColumn("EntryNumber");self.bookentriesGrid.autoFitColumn("InvoiceDate");self.bookentriesGrid.autoFitColumn("TypeId");self.bookentriesGrid.autoFitColumn("IncomeExpenseId");self.bookentriesGrid.autoFitColumn("CategoryId");self.bookentriesGrid.autoFitColumn("Amount");self.bookentriesGrid.autoFitColumn("Vat");self.bookentriesGrid.autoFitColumn("IsOK");self.bookentriesGrid.autoFitColumn("Net");self.bookentriesGrid.autoFitColumn("Tax");self.bookentriesGrid.autoFitColumn("Attachment");self.bookentriesGrid.autoFitColumn("Command");var tableWidth=grid.wrapper.find("div.k-grid-content")[0].clientWidth;var autoFitColumnsWidth=0;var countNoneAutoFitColumns=0;for(i=0;i0){var autoFitColumnWidth=Math.floor((tableWidth-autoFitColumnsWidth)/countNoneAutoFitColumns);var addToFirstColumn=(tableWidth-autoFitColumnsWidth)%countNoneAutoFitColumns;if(autoFitColumnWidth0?0:addToFirstColumn;addToFirstColumn=self.setColumnWidth("Note",autoFitColumnWidth+addToFirstColumn)>0?0:addToFirstColumn;addToFirstColumn=self.setColumnWidth("Info1",autoFitColumnWidth+addToFirstColumn)>0?0:addToFirstColumn;addToFirstColumn=self.setColumnWidth("Info2",autoFitColumnWidth+addToFirstColumn)>0?0:addToFirstColumn;}};this.setColumnWidth=function(field,width){opt=self.bookentriesGrid.getOptions();j=0;for(i=0;iRechnungsdatum
angegeben werden.");return false;} return true;},invoiceDateValidation:function(input){DEBUG&&console.log("entered invoiceDataValidation");if(input.is("[name='InvoiceDate']")&&input.val()!=""){DEBUG&&console.log("invoceDateValidation input:",input.val());var dateValid=tboCheckDate(input.val());DEBUG&&console.log("currentDate:"+input.val());if(!dateValid){input.attr("data-invoicedatevalidation-msg","Das Datum ist nicht gültig.");return false;} dateValid=input.data("kendoDatePicker").value();if(!dateValid){input.attr("data-invoicedatevalidation-msg","Das Datum ist nicht gültig.");return false;} dateValid=tboCheckDate(input.val(),self.currentBookKeeping.Year);if(!dateValid){input.attr("data-invoicedatevalidation-msg","Das Datum muss
im Jahr "+self.currentBookKeeping.Year+" liegen.");return false;}} return true;}}},TypeId:{nullable:false,validation:{typeIdRequired:function(input){if(input.is("[name='TypeId']")&&input.val()==""){input.attr("data-typeIdRequired-msg","Es muss eine
Buchungstyp
angegeben werden.");return false;} return true;}}},CustomerSupplier:{nullable:false,validation:{customerSupplierRequired:function(input){if(input.is("[name='CustomerSupplier']")&&input.val()==""){input.attr("data-customerSupplierRequired-msg","Es muss ein
Kunde/Lieferant
angegeben werden.");return false;} return true;}}},Note:{nullable:false},Info1:{nullable:false},Info2:{nullable:false},IncomeExpenseId:{nullable:false,validation:{incomeExpenseIdRequired:function(input){DEBUG&&console.log("entered incomeExpenseIdRequired");if(input.is("[name='IncomeExpenseId']")&&input.val()==""){input.attr("data-incomeExpenseIdRequired-msg","Es muss eine
Einnahmen-/Ausgabenart
angegeben werden.");return false;} if(input.is("[name='IncomeExpenseId']")&&input.val()!=""){validator=$("#BookentriesGrid").kendoValidator().data("kendoValidator");validator.validateInput($("input[name=CategoryId]"));validator.validateInput($("input[name=Vat]"));} return true;}}},CategoryId:{nullable:false,validation:{categoryIdRequired:function(input){if(input.is("[name='CategoryId']")&&input.val()==""){input.attr("data-categoryIdRequired-msg","Es muss eine
Einnahmen-/Ausgabenkategorie
angegeben werden.");return false;} return true;},categoryIdValidation:function(input){if(input.is("[name='CategoryId']")||input.is("[name='IncomeExpenseId']")){var row=input.closest("tr");var grid=row.closest("[data-role=grid]").data("kendoGrid");var dataItem=grid.dataItem(row);var curCategoryId="",curIncomeExpenseId="";input.is("[name='CategoryId']")?curCategoryId=input.val():curCategoryId=dataItem.CategoryId;input.is("[name='IncomeExpenseId']")?curIncomeExpenseId=input.val():curIncomeExpenseId=dataItem.IncomeExpenseId;if(curCategoryId=="SVA"&&curIncomeExpenseId=="A-AUST"){self.categoryHint=decodeHtml("SVA in Kombination mit einer Ausgabe im Ausland ist nur in den seltensten F\ällen korrekt!");$timeout(0);return true;} self.categoryHint="";$timeout(0);return true;} return true;}}},Amount:{type:"number",validation:{amountValidation:function(input){DEBUG&&console.log("entered amountValidation");if(input.is("[name='Amount']")){var row=input.closest("tr");var grid=row.closest("[data-role=grid]").data("kendoGrid");var dataItem=grid.dataItem(row);var curAmount=null,curCategoryId="";input.is("[name='Amount']")?curAmount=input.val():curAmount=dataItem.Vat;input.is("[name='CategoryId']")?curCategoryId=input.val():curCategoryId=dataItem.CategoryId;if(curAmount>400&&curCategoryId=="GWG"&&self.currentBookKeeping.Year<2020){self.amountHint=decodeHtml("Ein Betrag über 400 Euro bei einem geringfügigen Wirtschaftsgut ist in der Regel nicht korrekt.");$timeout(0);return true;} if(curAmount>800&&curCategoryId=="GWG"&&self.currentBookKeeping.Year>=2020){self.amountHint=decodeHtml("Ein Betrag über 800 Euro bei einem geringfügigen Wirtschaftsgut ist in der Regel nicht korrekt.");$timeout(0);return true;} self.amountHint="";$timeout(0);return true;} return true;}}},SignedAmount:{type:"number",editable:false},Vat:{nullable:true,type:"number",validation:{vatValidation:function(input){DEBUG&&console.log("entered vatValidation");DEBUG&&console.log("field:"+input[0].name);if(input.is("[name='Vat']")){if(self.currentBookKeeping.IsGross=="true"){return true;} var row=input.closest("tr");var grid=row.closest("[data-role=grid]").data("kendoGrid");var dataItem=grid.dataItem(row);var curVat=null,curIncomeExpenseId="",curUstCode="";input.is("[name='Vat']")?curVat=input.val():curVat=dataItem.Vat;input.is("[name='IncomeExpenseId']")?curIncomeExpenseId=input.val():curIncomeExpenseId=dataItem.IncomeExpenseId;if(curIncomeExpenseId!=""){curUstCode=($filter('filter')(self.incomeExpensesWithCategories,curIncomeExpenseId,true,'value'))[0].UstCode;} if(curVat!=null&&(curVat<0||curVat>100)){input.attr("data-vatValidation-msg","Der Steuersatz muss einen Wert
von 0 bis 100 annehmen.");return false;} if((curUstCode=="A-AUSL"||curUstCode=="E-OUB"||curUstCode=="E-RC"||curUstCode=="E-NSTB")&&(curVat!=null&&curVat!="")){input.attr("data-vatValidation-msg","Bei dieser E/A-Art darf
kein Steuersatz angegeben sein.");return false;}else if(curUstCode=="A-O"||curUstCode=="A-RC"||curUstCode=="A-IGE"||curUstCode=="E-O"){if(curVat==null||curVat==""){input.attr("data-vatValidation-msg","Der Wert muss
aufgrund der E/A-Art
0%, 10%, 13% oder 20% sein.");return false;} else if(curVat!=0&&curVat!=10&&curVat!=13&&curVat!=20){input.attr("data-vatValidation-msg","Bei dieser E/A-Art sind nur
0%, 10%, 13% oder 20%
erlaubt.");return false;} if(curVat==0&&curUstCode=="E-O"){self.vatHint=decodeHtml("0% USt bei einer Einnahme in Österreich ist nur in den seltensten F\ällen korrekt.");$timeout(0);return true;}}else if((curUstCode=="A-WDL"||curUstCode=="E-IGL"||curUstCode=="E-EX")&&(curVat!=0||curVat==""||curVat==null)){input.attr("data-vatValidation-msg","Der Steuersatz muss 0% sein.");return false;}else{if(curVat==null){self.vatHint=decodeHtml("Es wurde kein Steuersatz angegeben.");$timeout(0);return true;}} self.vatHint="";$timeout(0);return true;} return true;}}},IsOK:{type:"boolean",defaultValue:true},Net:{type:"number",editable:false},SignedNet:{type:"number",editable:false},Tax:{type:"number",editable:false},SignedTax:{type:"number",editable:false},Attachment:{editable:false}}}},aggregate:[{field:"Amount",aggregate:"sum"},{field:"SignedAmount",aggregate:"sum"},{field:"Tax",aggregate:"sum"},{field:"SignedTax",aggregate:"sum"},{field:"Net",aggregate:"sum"},{field:"SignedNet",aggregate:"sum"},],requestStart:function(e){if(self._isInEditMode){e.preventDefault();}}});var dropDownElementTemplate='
#:data.IEDescription#
' this.incomeExpenseDropDownEditor=function(container,options){var editor=$('').appendTo(container).kendoDropDownList({filter:"contains",placeholder:"Einnahme/Ausgabe",dataTextField:'IEDescription',dataValueField:'IncomeExpenseId',dataSource:{data:self.incomeExpensesWithCategories,sort:{field:"Order",dir:"asc"},},noDataTemplate:"Keine gültige Auswahl.",template:dropDownElementTemplate,change:function(e){var value=this.value();var categoryControl=$(container.prevObject).find("input[name='CategoryId']");categoryControl.data("kendoDropDownList").dataSource.data(($filter('filter')(self.incomeExpensesWithCategories,options.model.IncomeExpenseId,true,'value'))[0].IncomeExpenseCategories);var vatControl=$(container.prevObject).find("input[name='Vat']");var curUstCode=($filter('filter')(self.incomeExpensesWithCategories,value,true,'value'))[0].UstCode;if(curUstCode=="A-AUSL"||curUstCode=="E-OUB"||curUstCode=="E-RC"||curUstCode=="E-NSTB"){vatControl.data("kendoNumericTextBox").value(null);vatControl.data("kendoNumericTextBox").trigger("change");} if(curUstCode=="A-WDL"||curUstCode=="E-IGL"||curUstCode=="E-EX"){vatControl.data("kendoNumericTextBox").value(0);vatControl.data("kendoNumericTextBox").trigger("change");}},dataBound:function(e){var sep=e.sender.popup.element.find("div.tbo-drop-down-separator");angular.forEach(sep,function(el){if(!$(el).parent().hasClass("tbo-drop-down-separator")){$(el).parent().addClass('tbo-drop-down-separator');}});var inc=e.sender.popup.element.find("div.tbo-drop-down-income");angular.forEach(inc,function(el){if(!$(el).parent().hasClass("tbo-drop-down-income")){$(el).parent().addClass('tbo-drop-down-income');}});var exp=e.sender.popup.element.find("div.tbo-drop-down-expense");angular.forEach(exp,function(el){if(!$(el).parent().hasClass("tbo-drop-down-expense")){$(el).parent().addClass('tbo-drop-down-expense');}});}});tboOpenDropDownOnKey(editor);editor.data("kendoDropDownList").list.width("auto");$('
').appendTo(container);} this.categoryDropDownEditor=function(container,options){var editor=$('').appendTo(container).kendoDropDownList({filter:"contains",placeholder:"Kategorie",dataTextField:'CatDescription',dataValueField:'CategoryId',dataSource:{data:(options.model.IncomeExpenseId?($filter('filter')(self.incomeExpensesWithCategories,options.model.IncomeExpenseId,true,'value'))[0].IncomeExpenseCategories:[]),sort:{field:"Weight",dir:"asc"},sort:{field:"CatDescription",dir:"asc"}}});editor.data("kendoDropDownList").list.width("auto");tboOpenDropDownOnKey(editor);$('
').appendTo(container);$('').appendTo(container);} this.typeDropDownEditor=function(container,options){var editor=$('').appendTo(container).kendoDropDownList({dataTextField:'Type',dataValueField:'Id',dataSource:{data:self.bookEntryTypes,sort:{field:"Type",dir:"asc"}}});editor.data("kendoDropDownList").list.width("auto");$('
').appendTo(container);} this.invoiceDateEditor=function(container,options){var editor=$('').appendTo(container).kendoDatePicker({parseFormats:["dd-MM-yyyy","ddMMyyyy","dd-MM-yy","dd.MM.yy","ddMMyy","dd-MM","dd.MM","ddMM"],defaultOption:null,placeholder:"TTMMJJ",change:function(e){}});$('
').appendTo(container);} this.amountEditor=function(container,options){var editor=$('').appendTo(container).kendoNumericTextBox({culture:"de-DE",format:"{0:n2}",decimals:2,round:false,restrictDecimals:true,spinners:false});$('').appendTo(container);tboNumberEditorSelectOnFocus(editor);} this.vatEditor=function(container,options){var editor=$('').appendTo(container).kendoNumericTextBox({culture:"de-DE",format:"{0:n2}",decimals:2,round:false,restrictDecimals:true,spinners:false});$('
xxx').appendTo(container);$('').appendTo(container);tboNumberEditorSelectOnFocus(editor);} this.autoCompleteEditor=function(container,options){var grid=$("#BookentriesGrid").data("kendoGrid");var autoData=[];grid.dataSource._data.forEach(function(entry){if(findWithAttr(autoData,options.field,entry[options.field])==-1){var newItem={};newItem[options.field]=entry[options.field];autoData.push(newItem);}});var placeholder={CustomerSupplier:'Kunder/Lieferant',Note:'Notiz',Info1:'Info1',Info2:'Info2'};var editor=$('').appendTo(container).kendoAutoComplete({dataSource:{data:autoData},dataTextField:options.field,placeholder:placeholder[options.field],suggest:true,filter:"contains",minLength:1});editor.data("kendoAutoComplete").list.width("auto");$('
').appendTo(container);} this.okEditor=function(container,options){var editor=$('').appendTo(container)} $('#AlertMessageWrapper').on("change",function(){DEBUG&&console.log('AlertMessage changed');self.resize();});}]}).directive('tboHint',function(){return{restrict:"E",scope:{message:'@'},link:function(scope,element,attrs){},template:''};}).directive('tboEllipsisDiv',function(){function getBackgroundcolor(element){if(window.getComputedStyle(element[0],null).getPropertyValue("background-color")=="rgba(0, 0, 0, 0)"){return getBackgroundcolor(element.parent())}else{return window.getComputedStyle(element[0],null).getPropertyValue("background-color")}} var linkFn=function($scope,element,attrs,ctrl){var div=element.find('div');if(!Modernizr.touchevents){div.bind("mouseover",function(){div.css({"overflow":"visible","display":"inline-block","position":"absolute","z-index":"1","background":"#00614d","text-wrap":"normal","max-width":"200px","padding-right":"10px","white-space":"normal",});});div.bind("mouseout",function(){div.css({"overflow":"","display":"","position":"","z-index":"","font-weight":"","background":"","text-wrap":"","max-width":"","padding-right":"","white-space":"",});});} div.bind("click",function(){if(div.css("overflow")=="visible"){div.css({"overflow":"","display":"","position":"","z-index":"","font-weight":"","background":"","text-wrap":"","max-width":"","padding-right":"","white-space":"",});} else {div.css({"overflow":"visible","display":"inline-block","position":"absolute","z-index":"1","background":"#00614d","text-wrap":"normal","max-width":"200px","padding-right":"10px","white-space":"normal",});}});} return{link:linkFn,restrict:'E',scope:{label:'@'},template:'
',transclude:true};});function resizeGrid(){DEBUG&&console.log('resizeGrid');var gridElement=$("#BookentriesGrid"),dataArea=gridElement.find(".k-grid-content"),otherElements=gridElement.children().not(".k-grid-content"),otherElementsHeight=0,messageWrapper=$(document).find(".tbo-alert-message-wrapper"),modalHeight=$(document).find(".modal-content").height(),alertBar=$(messageWrapper[0]).find(".custom-alerts"),modalDialog=$(document).find(".modal-dialog"),residualMiddleHeight=$(window).height()-$(document).find(".page-wrapper-top").height()-$(document).find(".page-wrapper-bottom").height() residualMiddleHeight-=$(document).find(".page-head").height();residualMiddleHeight-=(-$(document).find(".page-content").height()+$(document).find(".page-content").innerHeight());if(alertBar[0]&&!modalDialog[0]){}else{messageWrapper.removeClass("modal-content")} if(modalHeight>0&&modalDialog[0]){messageWrapper.css("height",modalHeight+"px");var rect=messageWrapper[0].getBoundingClientRect();modalDialog.css("width",rect.width+'px');modalDialog.css("left",rect.left+'px');modalDialog.css("top",rect.top+'px');}else{messageWrapper.css("height","");} residualMiddleHeight-=messageWrapper.outerHeight(true);otherElements.each(function(){otherElementsHeight+=$(this).outerHeight(true);});dataArea.css("max-height",residualMiddleHeight-otherElementsHeight-5);} function resizeWrapper(){} $(document).ready(function(){$(window).trigger("resize");});