SettlementService.ts
2,030 bytes
| 1 | import httpClient from '@/services/httpClient' |
|---|---|
| 2 | import type { IResultObject } from '@/types/IResultObject' |
| 3 | import type { ISettlementPlan, ISettlementSummary, IBalance } from '@/types/ISettlement' |
| 4 | import axios from 'axios' |
| 5 | |
| 6 | export default class SettlementService { |
| 7 | static async getSummary(tripId: string): Promise<IResultObject<ISettlementSummary>> { |
| 8 | try { |
| 9 | const response = await httpClient.get<ISettlementSummary>(`Settlements/trip/${tripId}/summary`) |
| 10 | return { data: response.data } |
| 11 | } catch (e) { |
| 12 | return { errors: SettlementService.handleError(e) } |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | static async getBalances(tripId: string): Promise<IResultObject<IBalance[]>> { |
| 17 | try { |
| 18 | const response = await httpClient.get<IBalance[]>(`Settlements/trip/${tripId}/balances`) |
| 19 | return { data: response.data } |
| 20 | } catch (e) { |
| 21 | return { errors: SettlementService.handleError(e) } |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | static async markPaid(paymentId: string): Promise<IResultObject<void>> { |
| 26 | try { |
| 27 | await httpClient.post(`Settlements/payments/${paymentId}/mark-paid`) |
| 28 | return { data: undefined } |
| 29 | } catch (e) { |
| 30 | return { errors: SettlementService.handleError(e) } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | static async confirmPayment(paymentId: string): Promise<IResultObject<void>> { |
| 35 | try { |
| 36 | await httpClient.post(`Settlements/payments/${paymentId}/confirm`) |
| 37 | return { data: undefined } |
| 38 | } catch (e) { |
| 39 | return { errors: SettlementService.handleError(e) } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | private static handleError(e: unknown): string[] { |
| 44 | if (axios.isAxiosError(e)) { |
| 45 | const data = e.response?.data |
| 46 | if (data?.errors && typeof data.errors === 'object') { |
| 47 | const messages: string[] = [] |
| 48 | for (const field of Object.values(data.errors)) { |
| 49 | if (Array.isArray(field)) messages.push(...field) |
| 50 | } |
| 51 | if (messages.length > 0) return messages |
| 52 | } |
| 53 | if (data?.title) return [data.title] |
| 54 | return [e.response?.statusText ?? 'Unknown error'] |
| 55 | } |
| 56 | return ['Network error or server unavailable'] |
| 57 | } |
| 58 | } |
| 59 | |