From e09fe77a5efb94dd585509bda0dc34ee2cd18c02 Mon Sep 17 00:00:00 2001 From: Vladimir Voronin Date: Mon, 6 Jan 2025 16:30:22 +0300 Subject: [PATCH] ver 2 --- public/service-worker.js | 1 + src/App.vue | 6 +- src/components/analytics/AnalyticsView.vue | 48 ++- src/components/auth/LoginView.vue | 44 +-- src/components/budgets/BudgetCategoryView.vue | 4 +- src/components/budgets/BudgetCreationView.vue | 11 +- src/components/budgets/BudgetList.vue | 152 ++++++--- .../budgets/BudgetTransactionView.vue | 49 ++- src/components/budgets/BudgetView.vue | 185 ++++++++--- .../budgets/TransactionEditDrawer.vue | 14 +- .../settings/CategorySettingView.vue | 2 +- .../settings/RecurrentSettingView.vue | 4 +- src/components/settings/SettingsView.vue | 2 +- .../settings/categories/CategoriesList.vue | 291 +++++++++-------- .../settings/categories/CategoryListItem.vue | 4 +- .../categories/CreateCategoryModal.vue | 14 +- .../settings/recurrent/RecurrentListItem.vue | 4 +- .../transactions/TransactionForm.vue | 5 +- .../transactions/TransactionFormContent.vue | 308 +++++++++--------- .../transactions/TransactionList.vue | 103 ++++-- src/main.ts | 3 + src/models/Budget.ts | 31 +- src/models/Transaction.ts | 11 +- src/services/axiosSetup.ts | 6 +- src/services/budgetsService.ts | 81 +++-- src/services/categoryService.ts | 2 +- src/services/transactionService.ts | 37 ++- src/services/userService.ts | 7 + src/stores/userStore.ts | 35 +- 29 files changed, 911 insertions(+), 553 deletions(-) create mode 100644 src/services/userService.ts diff --git a/public/service-worker.js b/public/service-worker.js index cd2339c..240065b 100644 --- a/public/service-worker.js +++ b/public/service-worker.js @@ -1,6 +1,7 @@ // public/service-worker.js self.addEventListener("push", (event) => { + console.log(event) const data = event.data.json(); console.log(data); const options = { diff --git a/src/App.vue b/src/App.vue index 3d911a6..778899d 100644 --- a/src/App.vue +++ b/src/App.vue @@ -2,13 +2,14 @@
-
diff --git a/src/components/auth/LoginView.vue b/src/components/auth/LoginView.vue index c1664c6..b05c722 100644 --- a/src/components/auth/LoginView.vue +++ b/src/components/auth/LoginView.vue @@ -36,10 +36,10 @@ diff --git a/src/components/budgets/BudgetCategoryView.vue b/src/components/budgets/BudgetCategoryView.vue index f6b4869..e6b9c78 100644 --- a/src/components/budgets/BudgetCategoryView.vue +++ b/src/components/budgets/BudgetCategoryView.vue @@ -13,7 +13,7 @@ const props = defineProps({ required: true }, budgetId: { - type: Number, + type: String, required: true } }); @@ -36,7 +36,7 @@ const stopEditing = () => { const spentPlannedRatio = computed(() => { return props.category.currentLimit ? (props.category.currentSpent / props.category.currentLimit) * 100 - : 0; + : props.category.currentSpent > 0 ? props.category.currentSpent : 0; }); // Синхронизация `currentLimit` с `props.category.currentLimit` при обновлении diff --git a/src/components/budgets/BudgetCreationView.vue b/src/components/budgets/BudgetCreationView.vue index 8396784..62bc52f 100644 --- a/src/components/budgets/BudgetCreationView.vue +++ b/src/components/budgets/BudgetCreationView.vue @@ -8,7 +8,6 @@ import DatePicker from "primevue/datepicker"; import {onMounted, ref} from "vue"; import {getMonthName} from "@/utils/utils"; import {Budget} from "@/models/Budget"; -import {createBudget} from "@/services/budgetsService"; const props = defineProps({ opened: { @@ -28,10 +27,10 @@ const budget = ref(new Budget()) const create = async () => { console.log(budget.value) try { - await createBudget(budget.value, createRecurrentPayments.value) - emits("budget-created"); + emits("budget-created", budget.value, createRecurrentPayments.value); } catch (e) { console.error(e) + throw e } } @@ -40,7 +39,7 @@ const cancel = () => { emits("close-modal"); } -onMounted(() => { +const resetForm = () => { budget.value.name = '' budget.value.dateTo = new Date(); budget.value.dateFrom = new Date(); @@ -58,8 +57,10 @@ onMounted(() => { budget.value.dateTo.setMonth(budget.value.dateTo.getMonth() + 2) } budget.value.name = getMonthName(budget.value.dateFrom.getMonth()) + ' ' + budget.value.dateFrom.getFullYear(); +} - +onMounted(() => { + resetForm() }) diff --git a/src/components/budgets/BudgetList.vue b/src/components/budgets/BudgetList.vue index a58bf63..b0df514 100644 --- a/src/components/budgets/BudgetList.vue +++ b/src/components/budgets/BudgetList.vue @@ -5,81 +5,106 @@

Бюджеты

+ +
-
-
{{ budget.name }}
- - - +
+
+
{{ budget.name }}
+
+ {{ formatDate(budget.dateFrom) }} - {{ formatDate(budget.dateTo) }} +
+ +
+
+ + + + +
-
- {{ formatDate(budget.dateFrom) }} - {{ formatDate(budget.dateTo) }} -
- - - - - - - - - - - + + + + + + + + + + + +
- - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + +
@@ -104,12 +120,15 @@ onMounted(async () => { " class="flex bg-white min-w-fit max-h-fit flex-row items-center gap-4 w-full ">
-

- {{ transaction.category.icon }}

- + + +
+ +
+
+
+
+ +
+
{{ warn.message.icon }}
+
+ {{ warn.message.title }} + +
+
+ +
+ +
+
+
+
+
+
@@ -58,6 +91,7 @@

Расходы

+
-{{ formatAmount(totalExpenses) }} ({{ formatAmount(totalExpenses - totalIncomes) }}) @@ -65,6 +99,8 @@
+ +

в первый период

@@ -136,7 +172,7 @@
Факт. траты 📛
- {{ formatAmount(totalInstantExpenses)}} ₽ + {{ formatAmount(totalInstantExpenses) }} ₽
@@ -144,7 +180,7 @@
Остаток на траты
- {{ formatAmount(totalInstantIncomes - totalInstantExpenses)}} ₽ + {{ formatAmount(totalInstantIncomes - totalInstantExpenses) }} ₽
@@ -170,8 +206,10 @@
- @@ -181,6 +219,7 @@ :transaction="transaction" :is-list="true" @transaction-updated="updateTransactions" + @transaction-checked="updateTransactions" />
@@ -211,8 +250,9 @@
    + :is-list="false" + @transaction-updated="updateTransactions" + @transaction-checked="updateTransactions"/>
@@ -241,7 +281,7 @@
@@ -268,8 +308,10 @@
- @@ -280,6 +322,7 @@ :is-list="true" @transaction-updated="updateTransactions" + />
@@ -288,16 +331,16 @@ - - - - - - - - + + + + + + + + - + { + await hideWarnRequest(route.params.id, warnId) + await fetchWarns() +} + const leftForUnplanned = ref(0) const budget = ref() +const warns = ref<[Warn]>() +const checkWarnsExists = computed(() => { + console.log(warns?.value && warns.value.length > 0 ? "true" : "false"); + return warns?.value?.length > 0; +}); + + const plannedIncomes = ref([]) const totalIncomes = computed(() => { let totalIncome = 0; @@ -365,7 +425,7 @@ const totalIncomes = computed(() => { const totalInstantIncomes = computed(() => { let totalIncome = 0; - transactions.value.filter(t => t.transactionType.code=='INSTANT' && t.category.type.code =='INCOME' ).forEach((i) => { + transactions.value.filter(t => t.type.code == 'INSTANT' && t.category.type.code == 'INCOME').forEach((i) => { totalIncome += i.amount }) return totalIncome @@ -383,7 +443,7 @@ const totalIncomeLeftToGet = computed(() => { const totalLoans = computed(() => { let value = 0 - categories.value.filter((cat) => cat.category.id == 29).forEach(cat => { + categories.value.filter((cat) => cat.category.id == "675850148198643f121e465d").forEach(cat => { value += cat.currentLimit }) return value @@ -391,18 +451,18 @@ const totalLoans = computed(() => { const loansRatio = computed(() => { - return totalExpenses.value == 0? 0 : totalLoans.value / totalExpenses.value * 100 + return totalExpenses.value == 0 ? 0 : totalLoans.value / totalExpenses.value * 100 }) const savingRatio = computed(() => { - return totalExpenses.value == 0? 0 :totalSaving.value / totalExpenses.value * 100 + return totalExpenses.value == 0 ? 0 : totalSaving.value / totalExpenses.value * 100 }) const totalSaving = computed(() => { let value = 0 - categories.value.filter((cat) => cat.category.id == 35).forEach(cat => { + categories.value.filter((cat) => cat.category.id == "675850148198643f121e466a").forEach(cat => { value += cat.currentLimit }) return value @@ -430,7 +490,7 @@ const closeDrawer = async () => { } const dailyRatio = computed(() => { - const value = totalExpenses.value == 0? 0 : (totalExpenses.value - totalLoans.value - totalSaving.value) / totalExpenses.value + const value = totalExpenses.value == 0 ? 0 : (totalExpenses.value - totalLoans.value - totalSaving.value) / totalExpenses.value return value * 100 }) @@ -441,13 +501,13 @@ const plannedExpenses = ref([]) const totalExpenses = computed(() => { let totalExpense = 0; categories.value.forEach((cat) => { - let catValue = cat.currentLimit - cat.categoryPlannedLimit - - plannedExpenses.value.filter(t => t.category.id == cat.category.id).forEach((i) => { - - catValue += i.amount - }) + let catValue = cat.currentLimit + // plannedExpenses.value.filter(t => t.category.id == cat.category.id).forEach((i) => { + // + // catValue += i.amount + // }) + // totalExpense += catValue }) @@ -465,7 +525,7 @@ const totalPlannedExpenses = computed(() => { const totalInstantExpenses = computed(() => { let totalExpenses = 0; - transactions.value.filter(t => t.transactionType.code=='INSTANT' && t.category.type.code =='EXPENSE').forEach((i) => { + transactions.value.filter(t => t.type.code == 'INSTANT' && t.category.type.code == 'EXPENSE').forEach((i) => { totalExpenses += i.amount }) return totalExpenses @@ -487,14 +547,14 @@ const transactions = ref([]) const selectedCategoryId = ref() const selectCategoryType = (categoryId) => { - if (selectedCategoryId.value==categoryId) { + if (selectedCategoryId.value == categoryId) { selectedCategoryId.value = null } else { selectedCategoryId.value = categoryId } } const filteredTransactions = computed(() => { - return selectedCategoryId.value ? transactions.value.filter(i => i.category.id==selectedCategoryId.value) : transactions.value + return selectedCategoryId.value ? transactions.value.filter(i => i.category.id == selectedCategoryId.value) : transactions.value }) const fetchBudgetTransactions = async () => { transactions.value = await getBudgetTransactions(route.params.id, 'INSTANT') @@ -502,7 +562,12 @@ const fetchBudgetTransactions = async () => { } const updateTransactions = async () => { - await Promise.all([fetchPlannedIncomes(), fetchPlannedExpenses(), fetchBudgetCategories(), fetchBudgetTransactions()]) + + setTimeout(async () => { + await Promise.all([fetchBudgetInfo(),fetchWarns()]) + + }, 10) + } const categories = ref([]) @@ -541,18 +606,27 @@ const transactionCategoriesSums = computed(() => { // } -const budgetInfo = ref(); +const budgetInfo = ref(); const fetchBudgetInfo = async () => { budget.value = await getBudgetInfo(route.params.id); + plannedExpenses.value = budget.value?.plannedExpenses.copyWithin() + plannedIncomes.value = budget.value?.plannedIncomes.copyWithin() + transactions.value = budget.value?.transactions.copyWithin() + categories.value = budget.value?.categories updateLoading.value = false } + const updateBudgetCategory = async (category) => { // loading.value = true - await updateBudgetCategoryRequest(budget.value.id, category) + category = await updateBudgetCategoryRequest(budget.value.id, category) + await fetchBudgetInfo() + setTimeout(async () => { + await fetchWarns() + }, 500) // categories.value = await getBudgetCategories(route.params.id) @@ -590,6 +664,7 @@ const incomesByPeriod = computed(() => { let incomesUntil25 = 0 let incomesFrom25 = 0 plannedIncomes.value.forEach((i) => { + i.date = new Date(i.date) if (i.date >= budget.value?.dateFrom && i.date <= twentyFour.value) { @@ -606,17 +681,19 @@ const incomesByPeriod = computed(() => { const expensesByPeriod = computed(() => { let expensesUntil25 = 0 let expensesFrom25 = 0 + let totalPlannedExpensesSum = 0 plannedExpenses.value.forEach((i) => { - + i.date = new Date(i.date) if (i.date >= budget.value?.dateFrom && i.date <= twentyFour.value) { expensesUntil25 += i.amount } else { expensesFrom25 += i.amount } + totalPlannedExpensesSum += i.amount }) categories.value.forEach((i) => { - expensesUntil25 += (i.currentLimit - i.categoryPlannedLimit) / 2 - expensesFrom25 += (i.currentLimit - i.categoryPlannedLimit) / 2 + expensesUntil25 += (i.currentLimit - i.currentPlanned) / 2 + expensesFrom25 += (i.currentLimit - i.currentPlanned) / 2 }) @@ -760,7 +837,11 @@ const incomeExpenseChartOptions = ref({ } } } -}); +}) + +const fetchWarns = async (hidden: Boolean = null) => { + warns.value = await getWarns(route.params.id, hidden) +} onMounted(async () => { @@ -768,11 +849,12 @@ onMounted(async () => { try { await Promise.all([ fetchBudgetInfo(), + fetchWarns() // budget.value = await getBudgetInfo(route.params.id), - fetchPlannedIncomes(), - fetchPlannedExpenses(), - fetchBudgetCategories(), - fetchBudgetTransactions(), + // fetchPlannedIncomes(), + // fetchPlannedExpenses(), + // fetchBudgetCategories(), + // fetchBudgetTransactions(), ]); } catch (error) { console.error('Error during fetching data:', error); @@ -795,7 +877,6 @@ onMounted(async () => { } - .max-h-tlist { max-height: 1170px; /* Ограничение высоты списка */ } diff --git a/src/components/budgets/TransactionEditDrawer.vue b/src/components/budgets/TransactionEditDrawer.vue index c37dc95..1bd473c 100644 --- a/src/components/budgets/TransactionEditDrawer.vue +++ b/src/components/budgets/TransactionEditDrawer.vue @@ -39,10 +39,6 @@ const props = defineProps({ categoryType: { type: String, required: false - }, - transactions: { - type: Array as () => Array, - required: false } }); @@ -258,7 +254,7 @@ const closeDrawer = () => emit('close-drawer'); const keyboardOpen = ref(false); const isMobile = ref(false); const userAgent = ref(null); -const transactions = ref(props.transactions); +const transactions = ref(null); // Мониторинг при монтировании onMounted(async () => { loading.value = true; @@ -267,10 +263,12 @@ onMounted(async () => { prepareData(); + console.log("is editing " + !isEditing.value) if ( !isEditing.value) { - await getTransactions('INSTANT', 'EXPENSE',null, user.value.id ).then(transactionsResponse => transactions.value = transactionsResponse.data); - transactions.value = transactions.value.slice(0,3) - console.log(transactions.value.slice(0,3)) + console.log("here blyat") + await getTransactions('INSTANT', 'EXPENSE',null, user.value.id, false, 3 ) + .then(transactionsResponse => transactions.value = transactionsResponse.data); + } loading.value = false; const deviceInfo = platform; diff --git a/src/components/settings/CategorySettingView.vue b/src/components/settings/CategorySettingView.vue index beed5c5..21f5198 100644 --- a/src/components/settings/CategorySettingView.vue +++ b/src/components/settings/CategorySettingView.vue @@ -36,7 +36,7 @@ onMounted(async () => {
-

Categories

+

Категории

- + +
diff --git a/src/components/transactions/TransactionList.vue b/src/components/transactions/TransactionList.vue index 536c6e3..57547f2 100644 --- a/src/components/transactions/TransactionList.vue +++ b/src/components/transactions/TransactionList.vue @@ -1,12 +1,15 @@ @@ -84,20 +119,32 @@ onMounted(async () => { - +
+ + +
+ +
+ +
- + animationDuration=".5s"/>
diff --git a/src/main.ts b/src/main.ts index abb382a..208f1de 100644 --- a/src/main.ts +++ b/src/main.ts @@ -10,11 +10,13 @@ import Ripple from "primevue/ripple"; import ToastService from 'primevue/toastservice' import Tooltip from 'primevue/tooltip'; import { createPinia } from 'pinia'; +import ConfirmationService from 'primevue/confirmationservice'; const app = createApp(App); app.use(router); app.use(ToastService); +app.use(ConfirmationService); app.use(createPinia()) app.directive('ripple', Ripple); app.directive('tooltip', Tooltip); @@ -24,6 +26,7 @@ app.use(PrimeVue, { } }); + app.config.globalProperties.$primevue.config.locale = { firstDayOfWeek: 1, // Устанавливаем понедельник как первый день недели dayNames: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"], diff --git a/src/models/Budget.ts b/src/models/Budget.ts index af601fe..dfcfb37 100644 --- a/src/models/Budget.ts +++ b/src/models/Budget.ts @@ -1,20 +1,27 @@ import {Transaction} from "@/models/Transaction"; -import {Category, CategorySetting} from "@/models/Category"; +import {Category} from "@/models/Category"; -export class BudgetInfo { - budget: Budget +export class Budget { + id: number + name: string + dateFrom: Date + dateTo: Date + createdAt: Date plannedExpenses: [Transaction] plannedIncomes: [Transaction] + categories: [BudgetCategory] transactions: [Transaction] - transactionCategoriesSums: [] - totalIncomes: number - totalExpenses: number - chartData: [[]] - unplannedCategories: [BudgetCategory] + warns: [Warn] } -export class Budget { +export class Warn { + id: string + severity: string + message: string +} + +export class BudgetInfo { id: number name: string dateFrom: Date @@ -23,6 +30,8 @@ export class Budget { } export class BudgetCategory { - category: Category; - categorySetting: CategorySetting + category: Category + currentSpent: BigDecimal // отображает сумму потраченных на данный момент средств по категории + currentLimit: BigDecimal // отображает текущий лимит по категории + currentPlanned: BigDecimal // отображает текущую сумму запланированных расходов по категории } diff --git a/src/models/Transaction.ts b/src/models/Transaction.ts index e0a436d..36ae3bc 100644 --- a/src/models/Transaction.ts +++ b/src/models/Transaction.ts @@ -1,23 +1,24 @@ import {Category} from "@/models/Category"; +import {User} from "@/models/User"; export class Transaction { - id: number; - transactionType: TransactionType; + id: String; + type: TransactionType; + user: User category: Category; comment: string; date: Date; amount: number + parentId: String isDone: boolean; } -export class TransactionCategoriesSum{ +export class TransactionCategoriesSum { category: Category; sum: number } - - export class TransactionType { code: string; name: string; diff --git a/src/services/axiosSetup.ts b/src/services/axiosSetup.ts index 1bedd16..f3beb50 100644 --- a/src/services/axiosSetup.ts +++ b/src/services/axiosSetup.ts @@ -4,8 +4,8 @@ import { useRouter } from 'vue-router'; // Создаем экземпляр axios const api = axios.create({ - baseURL: 'https://luminic.space/api/v1', - // baseURL: 'http://localhost:8000/api/v1', + baseURL: 'https://luminic.space/api/', + // baseURL: 'http://localhost:8082/api', }); // Устанавливаем токен из localStorage при каждом запуске @@ -19,7 +19,7 @@ api.interceptors.response.use( (response) => response, (error) => { - if (error.response && error.response.status === 401) { + if (error.response && error.response.status === 403) { localStorage.removeItem('token'); const router = useRouter(); router.push('/login'); diff --git a/src/services/budgetsService.ts b/src/services/budgetsService.ts index 5c61f9a..7d3b8a6 100644 --- a/src/services/budgetsService.ts +++ b/src/services/budgetsService.ts @@ -4,25 +4,32 @@ import {format} from "date-fns"; // Импортируете настроенный экземпляр axios export const getBudgetInfos = async () => { + try { - let response = await apiClient.get('/budgets/'); + + let response = await apiClient.get('/budgets'); let budgetInfos = response.data; budgetInfos.forEach((budgetInfo: Budget) => { budgetInfo.dateFrom = new Date(budgetInfo.dateFrom); budgetInfo.dateTo = new Date(budgetInfo.dateTo); - // budgetInfo.plannedExpenses.forEach(e => { - // e.date = new Date(e.date) - // }) - // - // budgetInfo.plannedIncomes.forEach(e => { - // e.date = new Date(e.date) - // }) - // - // budgetInfo.transactions.forEach(e => { - // e.date = new Date(e.date) - // }) + budgetInfo.plannedExpenses?.forEach(e => { + e.date = new Date(e.date) + }) + + budgetInfo.plannedIncomes?.forEach(e => { + e.date = new Date(e.date) + }) + + budgetInfo.transactions?.forEach(e => { + e.date = new Date(e.date) + }) }) return budgetInfos + } catch (e) { + console.log(e) + throw e + + } } export const getBudgetTransactions = async (budgetId, transactionType, categoryType) => { @@ -66,18 +73,50 @@ export const getBudgetInfo = async (budget_id: number) => { }; + +export const getWarns = async (budgetId: string, hidden: Boolean = null) => { + let url = `/budgets/${budgetId}/warns` + if (hidden) { + url += `?hidden=${hidden}` + } + let warns = await apiClient.get(url); + return warns.data +} + +export const hideWarnRequest = async (budgetId: string, warnId: string) => { + await apiClient.post(`/budgets/${budgetId}/warns/${warnId}/hide`); +} + export const updateBudgetCategoryRequest = async (budget_id, category: BudgetCategory) => { - await apiClient.put('/budgets/' + budget_id + '/category', category); + return await apiClient.post('/budgets/' + budget_id + '/categories/' + category.category.id + "/limit", {"limit": category.currentLimit}).then(i => i.data); } export const createBudget = async (budget: Budget, createRecurrent: Boolean) => { - budget.dateFrom = format(budget.dateFrom, 'yyyy-MM-dd') - budget.dateTo = format(budget.dateTo, 'yyyy-MM-dd') - let data = { - budget: budget, - createRecurrent: createRecurrent + + try { + + let budgetToCreate = JSON.parse(JSON.stringify(budget)); + budgetToCreate.dateFrom = format(budget.dateFrom, 'yyyy-MM-dd') + budgetToCreate.dateTo = format(budget.dateTo, 'yyyy-MM-dd') + let data = { + budget: budgetToCreate, + createRecurrent: createRecurrent + } + await apiClient.post('/budgets/', data); + + } catch (e){ + console.error(e) + throw e + } +} + + +export const deleteBudgetRequest = async (budgetId: string) => { + try { + // throw Error("test") + let response = await apiClient.delete(`/budgets/${budgetId}`); + } catch (error) { + console.log(error); + throw error; } - await apiClient.post('/budgets', data); - budget.dateFrom = format(budget.dateFrom, 'dd.mm.yy') - budget.dateTo = format(budget.dateTo, 'dd.mm.yy') } \ No newline at end of file diff --git a/src/services/categoryService.ts b/src/services/categoryService.ts index f75d7e4..be055fa 100644 --- a/src/services/categoryService.ts +++ b/src/services/categoryService.ts @@ -5,7 +5,7 @@ import {Category} from "@/models/Category"; // Импортируете нас export const getCategories = async (type = null) => { type = type ? type : '' - return await apiClient.get('/categories/?type=' + type); + return await apiClient.get('/categories?type=' + type); }; export const getCategoryTypes = async () => { diff --git a/src/services/transactionService.ts b/src/services/transactionService.ts index da7c97d..b747531 100644 --- a/src/services/transactionService.ts +++ b/src/services/transactionService.ts @@ -7,9 +7,10 @@ export const getTransaction = async (transactionId: int) => { return await apiClient.post(`/transactions/${transactionId}`,); } -export const getTransactions = async (transaction_type = null, category_type = null, category_id = null, user_id = null, limit = null, offset = null) => { +export const getTransactions = async (transaction_type = null, category_type = null, category_id = null, user_id = null, is_child = null, limit = null, offset = null) => { const params = {}; + console.log(is_child) // Add the parameters to the params object if they are not null if (transaction_type) { params.transaction_type = transaction_type; @@ -25,6 +26,9 @@ export const getTransactions = async (transaction_type = null, category_type = n if (user_id) { params.user_id = user_id } + if (is_child!=null){ + params.is_child = is_child + } if (limit) { params.limit = limit } @@ -33,22 +37,25 @@ export const getTransactions = async (transaction_type = null, category_type = n } // Use axios to make the GET request, passing the params as the second argument - return await apiClient.get('/transactions/', { + return await apiClient.get('/transactions', { params: params }); } export const createTransactionRequest = async (transaction: Transaction) => { transaction.date = format(transaction.date, 'yyyy-MM-dd') - let transactionResponse = await apiClient.post('/transactions', transaction); - console.log(transaction.date) + let transactionResponse = await apiClient.post('/transactions', transaction); + transaction.date = new Date(transaction.date); return transactionResponse.data }; export const updateTransactionRequest = async (transaction: Transaction) => { const id = transaction.id - transaction.date = format(transaction.date, 'yyyy-MM-dd') + // console.log(transaction.isDone) + // transaction.date = transaction.date.setHours(0,0,0,0) + transaction.date = format(transaction.date, "yyyy-MM-dd") + const response = await apiClient.put(`/transactions/${id}`, transaction); transaction = response.data transaction.date = new Date(transaction.date); @@ -56,15 +63,15 @@ export const updateTransactionRequest = async (transaction: Transaction) => { return transaction }; -export const setTransactionDoneRequest = async (transaction: Transaction) => { - const id = transaction.id - // transaction.date = format(transaction.date, 'yyyy-MM-dd') - const response = await apiClient.put(`/transactions/${id}/done`, transaction); - transaction = response.data - transaction.date = new Date(transaction.date); - - return transaction -}; +// export const setTransactionDoneRequest = async (transaction: Transaction) => { +// const id = transaction.id +// // transaction.date = format(transaction.date, 'yyyy-MM-dd') +// const response = await apiClient.patch(`/transactions/${id}/set-done`, transaction); +// // transaction = response.data +// // transaction.date = new Date(transaction.date); +// +// // return transaction +// }; export const deleteTransactionRequest = async (id: number) => { return await apiClient.delete(`/transactions/${id}`); @@ -74,7 +81,7 @@ export const getTransactionTypes = async () => { return await apiClient.get('/transactions/types'); } -export const getTransactionCategoriesSums = async () => { +export const getTransactionCategoriesSums = async () => { let response = await apiClient.get('/transactions/categories/_calc_sums'); return response.data; } \ No newline at end of file diff --git a/src/services/userService.ts b/src/services/userService.ts new file mode 100644 index 0000000..c9aacff --- /dev/null +++ b/src/services/userService.ts @@ -0,0 +1,7 @@ +import apiClient from '@/services/axiosSetup'; + + +export const getUsers = async () => { + let users = await apiClient.get('/users/'); + return users.data; +} \ No newline at end of file diff --git a/src/stores/userStore.ts b/src/stores/userStore.ts index 90aa70c..9fefb16 100644 --- a/src/stores/userStore.ts +++ b/src/stores/userStore.ts @@ -1,17 +1,20 @@ -import { defineStore } from 'pinia'; -import { ref } from 'vue'; +import {defineStore} from 'pinia'; +import {ref} from 'vue'; import apiClient from "@/services/axiosSetup"; +import {useRoute, useRouter} from "vue-router"; export const useUserStore = defineStore('user', () => { const user = ref(null); const loadingUser = ref(true); + const router = useRouter(); + const route = useRoute(); async function fetchUserProfile() { // Убираем проверку на `loadingUser`, чтобы не блокировать запрос if (!user.value) { loadingUser.value = true; try { - const response = await apiClient.get('/auth/users/me'); // запрос к API для получения данных пользователя + const response = await apiClient.get('/auth/me'); // запрос к API для получения данных пользователя if (response.status !== 200) throw new Error('Ошибка загрузки данных пользователя'); user.value = response.data; @@ -24,5 +27,29 @@ export const useUserStore = defineStore('user', () => { } } - return { user, loadingUser, fetchUserProfile }; + // Основная функция для логина + async function login( username, password, tg_id=null) { + try { + let response; + if (tg_id) { + response = await apiClient.post('/auth/token/tg', {tg_id: tg_id}); + } else { + response = await apiClient.post('/auth/login', { + username: username, + password: password, + }); + } + + const token = response.data.token; + localStorage.setItem('token', token); + apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`; + await fetchUserProfile(); + await router.push(route.query['back'] ? route.query['back'].toString() : '/'); + } catch (error) { + console.error(error); + alert('Ошибка входа. Проверьте логин и пароль.'); + } + }; + + return {user, loadingUser, fetchUserProfile, login}; });