Files
firefly-iii/public/build/assets/create-d5d549ca.js
2024-01-06 07:42:00 +01:00

2 lines
16 KiB
JavaScript

import{a as v,d as P,f as _,g as E,l as S}from"./get-c53daca3.js";import{l as T,a as L,b as k,c as A,d as x,e as D,f as h,g as O,s as B,h as F,i as I,j as U,k as y,m as w}from"./autocomplete-functions-31caaca5.js";import{k as g,I as z,l as M}from"./vendor-4332182f.js";function R(e,t){let o=[];for(let r in e)if(e.hasOwnProperty(r)){const n=e[r];let i={};i.description=n.description,i.source_name=n.source_account.name,i.destination_name=n.destination_account.name,i.amount=n.amount,i.currency_code=n.currency_code,i.date=n.date,i.interest_date=n.interest_date,i.book_date=n.book_date,i.process_date=n.process_date,i.due_date=n.due_date,i.payment_date=n.payment_date,i.invoice_date=n.invoice_date,i.budget_id=n.budget_id,i.category_name=n.category_name,i.piggy_bank_id=n.piggy_bank_id,i.bill_id=n.bill_id,i.tags=n.tags,i.notes=n.notes,i.internal_reference=n.internal_reference,i.external_url=n.external_url,i.store_location=!1,n.hasLocation&&(i.store_location=!0,i.longitude=n.longitude.toString(),i.latitude=n.latitude.toString(),i.zoom_level=n.zoomLevel),typeof n.foreign_currency_code<"u"&&n.foreign_currency_code.toString()!==""&&(i.foreign_currency_code=n.foreign_currency_code,typeof n.foreign_amount<"u"&&n.foreign_amount.toString()!==""&&(i.foreign_amount=n.foreign_amount),(typeof n.foreign_amount>"u"||n.foreign_amount.toString()==="")&&(delete i.foreign_amount,delete i.foreign_currency_code)),typeof n.source_account.id<"u"&&n.source_account.id.toString()!==""&&(i.source_id=n.source_account.id),typeof n.destination_account.id<"u"&&n.destination_account.id.toString()!==""&&(i.destination_id=n.destination_account.id),i.type=t,o.push(i)}return o}let N=class{post(t){let o="/api/v2/transactions";return v.post(o,t)}};class ${post(t,o,r){let n="/api/v1/attachments";return v.post(n,{filename:t,attachable_type:o,attachable_id:r})}upload(t,o){let r="./api/v1/attachments/"+t+"/upload";return axios.post(r,o)}}let j=function(e){let t=e.length,o=0,r=!1;for(const n in e)if(e.hasOwnProperty(n)&&/^0$|^[1-9]\d*$/.test(n)&&n<=4294967294&&r===!1){let i=new $;i.post(e[n].name,"TransactionJournal",e[n].journal).then(s=>{let a=parseInt(s.data.data.id);i.upload(a,e[n].content).then(l=>{if(o++,o===t){const d=new CustomEvent("upload-success",{some:"details"});document.dispatchEvent(d)}}).catch(l=>{console.error("Could not upload"),console.error(l),o++;const d=new CustomEvent("upload-failed",{error:l});document.dispatchEvent(d),r=!0})}).catch(s=>{console.error("Could not create upload."),console.error(s),o++;const a=new CustomEvent("upload-failed",{error:s});document.dispatchEvent(a),r=!0})}};function q(e,t){t=t.reverse();let o=[],r=0,n=[],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&&(o.push({journal:t[s].transaction_journal_id,file:i[s].files[a]}),r++);for(const s in o)o.hasOwnProperty(s)&&/^0$|^[1-9]\d*$/.test(s)&&s<=4294967294&&function(a,l){let d=new FileReader;d.onloadend=function(m){m.target.readyState===FileReader.DONE&&(n.push({name:o[l].file.name,journal:o[l].journal,content:new Blob([m.target.result])}),n.length===r&&j(n))},d.readAsArrayBuffer(a.file)}(o[s],s);return r}function Z(e,t,o){let r=[];for(let n in o)o.hasOwnProperty(n)&&r.push(o[n].replace(e,t));return r}function V(e,t,o){let r,n,i;for(const s in t)if(t.hasOwnProperty(s)){if(s==="group_title"){console.error("Cannot handle error in group title.");continue}if(r=parseInt(s.split(".")[1]),n=s.split(".")[2],i=Z(s,n,t[s]),!o.hasOwnProperty(r)){console.error("Cannot handle errors in index #"+r);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":o[r].errors[n]=i;break;case"source_name":case"source_id":o[r].errors.source_account=o[r].errors.source_account.concat(i);break;case"type":o[r].errors.source_account=o[r].errors.source_account.concat([e.t("validation.bad_type_source")]),o[r].errors.destination_account=o[r].errors.destination_account.concat([e.t("validation.bad_type_destination")]);break;case"destination_name":case"destination_id":o[r].errors.destination_account=o[r].errors.destination_account.concat(i);break;case"foreign_amount":case"foreign_currency_id":o[r].errors.foreign_amount=o[r].errors.foreign_amount.concat(i);break}typeof o[r]<"u"&&(o[r].errors.source_account=Array.from(new Set(o[r].errors.source_account)),o[r].errors.destination_account=Array.from(new Set(o[r].errors.destination_account)))}return console.log(o[0].errors),o}let u=[],f=[];document.addEventListener("location-remove",e=>{f[e.detail.index].remove()});function H(e){let t=0;if(document.querySelector("#form")._x_dataStack[0].$data.entries[t].hasLocation===!1){f[t]=new g.marker(e.latlng,{draggable:!0}),f[t].on("dragend",J),f[t].addTo(u[t]);const r=new CustomEvent("location-set",{detail:{latitude:e.latlng.lat,longitude:e.latlng.lng,index:t,zoomLevel:u[t].getZoom()}});document.dispatchEvent(r)}}function K(e){let t=0;const o=new CustomEvent("location-zoom",{detail:{index:t,zoomLevel:u[t].getZoom()}});document.dispatchEvent(o)}function J(e){let t=e.target,o=t.getLatLng();t.setLatLng(new g.LatLng(o.lat,o.lng),{draggable:"true"});const r=new CustomEvent("location-move",{detail:{latitude:o.lat,longitude:o.lng,index:0}});document.dispatchEvent(r)}function X(e){if(e>0){console.warn("Corwardly refuse to add a map on split #"+(e+1));return}if(typeof u[e]>"u"){let t=document.getElementById("location_map");u[e]=g.map(t).setView([t.dataset.latitude,t.dataset.longitude],t.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(u[e]),u[e].on("click",H),u[e].on("zoomend",K)}}let c;const p=U();let G=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",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?_(this.groupProperties.totalAmount,"EUR"):_(this.groupProperties.totalAmount,this.entries[0].currency_code??"EUR")},filterForeignCurrencies(e){let t=[],o;for(let r in this.formData.enabledCurrencies)if(this.formData.enabledCurrencies.hasOwnProperty(r)){let n=this.formData.enabledCurrencies[r];n.code===e&&(o=n)}t.push(o),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 r in this.entries)this.entries.hasOwnProperty(r)&&(this.entries[r].foreign_currency_code=e)},filterNativeCurrencies(e){let t=[],o;for(let r in this.formData.enabledCurrencies)if(this.formData.enabledCurrencies.hasOwnProperty(r)){let n=this.formData.enabledCurrencies[r];n.code===e&&(o=n)}t.push(o),this.formData.nativeCurrencies=t;for(let r in this.entries)this.entries.hasOwnProperty(r)&&(this.entries[r].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 o in this.entries)this.entries.hasOwnProperty(o)&&(this.groupProperties.totalAmount=this.groupProperties.totalAmount+parseFloat(this.entries[o].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=c.t("firefly.errors_upload"),console.error(e)},init(){Promise.all([E("language","en_US")]).then(e=>{c=new z;const t=e[0].replace("-","_");c.locale=t,S(c,t).then(()=>{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=x());this.formStates.isSubmitting=!0,this.detectTransactionType();let e=R(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 o=new N;console.log(t),o.post(t).then(r=>{const n=r.data.data;if(this.groupProperties.id=parseInt(n.id),this.groupProperties.title=n.attributes.group_title??n.attributes.transactions[0].description,q(this.groupProperties.id,n.attributes.transactions)>0){this.notifications.wait.show=!0,this.notifications.wait.text=c.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=c.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=c.t("firefly.errors_submission",{errorMessage:e.message}),e.hasOwnProperty("errors")&&(this.entries=V(c,e.errors,this.entries))},addSplit(){this.entries.push(D()),setTimeout(()=>{M.init("select.ac-tags",{allowClear:!0,server:p.tag,liveServer:!0,clearEnd:!0,allowNew:!0,notFoundMessage:c.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;X(e);const t=function(o,r,n){return o.name_with_balance+'<br><small class="text-muted">'+c.t("firefly.account_type_"+o.type)+"</small>"};h({selector:"input.ac-source",serverUrl:p.account,onChange:O,onSelectItem:B,hiddenValue:this.items[e].source_account.alpine_name}),h({selector:"input.ac-dest",serverUrl:p.account,filters:this.filters.destination,onRenderItem:t,onChange:F,onSelectItem:I}),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 t=e.currentTarget,o=parseInt(t.attributes["data-index"].value);this.entries[o].hasLocation=!1,this.entries[o].latitude=null,this.entries[o].longitude=null,this.entries[o].zoomLevel=null;const r=new CustomEvent("location-remove",{detail:{index:o}});return document.dispatchEvent(r),!1}}},b={transactions:G,dates:P};function C(){Object.keys(b).forEach(e=>{console.log(`Loading page component "${e}"`);let t=b[e]();Alpine.data(e,()=>t)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),C()});window.bootstrapped&&(console.log("Loaded through window variable."),C());