Files
firefly-iii/public/build/assets/create-9af1982c.js
2024-01-07 12:51:42 +01:00

2 lines
16 KiB
JavaScript

import{a as v,d as E,f as _}from"./format-money-e259f5e4.js";import{d as P,c as S}from"./create-empty-split-fb5bda92.js";import{l as T,a as L,b as k,c as A,d as h,e as x,s as D,f as O,g as B,h as F,i as y,j as w}from"./autocomplete-functions-ac0d2cb1.js";import{l as g,i as d,m as z}from"./vendor-fca45885.js";import"./get-da167d5b.js";function M(e,n){let t=[];for(let r in e)if(e.hasOwnProperty(r)){const o=e[r];let i={};i.description=o.description,i.source_name=o.source_account.name,i.destination_name=o.destination_account.name,i.amount=o.amount,i.currency_code=o.currency_code,i.date=o.date,i.interest_date=o.interest_date,i.book_date=o.book_date,i.process_date=o.process_date,i.due_date=o.due_date,i.payment_date=o.payment_date,i.invoice_date=o.invoice_date,i.budget_id=o.budget_id,i.category_name=o.category_name,i.piggy_bank_id=o.piggy_bank_id,i.bill_id=o.bill_id,i.tags=o.tags,i.notes=o.notes,i.internal_reference=o.internal_reference,i.external_url=o.external_url,i.store_location=!1,o.hasLocation&&(i.store_location=!0,i.longitude=o.longitude.toString(),i.latitude=o.latitude.toString(),i.zoom_level=o.zoomLevel),typeof o.foreign_currency_code<"u"&&o.foreign_currency_code.toString()!==""&&(i.foreign_currency_code=o.foreign_currency_code,typeof o.foreign_amount<"u"&&o.foreign_amount.toString()!==""&&(i.foreign_amount=o.foreign_amount),(typeof o.foreign_amount>"u"||o.foreign_amount.toString()==="")&&(delete i.foreign_amount,delete i.foreign_currency_code)),typeof o.source_account.id<"u"&&o.source_account.id.toString()!==""&&(i.source_id=o.source_account.id),typeof o.destination_account.id<"u"&&o.destination_account.id.toString()!==""&&(i.destination_id=o.destination_account.id),i.type=n,t.push(i)}return t}let U=class{post(n){let t="/api/v2/transactions";return v.post(t,n)}};class I{post(n,t,r){let o="/api/v1/attachments";return v.post(o,{filename:n,attachable_type:t,attachable_id:r})}upload(n,t){let r="./api/v1/attachments/"+n+"/upload";return axios.post(r,t)}}let R=function(e){let n=e.length,t=0,r=!1;for(const o in e)if(e.hasOwnProperty(o)&&/^0$|^[1-9]\d*$/.test(o)&&o<=4294967294&&r===!1){let i=new I;i.post(e[o].name,"TransactionJournal",e[o].journal).then(s=>{let a=parseInt(s.data.data.id);i.upload(a,e[o].content).then(u=>{if(t++,t===n){const l=new CustomEvent("upload-success",{some:"details"});document.dispatchEvent(l)}}).catch(u=>{console.error("Could not upload"),console.error(u),t++;const l=new CustomEvent("upload-failed",{error:u});document.dispatchEvent(l),r=!0})}).catch(s=>{console.error("Could not create upload."),console.error(s),t++;const a=new CustomEvent("upload-failed",{error:s});document.dispatchEvent(a),r=!0})}};function N(e,n){n=n.reverse();let t=[],r=0,o=[],i=document.querySelectorAll('input[name="attachments[]"]');for(const s in i)if(i.hasOwnProperty(s)&&/^0$|^[1-9]\d*$/.test(s)&&s<=4294967294)for(const a in i[s].files)i[s].files.hasOwnProperty(a)&&/^0$|^[1-9]\d*$/.test(a)&&a<=4294967294&&(t.push({journal:n[s].transaction_journal_id,file:i[s].files[a]}),r++);for(const s in t)t.hasOwnProperty(s)&&/^0$|^[1-9]\d*$/.test(s)&&s<=4294967294&&function(a,u){let l=new FileReader;l.onloadend=function(m){m.target.readyState===FileReader.DONE&&(o.push({name:t[u].file.name,journal:t[u].journal,content:new Blob([m.target.result])}),o.length===r&&R(o))},l.readAsArrayBuffer(a.file)}(t[s],s);return r}function $(e,n,t){let r=[];for(let o in t)t.hasOwnProperty(o)&&r.push(t[o].replace(e,n));return r}function j(e,n,t){let r,o,i;for(const s in n)if(n.hasOwnProperty(s)){if(s==="group_title"){console.error("Cannot handle error in group title.");continue}if(r=parseInt(s.split(".")[1]),o=s.split(".")[2],i=$(s,o,n[s]),!t.hasOwnProperty(r)){console.error("Cannot handle errors in index #"+r);continue}switch(o){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":t[r].errors[o]=i;break;case"source_name":case"source_id":t[r].errors.source_account=t[r].errors.source_account.concat(i);break;case"type":t[r].errors.source_account=t[r].errors.source_account.concat([e.t("validation.bad_type_source")]),t[r].errors.destination_account=t[r].errors.destination_account.concat([e.t("validation.bad_type_destination")]);break;case"destination_name":case"destination_id":t[r].errors.destination_account=t[r].errors.destination_account.concat(i);break;case"foreign_amount":case"foreign_currency_id":t[r].errors.foreign_amount=t[r].errors.foreign_amount.concat(i);break}typeof t[r]<"u"&&(t[r].errors.source_account=Array.from(new Set(t[r].errors.source_account)),t[r].errors.destination_account=Array.from(new Set(t[r].errors.destination_account)))}return console.log(t[0].errors),t}let c=[],f=[];document.addEventListener("location-remove",e=>{f[e.detail.index].remove()});function q(e){let n=0;if(document.querySelector("#form")._x_dataStack[0].$data.entries[n].hasLocation===!1){f[n]=new g.marker(e.latlng,{draggable:!0}),f[n].on("dragend",H),f[n].addTo(c[n]);const r=new CustomEvent("location-set",{detail:{latitude:e.latlng.lat,longitude:e.latlng.lng,index:n,zoomLevel:c[n].getZoom()}});document.dispatchEvent(r)}}function Z(e){let n=0;const t=new CustomEvent("location-zoom",{detail:{index:n,zoomLevel:c[n].getZoom()}});document.dispatchEvent(t)}function H(e){let n=e.target,t=n.getLatLng();n.setLatLng(new g.LatLng(t.lat,t.lng),{draggable:"true"});const r=new CustomEvent("location-move",{detail:{latitude:t.lat,longitude:t.lng,index:0}});document.dispatchEvent(r)}function K(e){if(e>0){console.warn("Corwardly refuse to add a map on split #"+(e+1));return}if(typeof c[e]>"u"){let n=document.getElementById("location_map");c[e]=g.map(n).setView([n.dataset.latitude,n.dataset.longitude],n.dataset.zoomLevel),g.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png",{maxZoom:19,attribution:'&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'}).addTo(c[e]),c[e].on("click",q),c[e].on("zoomend",Z)}}const p=F();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.warn("changedDateTime, event is not used")},changedDescription(e){console.warn("changedDescription, event is not used")},changedDestinationAccount(e){this.detectTransactionType()},changedSourceAccount(e){this.detectTransactionType()},detectTransactionType(){const e=this.entries[0].source_account.type??"unknown",n=this.entries[0].destination_account.type??"unknown";if(e==="unknown"&&n==="unknown"){this.groupProperties.transactionType="unknown",console.warn("Cannot infer transaction type from two unknown accounts.");return}if(e===n&&["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(n)){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"&&n==="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)&&n==="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(n)){this.groupProperties.transactionType="deposit",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".');return}if(["Debt","Loan","Mortgage"].includes(e)&&n==="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 "'+n+'".')},formattedTotalAmount(){return this.entries.length===0?_(this.groupProperties.totalAmount,"EUR"):_(this.groupProperties.totalAmount,this.entries[0].currency_code??"EUR")},filterForeignCurrencies(e){let n=[],t;for(let r in this.formData.enabledCurrencies)if(this.formData.enabledCurrencies.hasOwnProperty(r)){let o=this.formData.enabledCurrencies[r];o.code===e&&(t=o)}n.push(t),this.formData.foreignCurrencies=n,n.length===1&&n[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),n.length===1&&n[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 r in this.entries)this.entries.hasOwnProperty(r)&&(this.entries[r].foreign_currency_code=e)},filterNativeCurrencies(e){let n=[],t;for(let r in this.formData.enabledCurrencies)if(this.formData.enabledCurrencies.hasOwnProperty(r)){let o=this.formData.enabledCurrencies[r];o.code===e&&(t=o)}n.push(t),this.formData.nativeCurrencies=n;for(let r in this.entries)this.entries.hasOwnProperty(r)&&(this.entries[r].currency_code=e)},changedAmount(e){const n=parseInt(e.target.dataset.index);this.entries[n].amount=parseFloat(e.target.value),this.groupProperties.totalAmount=0;for(let t in this.entries)this.entries.hasOwnProperty(t)&&(this.groupProperties.totalAmount=this.groupProperties.totalAmount+parseFloat(this.entries[t].amount))},addedSplit(){},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=d.t("firefly.errors_upload"),console.error(e)},init(){this.addSplit(),T().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}),L().then(e=>{this.formData.budgets=e,this.formStates.loadingBudgets=!1}),k().then(e=>{this.formData.piggyBanks=e,this.formStates.loadingPiggyBanks=!1}),A().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)}),document.addEventListener("location-move",e=>{this.entries[e.detail.index].latitude=e.detail.latitude,this.entries[e.detail.index].longitude=e.detail.longitude}),document.addEventListener("location-set",e=>{this.entries[e.detail.index].hasLocation=!0,this.entries[e.detail.index].latitude=e.detail.latitude,this.entries[e.detail.index].longitude=e.detail.longitude,this.entries[e.detail.index].zoomLevel=e.detail.zoomLevel}),document.addEventListener("location-zoom",e=>{this.entries[e.detail.index].hasLocation=!0,this.entries[e.detail.index].zoomLevel=e.detail.zoomLevel}),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 r in this.entries)this.entries.hasOwnProperty(r)&&(this.entries[r].errors=P());this.formStates.isSubmitting=!0,this.detectTransactionType();let e=M(this.entries,this.groupProperties.transactionType),n={group_title:this.groupProperties.title,fire_webhooks:this.formStates.webhooksButton,apply_rules:this.formStates.rulesButton,transactions:e};this.groupProperties.title===null&&e.length>1&&(n.group_title=e[0].description);let t=new U;console.log(n),t.post(n).then(r=>{const o=r.data.data;if(this.groupProperties.id=parseInt(o.id),this.groupProperties.title=o.attributes.group_title??o.attributes.transactions[0].description,N(this.groupProperties.id,o.attributes.transactions)>0){this.notifications.wait.show=!0,this.notifications.wait.text=d.t("firefly.wait_attachments");return}this.showMessageOrRedirectUser()}).catch(r=>{this.submitting=!1,console.log(r),typeof r.response<"u"&&this.parseErrors(r.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=d.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=d.t("firefly.errors_submission",{errorMessage:e.message}),e.hasOwnProperty("errors")&&(this.entries=j(i18n,e.errors,this.entries))},addSplit(){this.entries.push(S()),setTimeout(()=>{z.init("select.ac-tags",{allowClear:!0,server:p.tag,liveServer:!0,clearEnd:!0,allowNew:!0,notFoundMessage:d.t("firefly.nothing_found"),noCache:!0,fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}}});const e=this.entries.length-1;K(e);const n=function(t,r,o){return t.name_with_balance+'<br><small class="text-muted">'+d.t("firefly.account_type_"+t.type)+"</small>"};h({selector:"input.ac-source",serverUrl:p.account,onChange:x,onSelectItem:D,hiddenValue:this.items[e].source_account.alpine_name}),h({selector:"input.ac-dest",serverUrl:p.account,filters:this.filters.destination,onRenderItem:n,onChange:O,onSelectItem:B}),h({selector:"input.ac-category",serverUrl:p.category,valueField:"id",labelField:"name",onChange:y,onSelectItem:y}),h({selector:"input.ac-description",serverUrl:p.description,valueField:"id",labelField:"description",onChange:w,onSelectItem:w})},150)},removeSplit(e){this.entries.splice(e,1),document.querySelector("#split-0-tab").click()},clearLocation(e){e.preventDefault();const n=e.currentTarget,t=parseInt(n.attributes["data-index"].value);this.entries[t].hasLocation=!1,this.entries[t].latitude=null,this.entries[t].longitude=null,this.entries[t].zoomLevel=null;const r=new CustomEvent("location-remove",{detail:{index:t}});return document.dispatchEvent(r),!1}}},b={transactions:V,dates:E};function C(){Object.keys(b).forEach(e=>{console.log(`Loading page component "${e}"`);let n=b[e]();Alpine.data(e,()=>n)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),C()});window.bootstrapped&&(console.log("Loaded through window variable."),C());