Files
firefly-iii/public/build/assets/create-5a2ad8a8.js
2024-01-02 20:19:09 +01:00

2 lines
21 KiB
JavaScript

import{a as h,d as b,g as w,l as S,f as v,b as k,G as T}from"./get-10f2a251.js";import{f as C,k as g,I as x,l as I,m as p}from"./vendor-5ec3da0f.js";function m(){return{id:"",name:"",alpine_name:""}}function L(){let t=C(new Date,"yyyy-MM-dd HH:mm");return{description:"",amount:"",currency_code:"EUR",foreign_amount:"",foreign_currency_code:"",source_account:m(),destination_account:m(),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:{amount:[],foreign_amount:[],budget_id:[],category_name:[],piggy_bank_id:[]}}}function A(e,t){let o=[];for(let a in e)if(e.hasOwnProperty(a)){const n=e[a];let r={};r.description=n.description,r.source_name=n.source_account.name,r.destination_name=n.destination_account.name,r.amount=n.amount,r.currency_code=n.currency_code,r.date=n.date,r.interest_date=n.interest_date,r.book_date=n.book_date,r.process_date=n.process_date,r.due_date=n.due_date,r.payment_date=n.payment_date,r.invoice_date=n.invoice_date,r.budget_id=n.budget_id,r.category_name=n.category_name,r.piggy_bank_id=n.piggy_bank_id,n.hasLocation&&(r.longitude=n.longitude.toString(),r.latitude=n.latitude.toString(),r.zoom_level=n.zoomLevel),typeof n.foreign_currency_code<"u"&&n.foreign_currency_code.toString()!==""&&(r.foreign_currency_code=n.foreign_currency_code,typeof n.foreign_amount<"u"&&n.foreign_amount.toString()!==""&&(r.foreign_amount=n.foreign_amount),(typeof n.foreign_amount>"u"||n.foreign_amount.toString()==="")&&(delete r.foreign_amount,delete r.foreign_currency_code)),typeof n.source_account.id<"u"&&n.source_account.id.toString()!==""&&(r.source_id=n.source_account.id),typeof n.destination_account.id<"u"&&n.destination_account.id.toString()!==""&&(r.destination_id=n.destination_account.id),r.type=t,o.push(r)}return o}let O=class{post(t){let o="/api/v2/transactions";return h.post(o,t)}};class E{post(t,o,a){let n="/api/v1/attachments";return h.post(n,{filename:t,attachable_type:o,attachable_id:a})}upload(t,o){let a="./api/v1/attachments/"+t+"/upload";return axios.post(a,o)}}let q=class{list(t){return h.get("/api/v2/currencies",{params:t})}};class ${list(t){return h.get("/api/v2/budgets",{params:t})}}let l;const d={description:"/api/v2/autocomplete/transaction-descriptions",account:"/api/v2/autocomplete/accounts",category:"/api/v2/autocomplete/categories",tag:"/api/v2/autocomplete/tags"};let B=function(e,t){console.log("Now in uploadAttachments"),t=t.reverse();let o=[],a=0,n=[],r=document.querySelectorAll('input[name="attachments[]"]');console.log(r);for(const s in r)if(r.hasOwnProperty(s)&&/^0$|^[1-9]\d*$/.test(s)&&s<=4294967294){console.log("Now at attachment #"+s);for(const i in r[s].files)r[s].files.hasOwnProperty(i)&&/^0$|^[1-9]\d*$/.test(i)&&i<=4294967294&&(console.log("Will upload #"+i+" from attachment #"+s+" to transaction #"+t[s].transaction_journal_id),o.push({journal:t[s].transaction_journal_id,file:r[s].files[i]}),a++)}console.log("Found "+a+" attachments.");for(const s in o)o.hasOwnProperty(s)&&/^0$|^[1-9]\d*$/.test(s)&&s<=4294967294&&(console.log("Create file reader for file #"+s),function(i,c){let u=new FileReader;u.onloadend=function(f){f.target.readyState===FileReader.DONE&&(console.log("Done reading file #"+c),n.push({name:o[c].file.name,journal:o[c].journal,content:new Blob([f.target.result])}),n.length===a&&(console.log("Done reading file #"+c),P(n,e)))},u.readAsArrayBuffer(i.file)}(o[s],s));return a},P=function(e,t){let o=e.length,a=0;console.log("Will now upload "+o+" file(s) to journal with id #"+t);for(const n in e)if(e.hasOwnProperty(n)&&/^0$|^[1-9]\d*$/.test(n)&&n<=4294967294){console.log("Creating attachment #"+n);let r=new E;r.post(e[n].name,"TransactionJournal",e[n].journal).then(s=>{let i=parseInt(s.data.data.id);console.log("Created attachment #"+i+" for key #"+n),console.log("Uploading attachment #"+n),r.upload(i,e[n].content).then(c=>{if(a++,a===o){console.log("FINAL UPLOAD, redirect user to new transaction or reset form or whatever.");const u=new CustomEvent("upload-success",{some:"details"});document.dispatchEvent(u);return}console.log("Upload complete!")}).catch(c=>{console.error("Could not upload"),console.error(c),a++,a===o&&console.log("FINAL UPLOAD, redirect user to new transaction or reset form or whatever.")})}).catch(s=>{console.error("Could not create upload."),console.error(s),a++,a===o&&console.log("FINAL UPLOAD, redirect user to new transaction or reset form or whatever.")})}},M=function(){return{count:0,totalAmount:0,transactionType:"unknown",showSuccessMessage:!1,showErrorMessage:!1,defaultCurrency:{},entries:[],loadingCurrencies:!0,loadingBudgets:!0,loadingPiggyBanks:!0,loadingSubscriptions:!0,enabledCurrencies:[],nativeCurrencies:[],foreignCurrencies:[],budgets:[],piggyBanks:{},subscriptions:[],dateFields:["interest_date","book_date","process_date","due_date","payment_date","invoice_date"],foreignAmountEnabled:!0,filters:{source:[],destination:[]},errorMessageText:"",successMessageLink:"#",successMessageText:"",showError:!1,showSuccess:!1,showWaitMessage:!1,returnHereButton:!0,resetButton:!1,resetButtonEnabled:!1,rulesButton:!0,webhookButton:!0,submitting:!1,newGroupTitle:"",newGroupId:0,hasLocation:!1,latitude:51.959659235274,longitude:5.756805887265858,zoomLevel:13,detectTransactionType(){const e=this.entries[0].source_account.type??"unknown",t=this.entries[0].destination_account.type??"unknown";if(e==="unknown"&&t==="unknown"){this.transactionType="unknown",console.warn("Cannot infer transaction type from two unknown accounts.");return}if(e===t&&["Asset account","Loan","Debt","Mortgage"].includes(e)){this.transactionType="transfer",console.log('Transaction type is detected to be "'+this.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.transactionType="withdrawal",console.log('[a] Transaction type is detected to be "'+this.transactionType+'".'),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(e==="Asset account"&&t==="unknown"){this.transactionType="withdrawal",console.log('[b] Transaction type is detected to be "'+this.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.transactionType="withdrawal",console.log('[c] Transaction type is detected to be "'+this.transactionType+'".'),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(e==="Revenue account"&&["Asset account","Debt","Loan","Mortgage"].includes(t)){this.transactionType="deposit",console.log('Transaction type is detected to be "'+this.transactionType+'".');return}if(["Debt","Loan","Mortgage"].includes(e)&&t==="Asset account"){this.transactionType="deposit",console.log('Transaction type is detected to be "'+this.transactionType+'".');return}console.warn('Unknown account combination between "'+e+'" and "'+t+'".')},selectSourceAccount(e,t){const o=parseInt(t._searchInput.attributes["data-index"].value);document.querySelector("#form")._x_dataStack[0].$data.entries[o].source_account={id:e.id,name:e.name,alpine_name:e.name,type:e.type,currency_code:e.currency_code},console.log("Changed source account into a known "+e.type.toLowerCase()),document.querySelector("#form")._x_dataStack[0].detectTransactionType()},filterForeignCurrencies(e){console.log('filterForeignCurrencies("'+e+'")');let t=[],o;for(let a in this.enabledCurrencies)if(this.enabledCurrencies.hasOwnProperty(a)){let n=this.enabledCurrencies[a];n.code===e&&(o=n)}t.push(o),this.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.foreignAmountEnabled=!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.foreignAmountEnabled=!0);for(let a in this.entries)this.entries.hasOwnProperty(a)&&(this.entries[a].foreign_currency_code=e)},filterNativeCurrencies(e){console.log('filterNativeCurrencies("'+e+'")');let t=[],o;for(let a in this.enabledCurrencies)if(this.enabledCurrencies.hasOwnProperty(a)){let n=this.enabledCurrencies[a];n.code===e&&(o=n)}t.push(o),this.nativeCurrencies=t;for(let a in this.entries)this.entries.hasOwnProperty(a)&&(this.entries[a].currency_code=e)},changedAmount(e){const t=parseInt(e.target.dataset.index);this.entries[t].amount=parseFloat(e.target.value),this.totalAmount=0;for(let o in this.entries)this.entries.hasOwnProperty(o)&&(this.totalAmount=this.totalAmount+parseFloat(this.entries[o].amount));console.log("Changed amount to "+this.totalAmount)},selectDestAccount(e,t){const o=parseInt(t._searchInput.attributes["data-index"].value);document.querySelector("#form")._x_dataStack[0].$data.entries[o].destination_account={id:e.id,name:e.name,alpine_name:e.name,type:e.type,currency_code:e.currency_code},console.log("Changed destination account into a known "+e.type.toLowerCase()),document.querySelector("#form")._x_dataStack[0].detectTransactionType()},loadCurrencies(){this.enabledCurrencies=[],this.nativeCurrencies=[],this.foreignCurrencies=[],this.foreignCurrencies.push({id:0,name:"(no foreign currency)",code:"",default:!1,symbol:"",decimal_places:2}),console.log("Loading user currencies."),new q().list({}).then(t=>{for(let o in t.data.data)if(t.data.data.hasOwnProperty(o)){let a=t.data.data[o];if(a.attributes.enabled){let n={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};n.default&&(this.defaultCurrency=n),this.enabledCurrencies.push(n),this.nativeCurrencies.push(n),this.foreignCurrencies.push(n)}}this.loadingCurrencies=!1})},loadBudgets(){this.budgets=[],this.budgets.push({id:0,name:"(no budget)"}),console.log("Loading user budgets."),new $().list({}).then(t=>{for(let o in t.data.data)if(t.data.data.hasOwnProperty(o)){let a=t.data.data[o],n={id:a.id,name:a.attributes.name};this.budgets.push(n)}this.loadingBudgets=!1,console.log(this.budgets)})},loadPiggyBanks(){this.piggyBanks={};let e={0:{id:0,name:"(no group)",order:0,piggyBanks:[{id:0,name:"(no piggy bank)",order:0}]}};console.log("Loading user piggy banks."),new k().list({}).then(o=>{for(let a in o.data.data)if(o.data.data.hasOwnProperty(a)){let n=o.data.data[a],r=n.attributes.object_group_id??"0",s=n.attributes.object_group_title??"(no group)",i={id:n.id,name:n.attributes.name,order:n.attributes.order};e.hasOwnProperty(r)||(e[r]={id:r,name:s,order:n.attributes.object_group_order??0,piggyBanks:[]}),e[r].piggyBanks.push(i),e[r].piggyBanks.sort((c,u)=>c.order-u.order)}this.loadingPiggyBanks=!1,this.piggyBanks=Object.keys(e).sort().reduce((a,n)=>(a[n]=e[n],a),{})})},loadSubscriptions(){this.subscriptions={};let e={0:{id:0,name:"(no group)",order:0,subscriptions:[{id:0,name:"(no subscription)",order:0}]}};console.log("Loading user suscriptions."),new T().list({}).then(o=>{for(let a in o.data.data)if(o.data.data.hasOwnProperty(a)){let n=o.data.data[a],r=n.attributes.object_group_id??"0",s=n.attributes.object_group_title??"(no group)",i={id:n.id,name:n.attributes.name,order:n.attributes.order};e.hasOwnProperty(r)||(e[r]={id:r,name:s,order:n.attributes.object_group_order??0,subscriptions:[]}),e[r].subscriptions.push(i),e[r].subscriptions.sort((c,u)=>c.order-u.order)}this.loadingSubscriptions=!1,this.subscriptions=Object.keys(e).sort().reduce((a,n)=>(a[n]=e[n],a),{})})},changeSourceAccount(e,t){if(console.log("changeSourceAccount"),typeof e>"u"){const o=parseInt(t._searchInput.attributes["data-index"].value);if(document.querySelector("#form")._x_dataStack[0].$data.entries[o].source_account.name===t._searchInput.value){console.warn('Ignore hallucinated source account name change to "'+t._searchInput.value+'"'),document.querySelector("#form")._x_dataStack[0].detectTransactionType();return}document.querySelector("#form")._x_dataStack[0].$data.entries[o].source_account={name:t._searchInput.value,alpine_name:t._searchInput.value},console.log('Changed source account into a unknown account called "'+t._searchInput.value+'"'),document.querySelector("#form")._x_dataStack[0].detectTransactionType()}},changeDestAccount(e,t){if(document.querySelector("#form")._x_dataStack[0].$data.entries[0].destination_account,typeof e>"u"){const o=parseInt(t._searchInput.attributes["data-index"].value);if(document.querySelector("#form")._x_dataStack[0].$data.entries[o].destination_account.name===t._searchInput.value){console.warn('Ignore hallucinated destination account name change to "'+t._searchInput.value+'"'),document.querySelector("#form")._x_dataStack[0].detectTransactionType();return}document.querySelector("#form")._x_dataStack[0].$data.entries[o].destination_account={name:t._searchInput.value,alpine_name:t._searchInput.value},console.log('Changed destination account into a unknown account called "'+t._searchInput.value+'"'),document.querySelector("#form")._x_dataStack[0].detectTransactionType()}},changeCategory(e,t){const o=parseInt(t._searchInput.attributes["data-index"].value);if(typeof e<"u"&&e.name){document.querySelector("#form")._x_dataStack[0].$data.entries[o].category_name=e.name;return}document.querySelector("#form")._x_dataStack[0].$data.entries[o].category_name=t._searchInput.value},changeDescription(e,t){const o=parseInt(t._searchInput.attributes["data-index"].value);if(typeof e<"u"&&e.description){document.querySelector("#form")._x_dataStack[0].$data.entries[o].description=e.description;return}document.querySelector("#form")._x_dataStack[0].$data.entries[o].description=t._searchInput.value},addedSplit(){console.log("addedSplit"),g.init("input.ac-source",{server:d.account,serverParams:{types:this.filters.source},fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}},hiddenInput:!0,preventBrowserAutocomplete:!0,highlightTyped:!0,liveServer:!0,onChange:this.changeSourceAccount,onSelectItem:this.selectSourceAccount,onRenderItem:function(e,t,o){return e.name_with_balance+'<br><small class="text-muted">'+l.t("firefly.account_type_"+e.type)+"</small>"}}),g.init("input.ac-category",{server:d.category,fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}},valueField:"id",labelField:"name",highlightTyped:!0,onSelectItem:this.changeCategory,onChange:this.changeCategory}),g.init("input.ac-dest",{server:d.account,serverParams:{types:this.filters.destination},fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}},hiddenInput:!0,preventBrowserAutocomplete:!0,liveServer:!0,highlightTyped:!0,onSelectItem:this.selectDestAccount,onChange:this.changeDestAccount,onRenderItem:function(e,t,o){return e.name_with_balance+'<br><small class="text-muted">'+l.t("firefly.account_type_"+e.type)+"</small>"}}),this.filters.destination=[],g.init("input.ac-description",{server:d.description,fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}},valueField:"id",labelField:"description",highlightTyped:!0,onSelectItem:this.changeDescription,onChange:this.changeDescription})},processUpload(e){console.log("I am ALSO event listener for upload-success!"),console.log(e),this.showBarOrRedirect()},init(){Promise.all([w("language","en_US")]).then(e=>{l=new x;const t=e[0].replace("-","_");l.locale=t,S(l,t).then(()=>{this.addSplit()})}),this.loadCurrencies(),this.loadBudgets(),this.loadPiggyBanks(),this.loadSubscriptions(),document.addEventListener("upload-success",e=>{this.processUpload(e)}),this.filters.source=["Asset account","Loan","Debt","Mortgage","Revenue account"],this.filters.destination=["Expense account","Loan","Debt","Mortgage","Asset account"]},submitTransaction(){this.submitting=!0,this.showSuccessMessage=!1,this.showErrorMessage=!1,this.showWaitmessage=!1,this.detectTransactionType();let e=A(this.entries,this.transactionType),t={group_title:null,fire_webhooks:!1,apply_rules:!1,transactions:e};e.length>1&&(t.group_title=e[0].description);let o=new O;console.log(t),o.post(t).then(a=>{if(this.newGroupId=parseInt(a.data.data.id),this.newGroupTitle=t.group_title??t.transactions[0].description,B(this.newGroupId,a.data.data.attributes.transactions)>0){this.showWaitMessage=!0;return}this.showBarOrRedirect()}).catch(a=>{this.submitting=!1,console.log(a),typeof a.response<"u"&&this.parseErrors(a.response.data)})},showBarOrRedirect(){this.showWaitMessage=!1,this.submitting=!1,this.returnHereButton&&(this.showSuccessMessage=!0,this.successMessageLink="transactions/show/"+this.newGroupId,this.successMessageText=l.t("firefly.stored_journal_js",{description:this.newGroupTitle}),this.resetButton&&(this.entries=[],this.addSplit(),this.totalAmount=0)),this.returnHereButton||(window.location="transactions/show/"+this.newGroupId+"?transaction_group_id="+this.newGroupId+"&message=created")},parseErrors(e){this.setDefaultErrors(),this.showErrorMessage=!0,this.showSuccessMessage=!1,this.errorMessageText=l.t("firefly.errors_submission")+" "+e.message;let t,o;for(const a in e.errors)if(e.errors.hasOwnProperty(a)){if(a!=="group_title")switch(t=parseInt(a.split(".")[1]),o=a.split(".")[2],o){case"amount":case"date":case"budget_id":case"bill_id":case"description":case"tags":this.entries[t].errors[o]=e.errors[a];break;case"source_name":case"source_id":this.entries[t].errors.source_account=this.entries[t].errors.source_account.concat(e.errors[a]);break;case"destination_name":case"destination_id":this.entries[t].errors.destination_account=this.entries[t].errors.destination_account.concat(e.errors[a]);break;case"foreign_amount":case"foreign_currency_id":this.entries[t].errors.foreign_amount=this.entries[t].errors.foreign_amount.concat(e.errors[a]);break}typeof this.entries[t]<"u"&&(this.entries[t].errors.source_account=Array.from(new Set(this.entries[t].errors.source_account)),this.entries[t].errors.destination_account=Array.from(new Set(this.entries[t].errors.destination_account)))}console.log(this.entries[0].errors)},setDefaultErrors(){},addSplit(){this.entries.push(L()),setTimeout(()=>{I.init("select.ac-tags",{allowClear:!0,server:d.tag,liveServer:!0,clearEnd:!0,notFoundMessage:"(nothing found)",noCache:!0,fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}}});const e=this.entries.length-1;this.entries[e].map=p.map("mappie").setView([this.latitude,this.longitude],this.zoomLevel),p.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png",{maxZoom:19,attribution:'&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'}).addTo(this.entries[e].map),this.entries[e].map.on("click",this.addPointToMap),this.entries[e].map.on("zoomend",this.saveZoomOfMap)},250)},removeSplit(e){this.entries.splice(e,1),document.querySelector("#split-0-tab").click()},formattedTotalAmount(){return v(this.totalAmount,"EUR")},clearLocation(e){e.preventDefault();const t=e.currentTarget,o=parseInt(t.attributes["data-index"].value);return this.entries[o].hasLocation=!1,this.entries[o].marker.remove(),!1},saveZoomOfMap(e){let t=parseInt(e.sourceTarget._container.attributes["data-index"].value),o=document.querySelector("#form")._x_dataStack[0].$data.entries[t].map;document.querySelector("#form")._x_dataStack[0].$data.entries[t].zoomLevel=o.getZoom(),console.log("New zoom level: "+o.getZoom())},addPointToMap(e){let t=parseInt(e.originalEvent.currentTarget.attributes["data-index"].value),o=document.querySelector("#form")._x_dataStack[0].$data.entries[t].map,a=document.querySelector("#form")._x_dataStack[0].$data.entries[t].hasLocation;if(console.log("Has location: "+a),a===!1){console.log("False!");const n=new p.marker(e.latlng,{draggable:!0});n.on("dragend",function(r){var s=r.target,i=s.getLatLng();s.setLatLng(new p.LatLng(i.lat,i.lng),{draggable:"true"}),document.querySelector("#form")._x_dataStack[0].$data.entries[t].latitude=i.lat,document.querySelector("#form")._x_dataStack[0].$data.entries[t].longitude=i.lng}),n.addTo(o),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=o.getZoom()}}}},_={transactions:M,dates:b};function y(){Object.keys(_).forEach(e=>{console.log(`Loading page component "${e}"`);let t=_[e]();Alpine.data(e,()=>t)}),Alpine.start()}document.addEventListener("upload-success",e=>{console.log("I am event listener for upload-success"),console.log(e)});document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),y()});window.bootstrapped&&(console.log("Loaded through window variable."),y());