Add some services function

This commit is contained in:
2023-09-14 23:02:35 +07:00
parent 46e0f3d2d2
commit b96007b375
7 changed files with 166 additions and 43 deletions
@@ -32,7 +32,6 @@ export default class HomeController {
if (this.homeView) { if (this.homeView) {
this.homeView.addHandlerEventWalletForm( this.homeView.addHandlerEventWalletForm(
this.handlerSaveWallet.bind(this), this.handlerSaveWallet.bind(this),
this.handlerGetAllCategory.bind(this),
); );
this.homeView.loadPage( this.homeView.loadPage(
@@ -51,6 +50,7 @@ export default class HomeController {
this.homeView.handlerEventTransactionDialog( this.homeView.handlerEventTransactionDialog(
this.handlerSaveTransaction.bind(this), this.handlerSaveTransaction.bind(this),
this.handlerSaveWallet.bind(this),
); );
} }
} }
@@ -3,14 +3,16 @@ export default class Transaction {
id = Transaction.createIdTransactions(), id = Transaction.createIdTransactions(),
categoryName = '', categoryName = '',
date = '', date = '',
note = 'None', note = '',
amount = 0, amount = 0,
idUser,
}) { }) {
this.id = id; this.id = id;
this.categoryName = categoryName; this.categoryName = categoryName;
this.date = date; this.date = date;
this.note = note; this.note = note;
this.amount = amount; this.amount = amount;
this.idUser = idUser;
} }
static createIdTransactions() { static createIdTransactions() {
@@ -22,4 +22,16 @@ export default class CategoryService extends CommonService {
return null; return null;
} }
async getCategoryByName(nameCategory) {
const data = await this.getDataFromProp(
'name',
nameCategory,
this.defaultPath,
);
if (data) return data;
return null;
}
} }
@@ -66,11 +66,39 @@ export default class CommonService {
async getAllDataFromPath(path = this.defaultPath) { async getAllDataFromPath(path = this.defaultPath) {
this.connectToDb(); this.connectToDb();
const result = await this.firebaseService.getAllDataFromPath(path); const results = await timeOutConnect(
this.firebaseService.getAllDataFromPath(path),
);
const listData = [];
const data = await timeOutConnect(result); if (results) {
// Convert format object
results.forEach((data) => {
listData.push(convertDataObjectToModel(data));
});
if (data) return data; return listData;
}
return null;
}
async getListDataFromProp(property, value, path = this.defaultPath) {
this.connectToDb();
const results = await timeOutConnect(
this.firebaseService.getListDataFromProp(path, property, value),
);
const listData = [];
if (results) {
// Convert format object
results.forEach((data) => {
listData.push(convertDataObjectToModel(data));
});
return listData;
}
return null; return null;
} }
@@ -100,7 +100,7 @@ class FirebaseService {
onValue( onValue(
ref(this.db, path), ref(this.db, path),
(snapshot) => { (snapshot) => {
const data = []; const listData = [];
// snapshot is a type of data by Firebase define // snapshot is a type of data by Firebase define
snapshot.forEach((childSnapshot) => { snapshot.forEach((childSnapshot) => {
@@ -111,11 +111,40 @@ class FirebaseService {
// data = dataTemp; // data = dataTemp;
// } // }
const id = childSnapshot.key; const id = childSnapshot.key;
const val = childSnapshot.val(); const data = childSnapshot.val();
data.push({ id, ...val }); listData.push({ id, data });
}); });
resolve(data); resolve(listData);
},
{
onlyOnce: true,
},
);
});
}
getListDataFromProp(path, property, value) {
return new Promise((resolve) => {
onValue(
ref(this.db, path),
(snapshot) => {
let id;
let data;
const listData = [];
// snapshot is a type of data by Firebase define
snapshot.forEach((childSnapshot) => {
const dataTemp = childSnapshot.val();
if (dataTemp[property] === value) {
id = childSnapshot.key;
data = dataTemp;
listData.push({ id, data });
}
});
resolve(listData);
}, },
{ {
onlyOnce: true, onlyOnce: true,
@@ -14,4 +14,18 @@ export default class TransactionService extends CommonService {
async saveTransaction(transaction) { async saveTransaction(transaction) {
await this.save(transaction); await this.save(transaction);
} }
async getListTransactionByIdUser(idUser) {
const results = this.getListDataFromProp(
'idUser',
idUser,
this.defaultPath,
);
if (results) {
return results;
}
return null;
}
} }
+72 -34
View File
@@ -36,7 +36,10 @@ export default class HomeView extends CommonView {
getWalletByIdUser, getWalletByIdUser,
getAllCategory, getAllCategory,
) { ) {
this.getWalletByIdUser = getWalletByIdUser; // Init function // Init function
this.getWalletByIdUser = getWalletByIdUser;
this.getAllCategory = getAllCategory;
this.toggleLoaderSpinner(); this.toggleLoaderSpinner();
const user = await getInfoUserLogin(); const user = await getInfoUserLogin();
@@ -55,18 +58,20 @@ export default class HomeView extends CommonView {
this.loadEvent(); this.loadEvent();
// Init data // Init data
this.loadData(getAllCategory); this.loadData();
} }
} }
this.toggleLoaderSpinner(); this.toggleLoaderSpinner();
} }
async loadData(getAllCategory) { async loadData() {
await this.loadWalletUser(); await this.loadWalletUser();
await this.loadCategory(getAllCategory); await this.loadCategory(this.getAllCategory);
this.loadSummaryTab();
} }
// ---------------------LOAD DATA---------------------//
/** /**
* Load wallet user * Load wallet user
*/ */
@@ -86,16 +91,52 @@ export default class HomeView extends CommonView {
} }
async updateAmountWallet(amount, saveWallet) { async updateAmountWallet(amount, saveWallet) {
this.wallet.amount += +amount; this.wallet.amount += amount;
if (amount > 0) {
this.wallet.inflow += amount;
} else {
this.wallet.outflow -= amount;
}
await saveWallet(this.wallet); await saveWallet(this.wallet);
} }
// ---------------------TRANSACTIONS DIALOG---------------------// /**
handlerEventTransactionDialog(saveTransaction) { * Load category data
* @param {function} getAllCategory Get all category function
*/
async loadCategory(getAllCategory) {
this.listCategory = await getAllCategory();
if (this.listCategory) {
this.renderCategoryItem();
}
}
loadSummaryTab() {
const inflowValue = document.querySelector('.inflow__text--income');
const outflowValue = document.querySelector('.outflow__text--outcome');
const totalValue = document.querySelector('.summary__total');
const { inflow } = this.wallet;
const { outflow } = this.wallet;
const total = inflow - outflow;
inflowValue.textContent = `+$ ${formatNumber(inflow)}`;
outflowValue.textContent = `-$ ${formatNumber(outflow)}`;
totalValue.textContent = `${total >= 0 ? '+' : '-'}$ ${formatNumber(
Math.abs(total),
)}`;
}
// ---------------------END---------------------//
// ---------------------TRANSACTION DIALOG---------------------//
handlerEventTransactionDialog(saveTransaction, saveWallet) {
this.transactionDialog.addEventListener('submit', (e) => { this.transactionDialog.addEventListener('submit', (e) => {
e.preventDefault(); e.preventDefault();
this.submitTransactionDialog(saveTransaction); this.submitTransactionDialog(saveTransaction, saveWallet);
}); });
this.transactionDialog.addEventListener('input', () => { this.transactionDialog.addEventListener('input', () => {
@@ -116,33 +157,40 @@ export default class HomeView extends CommonView {
}); });
} }
async submitTransactionDialog(saveTransaction) { async submitTransactionDialog(saveTransaction, saveWallet) {
this.toggleLoaderSpinner(); this.toggleLoaderSpinner();
this.transactionDialog.close(); this.transactionDialog.close();
try { try {
const transactionForm = document.getElementById('formAddTransaction'); const transactionForm = document.getElementById('formAddTransaction');
const dateEl = transactionForm.querySelector("[name='selected_date']"); const date = transactionForm.querySelector("[name='selected_date']");
const categoryNameEl = transactionForm.querySelector( const categoryName = transactionForm.querySelector(
"[name='category_name']", "[name='category_name']",
); );
const amountEl = transactionForm.querySelector("[name='amount']"); const amount = transactionForm.querySelector("[name='amount']");
const noteEl = transactionForm.querySelector("[name='note']"); const note = transactionForm.querySelector("[name='note']");
const transaction = new Transaction({ const transaction = new Transaction({
categoryName: categoryNameEl.value, categoryName: categoryName.value,
date: dateEl.value, date: date.value,
amount: +amountEl.value, amount: -+amount.value,
note: noteEl.value, note: note.value,
idUser: this.wallet.idUser,
}); });
await saveTransaction(transaction); await saveTransaction(transaction);
// Update wallet info
this.updateAmountWallet(-+amount.value, saveWallet);
this.showSuccessToast( this.showSuccessToast(
MESSAGE.ADD_TRANSACTION_SUCCESS, MESSAGE.ADD_TRANSACTION_SUCCESS,
MESSAGE.DEFAULT_MESSAGE, MESSAGE.DEFAULT_MESSAGE,
); );
this.clearInputTransactionForm(transactionForm); this.clearInputTransactionForm(transactionForm);
// Reload data
this.loadData();
} catch (error) { } catch (error) {
this.showErrorToast(error); this.showErrorToast(error);
} }
@@ -164,18 +212,6 @@ export default class HomeView extends CommonView {
// ---------------------END DIALOG---------------------// // ---------------------END DIALOG---------------------//
// ---------------------SELECTED CATEGORY DIALOG---------------------// // ---------------------SELECTED CATEGORY DIALOG---------------------//
/**
* Load category data
* @param {function} getAllCategory Get all category function
*/
async loadCategory(getAllCategory) {
this.listCategory = await getAllCategory();
if (this.listCategory) {
this.renderCategoryItem();
}
}
handlerEventCategoryDialog() { handlerEventCategoryDialog() {
this.categoryDialog.addEventListener('input', () => { this.categoryDialog.addEventListener('input', () => {
setTimeout(() => { setTimeout(() => {
@@ -261,13 +297,14 @@ export default class HomeView extends CommonView {
date: changeDateFormat(date), date: changeDateFormat(date),
amount: +amount, amount: +amount,
note, note,
idUser: this.wallet.idUser,
}); });
await saveTransaction(transaction); await saveTransaction(transaction);
await this.updateAmountWallet(+amount, saveWallet); // Update wallet await this.updateAmountWallet(+amount, saveWallet); // Update wallet
this.loadWalletUser(); this.loadData();
// Hide loader spinner // Hide loader spinner
this.toggleLoaderSpinner(); this.toggleLoaderSpinner();
@@ -298,11 +335,11 @@ export default class HomeView extends CommonView {
// ---------------------END DIALOG---------------------// // ---------------------END DIALOG---------------------//
// ---------------------WALLET DIALOG--------------------- // // ---------------------WALLET DIALOG--------------------- //
addHandlerEventWalletForm(saveWallet, getAllCategory) { addHandlerEventWalletForm(saveWallet) {
this.walletDialog.addEventListener('submit', (e) => { this.walletDialog.addEventListener('submit', (e) => {
e.preventDefault(); e.preventDefault();
this.submitWalletForm(saveWallet, getAllCategory); this.submitWalletForm(saveWallet);
}); });
this.walletDialog.addEventListener('input', (e) => { this.walletDialog.addEventListener('input', (e) => {
@@ -311,7 +348,7 @@ export default class HomeView extends CommonView {
}); });
} }
async submitWalletForm(saveWallet, getAllCategory) { async submitWalletForm(saveWallet) {
this.walletDialog.close(); this.walletDialog.close();
this.toggleLoaderSpinner(); this.toggleLoaderSpinner();
@@ -325,6 +362,7 @@ export default class HomeView extends CommonView {
walletName, walletName,
amount: +amount, amount: +amount,
idUser: this.user.id, idUser: this.user.id,
inflow: +amount,
}); });
await saveWallet(wallet); await saveWallet(wallet);
@@ -335,7 +373,7 @@ export default class HomeView extends CommonView {
); );
this.loadEvent(); // Load event page this.loadEvent(); // Load event page
this.loadData(getAllCategory); // Load data from database into page this.loadData(); // Load data from database into page
} catch (error) { } catch (error) {
// Show toast error // Show toast error
this.showErrorToast(error); this.showErrorToast(error);