mirror of
https://github.com/firefly-iii/firefly-iii.git
synced 2025-12-12 09:52:20 +00:00
2 lines
21 KiB
JavaScript
2 lines
21 KiB
JavaScript
import{a as g,d as k,g as x,l as P}from"./load-translations-23553922.js";import{f as C,k as I,I as T,l as h}from"./vendor-e194ad60.js";import{a as A,G as E,f as m}from"./get-748a816c.js";function _(){return{id:"",name:"",alpine_name:""}}function S(){return{description:[],amount:[],currency_code:[],foreign_amount:[],foreign_currency_code:[],source_account:[],destination_account:[],budget_id:[],category_name:[],piggy_bank_id:[],bill_id:[],tags:[],notes:[],internal_reference:[],external_url:[],latitude:[],longitude:[],zoom_level:[],date:[],interest_date:[],book_date:[],process_date:[],due_date:[],payment_date:[],invoice_date:[]}}function D(){let t=C(new Date,"yyyy-MM-dd HH:mm");return{description:"",amount:"",currency_code:"EUR",foreign_amount:"",foreign_currency_code:"",source_account:_(),destination_account:_(),budget_id:null,category_name:"",piggy_bank_id:null,bill_id:null,tags:[],notes:"",internal_reference:"",external_url:"",hasLocation:!1,map:null,latitude:null,longitude:null,zoomLevel:null,marker:null,date:t,interest_date:"",book_date:"",process_date:"",due_date:"",payment_date:"",invoice_date:"",errors:S()}}function $(e,t){let r=[];for(let o in e)if(e.hasOwnProperty(o)){const n=e[o];let a={};a.description=n.description,a.source_name=n.source_account.name,a.destination_name=n.destination_account.name,a.amount=n.amount,a.currency_code=n.currency_code,a.date=n.date,a.interest_date=n.interest_date,a.book_date=n.book_date,a.process_date=n.process_date,a.due_date=n.due_date,a.payment_date=n.payment_date,a.invoice_date=n.invoice_date,a.budget_id=n.budget_id,a.category_name=n.category_name,a.piggy_bank_id=n.piggy_bank_id,a.bill_id=n.bill_id,a.tags=n.tags,a.notes=n.notes,a.internal_reference=n.internal_reference,a.external_url=n.external_url,a.store_location=!1,n.hasLocation&&(a.store_location=!0,a.longitude=n.longitude.toString(),a.latitude=n.latitude.toString(),a.zoom_level=n.zoomLevel),typeof n.foreign_currency_code<"u"&&n.foreign_currency_code.toString()!==""&&(a.foreign_currency_code=n.foreign_currency_code,typeof n.foreign_amount<"u"&&n.foreign_amount.toString()!==""&&(a.foreign_amount=n.foreign_amount),(typeof n.foreign_amount>"u"||n.foreign_amount.toString()==="")&&(delete a.foreign_amount,delete a.foreign_currency_code)),typeof n.source_account.id<"u"&&n.source_account.id.toString()!==""&&(a.source_id=n.source_account.id),typeof n.destination_account.id<"u"&&n.destination_account.id.toString()!==""&&(a.destination_id=n.destination_account.id),a.type=t,r.push(a)}return r}let O=class{post(t){let r="/api/v2/transactions";return g.post(r,t)}},B=class{list(t){return g.get("/api/v2/currencies",{params:t})}};function L(){let e={page:1,limit:1337};return new B().list(e).then(r=>{let o={defaultCurrency:{},nativeCurrencies:[],foreignCurrencies:[],enabledCurrencies:[]};o.foreignCurrencies.push({id:0,name:"(no foreign currency)",code:"",default:!1,symbol:"",decimal_places:2});for(let n in r.data.data)if(r.data.data.hasOwnProperty(n)){let a=r.data.data[n];if(a.attributes.enabled){let i={id:a.id,name:a.attributes.name,code:a.attributes.code,default:a.attributes.default,symbol:a.attributes.symbol,decimal_places:a.attributes.decimal_places};i.default&&(o.defaultCurrency=i),o.enabledCurrencies.push(i),o.nativeCurrencies.push(i),o.foreignCurrencies.push(i)}}return o})}class q{list(t){return g.get("/api/v2/budgets",{params:t})}}function F(){let e={page:1,limit:1337};return new q().list(e).then(r=>{let o=[{id:0,name:"(no budget)"}];for(let n in r.data.data)if(r.data.data.hasOwnProperty(n)){let a=r.data.data[n],i={id:a.id,name:a.attributes.name};o.push(i)}return o})}function j(){let e={page:1,limit:1337};return new A().list(e).then(r=>{let o={0:{id:0,name:"(no group)",order:0,piggyBanks:[{id:0,name:"(no piggy bank)",order:0}]}};for(let n in r.data.data)if(r.data.data.hasOwnProperty(n)){let a=r.data.data[n],i=a.attributes.object_group_id??"0",s=a.attributes.object_group_title??"(no group)",c={id:a.id,name:a.attributes.name,order:a.attributes.order};o.hasOwnProperty(i)||(o[i]={id:i,name:s,order:a.attributes.object_group_order??0,piggyBanks:[]}),o[i].piggyBanks.push(c),o[i].piggyBanks.sort((u,d)=>u.order-d.order)}return Object.keys(o).sort().reduce((n,a)=>(n[a]=o[a],n),{})})}function R(){let e={page:1,limit:1337};return new E().list(e).then(r=>{let o={0:{id:0,name:"(no group)",order:0,subscriptions:[{id:0,name:"(no subscription)",order:0}]}};for(let n in r.data.data)if(r.data.data.hasOwnProperty(n)){let a=r.data.data[n],i=a.attributes.object_group_id??"0",s=a.attributes.object_group_title??"(no group)",c={id:a.id,name:a.attributes.name,order:a.attributes.order};o.hasOwnProperty(i)||(o[i]={id:i,name:s,order:a.attributes.object_group_order??0,subscriptions:[]}),o[i].subscriptions.push(c),o[i].subscriptions.sort((u,d)=>u.order-d.order)}return Object.keys(o).sort().reduce((n,a)=>(n[a]=o[a],n),{})})}function p(e){const t={server:e.serverUrl,serverParams:{},fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}},hiddenInput:!0,preventBrowserAutocomplete:!0,highlightTyped:!0,liveServer:!0};typeof e.filters<"u"&&e.filters.length>0&&(t.serverParams.types=e.filters),typeof e.onRenderItem<"u"&&e.onRenderItem!==null&&(console.log("add on render item"),t.onRenderItem=e.onRenderItem),e.valueField&&(t.valueField=e.valueField),e.labelField&&(t.labelField=e.labelField),e.onSelectItem&&(t.onSelectItem=e.onSelectItem),e.onChange&&(t.onChange=e.onChange),I.init(e.selector,t)}function y(e,t){const r=parseInt(t._searchInput.attributes["data-index"].value);if(typeof e<"u"&&e.name){document.querySelector("#form")._x_dataStack[0].$data.entries[r].category_name=e.name;return}document.querySelector("#form")._x_dataStack[0].$data.entries[r].category_name=t._searchInput.value}function b(e,t){const r=parseInt(t._searchInput.attributes["data-index"].value);if(typeof e<"u"&&e.description){document.querySelector("#form")._x_dataStack[0].$data.entries[r].description=e.description;return}document.querySelector("#form")._x_dataStack[0].$data.entries[r].description=t._searchInput.value}function U(e,t){if(typeof e>"u"){const r=parseInt(t._searchInput.attributes["data-index"].value);if(document.querySelector("#form")._x_dataStack[0].$data.entries[r].destination_account.name===t._searchInput.value){console.warn('Ignore hallucinated destination account name change to "'+t._searchInput.value+'"');return}document.querySelector("#form")._x_dataStack[0].$data.entries[r].destination_account={name:t._searchInput.value,alpine_name:t._searchInput.value},document.querySelector("#form")._x_dataStack[0].changedDestinationAccount()}}function M(e,t){const r=parseInt(t._searchInput.attributes["data-index"].value);document.querySelector("#form")._x_dataStack[0].$data.entries[r].destination_account={id:e.id,name:e.name,alpine_name:e.name,type:e.type,currency_code:e.currency_code},document.querySelector("#form")._x_dataStack[0].changedDestinationAccount()}function N(e,t){if(typeof e>"u"){const r=parseInt(t._searchInput.attributes["data-index"].value);if(document.querySelector("#form")._x_dataStack[0].$data.entries[r].source_account.name===t._searchInput.value)return;document.querySelector("#form")._x_dataStack[0].$data.entries[r].source_account={name:t._searchInput.value,alpine_name:t._searchInput.value},document.querySelector("#form")._x_dataStack[0].changedSourceAccount()}}function G(e,t){const r=parseInt(t._searchInput.attributes["data-index"].value);document.querySelector("#form")._x_dataStack[0].$data.entries[r].source_account={id:e.id,name:e.name,alpine_name:e.name,type:e.type,currency_code:e.currency_code},document.querySelector("#form")._x_dataStack[0].changedSourceAccount()}class z{post(t,r,o){let n="/api/v1/attachments";return g.post(n,{filename:t,attachable_type:r,attachable_id:o})}upload(t,r){let o="./api/v1/attachments/"+t+"/upload";return axios.post(o,r)}}let H=function(e){let t=e.length,r=0,o=!1;for(const n in e)if(e.hasOwnProperty(n)&&/^0$|^[1-9]\d*$/.test(n)&&n<=4294967294&&o===!1){let a=new z;a.post(e[n].name,"TransactionJournal",e[n].journal).then(i=>{let s=parseInt(i.data.data.id);a.upload(s,e[n].content).then(c=>{if(r++,r===t){const u=new CustomEvent("upload-success",{some:"details"});document.dispatchEvent(u)}}).catch(c=>{console.error("Could not upload"),console.error(c),r++;const u=new CustomEvent("upload-failed",{error:c});document.dispatchEvent(u),o=!0})}).catch(i=>{console.error("Could not create upload."),console.error(i),r++;const s=new CustomEvent("upload-failed",{error:i});document.dispatchEvent(s),o=!0})}};function Z(e,t){t=t.reverse();let r=[],o=0,n=[],a=document.querySelectorAll('input[name="attachments[]"]');for(const i in a)if(a.hasOwnProperty(i)&&/^0$|^[1-9]\d*$/.test(i)&&i<=4294967294)for(const s in a[i].files)a[i].files.hasOwnProperty(s)&&/^0$|^[1-9]\d*$/.test(s)&&s<=4294967294&&(r.push({journal:t[i].transaction_journal_id,file:a[i].files[s]}),o++);for(const i in r)r.hasOwnProperty(i)&&/^0$|^[1-9]\d*$/.test(i)&&i<=4294967294&&function(s,c){let u=new FileReader;u.onloadend=function(d){d.target.readyState===FileReader.DONE&&(n.push({name:r[c].file.name,journal:r[c].journal,content:new Blob([d.target.result])}),n.length===o&&H(n))},u.readAsArrayBuffer(s.file)}(r[i],i);return o}function K(e,t,r){let o=[];for(let n in r)r.hasOwnProperty(n)&&o.push(r[n].replace(e,t));return o}function J(e,t,r){let o,n,a;for(const i in t)if(t.hasOwnProperty(i)){if(i==="group_title"){console.error("Cannot handle error in group title.");continue}if(o=parseInt(i.split(".")[1]),n=i.split(".")[2],a=K(i,n,t[i]),!r.hasOwnProperty(o)){console.error("Cannot handle errors in index #"+o);continue}switch(n){case"currency_code":case"foreign_currency_code":case"category_name":case"piggy_bank_id":case"notes":case"internal_reference":case"external_url":case"latitude":case"longitude":case"zoom_level":case"interest_date":case"book_date":case"process_date":case"due_date":case"payment_date":case"invoice_date":case"amount":case"date":case"budget_id":case"bill_id":case"description":case"tags":r[o].errors[n]=a;break;case"source_name":case"source_id":r[o].errors.source_account=r[o].errors.source_account.concat(a);break;case"type":r[o].errors.source_account=r[o].errors.source_account.concat([e.t("validation.bad_type_source")]),r[o].errors.destination_account=r[o].errors.destination_account.concat([e.t("validation.bad_type_destination")]);break;case"destination_name":case"destination_id":r[o].errors.destination_account=r[o].errors.destination_account.concat(a);break;case"foreign_amount":case"foreign_currency_id":r[o].errors.foreign_amount=r[o].errors.foreign_amount.concat(a);break}typeof r[o]<"u"&&(r[o].errors.source_account=Array.from(new Set(r[o].errors.source_account)),r[o].errors.destination_account=Array.from(new Set(r[o].errors.destination_account)))}return console.log(r[0].errors),r}let l;const f={description:"/api/v2/autocomplete/transaction-descriptions",account:"/api/v2/autocomplete/accounts",category:"/api/v2/autocomplete/categories",tag:"/api/v2/autocomplete/tags"};let V=function(){return{entries:[],formStates:{loadingCurrencies:!0,loadingBudgets:!0,loadingPiggyBanks:!0,loadingSubscriptions:!0,isSubmitting:!1,returnHereButton:!1,saveAsNewButton:!1,resetButton:!0,rulesButton:!0,webhooksButton:!0},formBehaviour:{formType:"create",foreignCurrencyEnabled:!0},formData:{defaultCurrency:null,enabledCurrencies:[],nativeCurrencies:[],foreignCurrencies:[],budgets:[],piggyBanks:[],subscriptions:[]},groupProperties:{transactionType:"unknown",title:null,id:null,totalAmount:0},notifications:{error:{show:!1,text:"",url:""},success:{show:!1,text:"",url:""},wait:{show:!1,text:""}},filters:{source:[],destination:[]},changedDateTime(e){console.log("changedDateTime")},changedDescription(e){console.log("changedDescription")},changedDestinationAccount(e){this.detectTransactionType()},changedSourceAccount(e){this.detectTransactionType()},detectTransactionType(){const e=this.entries[0].source_account.type??"unknown",t=this.entries[0].destination_account.type??"unknown";if(e==="unknown"&&t==="unknown"){this.groupProperties.transactionType="unknown",console.warn("Cannot infer transaction type from two unknown accounts.");return}if(e===t&&["Asset account","Loan","Debt","Mortgage"].includes(e)){this.groupProperties.transactionType="transfer",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),console.log("filter down currencies for transfer."),this.filterNativeCurrencies(this.entries[0].source_account.currency_code),this.filterForeignCurrencies(this.entries[0].destination_account.currency_code);return}if(e==="Asset account"&&["Expense account","Debt","Loan","Mortgage"].includes(t)){this.groupProperties.transactionType="withdrawal",console.log('[a] Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(e==="Asset account"&&t==="unknown"){this.groupProperties.transactionType="withdrawal",console.log('[b] Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),console.log(this.entries[0].source_account),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(["Debt","Loan","Mortgage"].includes(e)&&t==="Expense account"){this.groupProperties.transactionType="withdrawal",console.log('[c] Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(e==="Revenue account"&&["Asset account","Debt","Loan","Mortgage"].includes(t)){this.groupProperties.transactionType="deposit",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".');return}if(["Debt","Loan","Mortgage"].includes(e)&&t==="Asset account"){this.groupProperties.transactionType="deposit",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".');return}console.warn('Unknown account combination between "'+e+'" and "'+t+'".')},formattedTotalAmount(){return this.entries.length===0?m(this.groupProperties.totalAmount,"EUR"):m(this.groupProperties.totalAmount,this.entries[0].currency_code??"EUR")},filterForeignCurrencies(e){let t=[],r;for(let o in this.formData.enabledCurrencies)if(this.formData.enabledCurrencies.hasOwnProperty(o)){let n=this.formData.enabledCurrencies[o];n.code===e&&(r=n)}t.push(r),this.formData.foreignCurrencies=t,t.length===1&&t[0].code===this.entries[0].source_account.currency_code&&(console.log("Foreign currency is same as source currency. Disable foreign amount."),this.formBehaviour.foreignCurrencyEnabled=!1),t.length===1&&t[0].code!==this.entries[0].source_account.currency_code&&(console.log("Foreign currency is NOT same as source currency. Enable foreign amount."),this.formBehaviour.foreignCurrencyEnabled=!0);for(let o in this.entries)this.entries.hasOwnProperty(o)&&(this.entries[o].foreign_currency_code=e)},filterNativeCurrencies(e){let t=[],r;for(let o in this.formData.enabledCurrencies)if(this.formData.enabledCurrencies.hasOwnProperty(o)){let n=this.formData.enabledCurrencies[o];n.code===e&&(r=n)}t.push(r),this.formData.nativeCurrencies=t;for(let o in this.entries)this.entries.hasOwnProperty(o)&&(this.entries[o].currency_code=e)},changedAmount(e){const t=parseInt(e.target.dataset.index);this.entries[t].amount=parseFloat(e.target.value),this.groupProperties.totalAmount=0;for(let r in this.entries)this.entries.hasOwnProperty(r)&&(this.groupProperties.totalAmount=this.groupProperties.totalAmount+parseFloat(this.entries[r].amount))},addedSplit(){const e=function(t,r,o){return t.name_with_balance+'<br><small class="text-muted">'+l.t("firefly.account_type_"+t.type)+"</small>"};console.log(this.filters),p({selector:"input.ac-source",serverUrl:f.account,filters:this.filters.source,onRenderItem:e,onChange:N,onSelectItem:G}),p({selector:"input.ac-dest",serverUrl:f.account,filters:this.filters.destination,onRenderItem:e,onChange:U,onSelectItem:M}),p({selector:"input.ac-category",serverUrl:f.category,valueField:"id",labelField:"name",onChange:y,onSelectItem:y}),p({selector:"input.ac-description",serverUrl:f.description,valueField:"id",labelField:"description",onChange:b,onSelectItem:b})},processUpload(e){this.showMessageOrRedirectUser()},processUploadError(e){this.notifications.success.show=!1,this.notifications.wait.show=!1,this.notifications.error.show=!0,this.formStates.isSubmitting=!1,this.notifications.error.text=l.t("firefly.errors_upload"),console.error(e)},init(){Promise.all([x("language","en_US")]).then(e=>{l=new T;const t=e[0].replace("-","_");l.locale=t,P(l,t).then(()=>{this.addSplit()})}),L().then(e=>{this.formStates.loadingCurrencies=!1,this.formData.defaultCurrency=e.defaultCurrency,this.formData.enabledCurrencies=e.enabledCurrencies,this.formData.nativeCurrencies=e.nativeCurrencies,this.formData.foreignCurrencies=e.foreignCurrencies}),F().then(e=>{this.formData.budgets=e,this.formStates.loadingBudgets=!1}),j().then(e=>{this.formData.piggyBanks=e,this.formStates.loadingPiggyBanks=!1}),R().then(e=>{this.formData.subscriptions=e,this.formStates.loadingSubscriptions=!1}),document.addEventListener("upload-success",e=>{this.processUpload(e),document.querySelectorAll("input[type=file]").value=""}),document.addEventListener("upload-error",e=>{this.processUploadError(e)}),this.filters.source=["Asset account","Loan","Debt","Mortgage","Revenue account"],this.filters.destination=["Expense account","Loan","Debt","Mortgage","Asset account"]},submitTransaction(){this.notifications.error.show=!1,this.notifications.success.show=!1,this.notifications.wait.show=!1;for(let o in this.entries)this.entries.hasOwnProperty(o)&&(this.entries[o].errors=S());this.formStates.isSubmitting=!0,this.detectTransactionType();let e=$(this.entries,this.groupProperties.transactionType),t={group_title:this.groupProperties.title,fire_webhooks:this.formStates.webhooksButton,apply_rules:this.formStates.rulesButton,transactions:e};this.groupProperties.title===null&&e.length>1&&(t.group_title=e[0].description);let r=new O;console.log(t),r.post(t).then(o=>{const n=o.data.data;if(this.groupProperties.id=parseInt(n.id),this.groupProperties.title=n.attributes.group_title??n.attributes.transactions[0].description,Z(this.groupProperties.id,n.attributes.transactions)>0){this.notifications.wait.show=!0,this.notifications.wait.text=l.t("firefly.wait_attachments");return}this.showMessageOrRedirectUser()}).catch(o=>{this.submitting=!1,console.log(o),typeof o.response<"u"&&this.parseErrors(o.response.data)})},showMessageOrRedirectUser(){if(this.notifications.error.show=!1,this.notifications.success.show=!1,this.notifications.wait.show=!1,this.formStates.returnHereButton){this.notifications.success.show=!0,this.notifications.success.url="transactions/show/"+this.groupProperties.id,this.notifications.success.text=l.t("firefly.stored_journal_js",{description:this.groupProperties.title}),this.formStates.resetButton&&(this.entries=[],this.addSplit(),this.groupProperties.totalAmount=0);return}window.location="transactions/show/"+this.groupProperties.id+"?transaction_group_id="+this.groupProperties.id+"&message=created"},parseErrors(e){this.notifications.error.show=!0,this.notifications.success.show=!1,this.notifications.wait.show=!1,this.formStates.isSubmitting=!1,this.notifications.error.text=l.t("firefly.errors_submission",{errorMessage:e.message}),e.hasOwnProperty("errors")&&(this.entries=J(l,e.errors,this.entries))},addSplit(){this.entries.push(D())},removeSplit(e){this.entries.splice(e,1),document.querySelector("#split-0-tab").click()},clearLocation(e){e.preventDefault();const t=e.currentTarget,r=parseInt(t.attributes["data-index"].value);return this.entries[r].hasLocation=!1,this.entries[r].marker.remove(),!1},saveZoomOfMap(e){let t=parseInt(e.sourceTarget._container.attributes["data-index"].value),r=document.querySelector("#form")._x_dataStack[0].$data.entries[t].map;document.querySelector("#form")._x_dataStack[0].$data.entries[t].zoomLevel=r.getZoom(),console.log("New zoom level: "+r.getZoom())},addPointToMap(e){let t=parseInt(e.originalEvent.currentTarget.attributes["data-index"].value),r=document.querySelector("#form")._x_dataStack[0].$data.entries[t].map,o=document.querySelector("#form")._x_dataStack[0].$data.entries[t].hasLocation;if(console.log("Has location: "+o),o===!1){console.log("False!");const n=new h.marker(e.latlng,{draggable:!0});n.on("dragend",function(a){var i=a.target,s=i.getLatLng();i.setLatLng(new h.LatLng(s.lat,s.lng),{draggable:"true"}),document.querySelector("#form")._x_dataStack[0].$data.entries[t].latitude=s.lat,document.querySelector("#form")._x_dataStack[0].$data.entries[t].longitude=s.lng}),n.addTo(r),document.querySelector("#form")._x_dataStack[0].$data.entries[t].hasLocation=!0,document.querySelector("#form")._x_dataStack[0].$data.entries[t].marker=n,document.querySelector("#form")._x_dataStack[0].$data.entries[t].latitude=e.latlng.lat,document.querySelector("#form")._x_dataStack[0].$data.entries[t].longitude=e.latlng.lng,document.querySelector("#form")._x_dataStack[0].$data.entries[t].zoomLevel=r.getZoom()}}}},w={transactions:V,dates:k};function v(){Object.keys(w).forEach(e=>{console.log(`Loading page component "${e}"`);let t=w[e]();Alpine.data(e,()=>t)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),v()});window.bootstrapped&&(console.log("Loaded through window variable."),v());
|