2025-06-22 00:21:09 +03:00

204 lines
6.3 KiB
JavaScript

import { d as derived, w as writable } from "./index2.js";
function calculateEqualSplit(totalAmount, participantCount) {
const amount = parseFloat(String(totalAmount));
if (isNaN(amount) || amount <= 0 || participantCount <= 0) {
return {
isValid: false,
error: "Invalid amount or participant count",
amountPerPerson: 0,
formattedAmount: "0.0000000"
};
}
const amountPerPerson = amount / participantCount;
const formattedAmount = amountPerPerson.toFixed(7);
return {
isValid: true,
amountPerPerson,
formattedAmount,
participantCount
};
}
const initialState = {
splitMethod: "equal",
// 'equal', 'percentage', or 'custom'
currentExpense: {
id: "",
description: "",
totalAmount: "",
participants: [],
createdAt: null,
createdBy: ""
},
history: [],
isLoading: false,
error: null
};
function createExpenseStore() {
const { subscribe, set, update } = writable(initialState);
return {
subscribe,
// Initialize a new expense
initializeExpense: (publicKey) => {
update((store) => ({
...store,
currentExpense: {
id: Date.now().toString(36) + Math.random().toString(36).substr(2),
description: "",
totalAmount: "",
participants: [],
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
createdBy: publicKey || ""
}
}));
},
// Import an expense from shared data
importExpense: (expenseData, currentUserAddress) => {
update((store) => {
if (!expenseData || !expenseData.id || !expenseData.description || !expenseData.totalAmount || !expenseData.creator) {
throw new Error("Invalid expense data");
}
return {
...store,
currentExpense: {
id: expenseData.id,
description: expenseData.description,
totalAmount: expenseData.totalAmount,
participants: [
// Add the creator as a participant (since current user is joining)
{
id: Date.now().toString(36),
name: "Creator",
address: expenseData.creator,
amount: "0"
// Will be calculated later
}
],
createdAt: expenseData.timestamp ? new Date(expenseData.timestamp).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
createdBy: currentUserAddress,
isJoined: true,
// Flag to indicate this is a joined expense
originalCreator: expenseData.creator
}
};
});
},
// Set split method and recalculate amounts if needed
setSplitMethod: (method) => {
update((store) => {
let updatedStore = {
...store,
splitMethod: method
};
if (method === "equal" && store.currentExpense.totalAmount && store.currentExpense.participants.length > 0) {
const totalAmount = parseFloat(String(store.currentExpense.totalAmount));
const totalPeople = store.currentExpense.participants.length + 1;
if (totalAmount > 0 && totalPeople > 1) {
const result = calculateEqualSplit(totalAmount, totalPeople);
const participantAmount = result.perPerson;
updatedStore.currentExpense.participants = store.currentExpense.participants.map((p) => ({
...p,
amount: participantAmount.toFixed(7)
}));
}
}
return updatedStore;
});
},
// Add current expense to history
saveExpenseToHistory: () => {
update((store) => {
const newHistory = [
{ ...store.currentExpense, savedAt: (/* @__PURE__ */ new Date()).toISOString() },
...store.history
];
if (typeof localStorage !== "undefined") {
try {
localStorage.setItem("expense_history", JSON.stringify(newHistory));
} catch (e) {
console.error("Failed to save expense history to localStorage", e);
}
}
return {
...store,
history: newHistory,
// Reset current expense
currentExpense: {
id: "",
description: "",
totalAmount: "",
participants: [],
createdAt: null,
createdBy: ""
}
};
});
},
// Load expense history from localStorage
loadHistory: () => {
if (typeof localStorage === "undefined") {
return;
}
try {
const savedHistory = localStorage.getItem("expense_history");
if (savedHistory) {
const parsedHistory = JSON.parse(savedHistory);
update((store) => ({
...store,
history: parsedHistory
}));
}
} catch (e) {
console.error("Failed to load expense history", e);
}
},
// Clear error state
clearError: () => update((store) => ({ ...store, error: null }))
};
}
const expenseStore = createExpenseStore();
derived(
expenseStore,
($expenseStore) => {
if (!$expenseStore.currentExpense.totalAmount) {
return "0";
}
const totalAmount = parseFloat(String($expenseStore.currentExpense.totalAmount));
const participantTotal = $expenseStore.currentExpense.participants.reduce(
(sum, p) => sum + parseFloat(p.amount || 0),
0
);
const creatorAmount = totalAmount - participantTotal;
return creatorAmount > 0 ? creatorAmount.toFixed(7) : "0";
}
);
const isExpenseValid = derived(
expenseStore,
($expenseStore) => {
const expense = $expenseStore.currentExpense;
if (!expense.description || !expense.totalAmount) {
return false;
}
const totalAmount = parseFloat(String(expense.totalAmount));
if (isNaN(totalAmount) || totalAmount <= 0) {
return false;
}
if (!expense.participants || expense.participants.length === 0) {
return false;
}
for (const participant of expense.participants) {
if (!participant.address || participant.address.length !== 56) {
return false;
}
const amount = parseFloat(participant.amount || 0);
if (isNaN(amount) || amount <= 0) {
return false;
}
}
return true;
}
);
export {
expenseStore as e,
isExpenseValid as i
};