Compare commits
86 Commits
maf
...
6abc5f8b6d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6abc5f8b6d | ||
|
|
460dcd17ef | ||
| 61916dc6da | |||
|
|
704f58b1a1 | ||
|
|
d9703d31ae | ||
|
|
e93c3d6bae | ||
|
|
3ed9cf5ebd | ||
|
|
b71eadd4f9 | ||
|
|
5c9d7c5db1 | ||
|
|
9729ff2f82 | ||
|
|
b78774bc39 | ||
|
|
4aa7e82429 | ||
| bade93ad57 | |||
| 47e1ed3891 | |||
|
|
4ff99b62c8 | ||
|
|
58627356f4 | ||
|
|
dcbde4db23 | ||
|
|
9e14849014 | ||
|
|
e2c0ab5389 | ||
|
|
a06a75ee97 | ||
|
|
937e8db776 | ||
|
|
64aa24c07b | ||
|
|
b2e903e968 | ||
|
|
c2a27abcac | ||
|
|
a2bfff5790 | ||
|
|
66cfd71ef5 | ||
|
|
aa0bdecc50 | ||
|
|
0708f833c8 | ||
|
|
0ffeb41605 | ||
|
|
44d9fbb0f6 | ||
|
|
32efbb0324 | ||
|
|
1711ee410d | ||
|
|
b0d632dcb7 | ||
|
|
435efbcb90 | ||
|
|
9611ff2088 | ||
|
|
4e2bf0da6c | ||
|
|
298ce03aa6 | ||
|
|
5d6797b16a | ||
|
|
2ffad479ba | ||
|
|
9b25c62662 | ||
|
|
1b3d01c78c | ||
|
|
0ef4b52fcc | ||
|
|
2043976998 | ||
|
|
3cbc868e9b | ||
|
|
c74ce24727 | ||
|
|
14bbd62262 | ||
|
|
0c95b6aa6e | ||
|
|
f77cc57cab | ||
|
|
59b81148ac | ||
|
|
04e4946f3d | ||
|
|
319f8f7d7b | ||
|
|
9069e3dbcf | ||
|
|
71a8707241 | ||
|
|
0e140548b7 | ||
|
|
12b8e4bd0e | ||
|
|
f4f1600782 | ||
|
|
caf6f3fe60 | ||
|
|
df3a06051b | ||
|
|
c80e5daf7d | ||
|
|
ea11d72c00 | ||
|
|
9e03187a95 | ||
|
|
667358fa0b | ||
|
|
69298c2ffa | ||
|
|
82e5c79868 | ||
|
|
65f7316c82 | ||
|
|
12cf1b6323 | ||
|
|
4444f2b808 | ||
|
|
0ccfa57d7b | ||
| f2f741411b | |||
|
|
6e7a237df9 | ||
|
|
6a45f3d67d | ||
|
|
c5c3b56200 | ||
| 556fc5af20 | |||
|
|
03115a04ec | ||
|
|
de4e692bce | ||
|
|
d324d204d5 | ||
|
|
b4cb0a200e | ||
| 02fcf07235 | |||
| e11c1e4fc4 | |||
|
|
83dfa66d85 | ||
|
|
c07c9dd07d | ||
|
|
a41c2b79af | ||
|
|
5cac4d6dde | ||
|
|
a8da1c6a70 | ||
|
|
8c7dbd24ad | ||
|
|
694925e326 |
@@ -13,13 +13,64 @@ jobs:
|
||||
name: Build Docker Image
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# ✅ 使用 Gitea 兼容的代码检出方式
|
||||
# 网络连接测试
|
||||
- name: Test network connectivity
|
||||
run: |
|
||||
echo "Testing network connectivity to Gitea server..."
|
||||
MAX_RETRIES=5
|
||||
RETRY_DELAY=10
|
||||
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
echo "Network test attempt $i/$MAX_RETRIES"
|
||||
if curl -s --connect-timeout 10 -f http://192.168.31.14:14200 > /dev/null; then
|
||||
echo "✅ Gitea server is reachable"
|
||||
exit 0
|
||||
else
|
||||
echo "❌ Network test failed, waiting $RETRY_DELAY seconds..."
|
||||
sleep $RETRY_DELAY
|
||||
fi
|
||||
done
|
||||
|
||||
echo "❌ All network tests failed"
|
||||
exit 1
|
||||
|
||||
- name: Checkout code
|
||||
uses: https://gitea.com/actions/checkout@v3
|
||||
with:
|
||||
gitea-server: http://192.168.31.14:14200
|
||||
token: ${{ secrets.GITEA_TOKEN }}
|
||||
ref: ${{ gitea.ref }} # 必须传递 Gitea 的 ref 参数
|
||||
# 添加重试策略
|
||||
continue-on-error: true
|
||||
|
||||
# 手动重试逻辑
|
||||
- name: Retry checkout if failed
|
||||
if: steps.checkout.outcome == 'failure'
|
||||
run: |
|
||||
echo "First checkout attempt failed, retrying..."
|
||||
MAX_RETRIES=3
|
||||
RETRY_DELAY=15
|
||||
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
echo "Retry attempt $i/$MAX_RETRIES"
|
||||
|
||||
# 清理可能的部分检出
|
||||
rm -rf .git || true
|
||||
git clean -fdx || true
|
||||
|
||||
# 使用git命令直接检出
|
||||
git init
|
||||
git remote add origin http://192.168.31.14:14200/${{ gitea.repository }}
|
||||
git config http.extraHeader "Authorization: Bearer ${{ secrets.GITEA_TOKEN }}"
|
||||
|
||||
if git fetch --depth=1 origin "${{ gitea.ref }}"; then
|
||||
git checkout FETCH_HEAD
|
||||
echo "Checkout successful on retry $i"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Retry $i failed, waiting $RETRY_DELAY seconds..."
|
||||
sleep $RETRY_DELAY
|
||||
done
|
||||
|
||||
echo "All checkout attempts failed"
|
||||
exit 1
|
||||
|
||||
- name: Cleanup old containers
|
||||
run: |
|
||||
@@ -28,7 +79,7 @@ jobs:
|
||||
|
||||
- name: Build new image
|
||||
run: |
|
||||
RETRIES=3
|
||||
RETRIES=20
|
||||
DELAY=10
|
||||
count=0
|
||||
until docker build -t $IMAGE_NAME .; do
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -404,3 +404,4 @@ FodyWeavers.xsd
|
||||
Web/dist
|
||||
# ESLint
|
||||
.eslintcache
|
||||
.aider*
|
||||
|
||||
9080
.pans/v2.pen
Normal file
9080
.pans/v2.pen
Normal file
File diff suppressed because it is too large
Load Diff
80
.sisyphus/notepads/statistics-year-selection/decisions.md
Normal file
80
.sisyphus/notepads/statistics-year-selection/decisions.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# Decisions - Statistics Year Selection Enhancement
|
||||
|
||||
## [2026-01-28] Architecture Decisions
|
||||
|
||||
### Frontend Implementation Strategy
|
||||
|
||||
#### 1. Date Picker Mode Toggle
|
||||
- Add a toggle switch in the date picker popup to switch between "按月" (month) and "按年" (year) modes
|
||||
- When "按年" selected: use `columns-type="['year']"`
|
||||
- When "按月" selected: use `columns-type="['year', 'month']` (current behavior)
|
||||
|
||||
#### 2. State Management
|
||||
- Add `dateSelectionMode` ref: `'month'` | `'year'`
|
||||
- When year-only mode: set `currentMonth = 0` to indicate full year
|
||||
- Keep `currentYear` as integer (unchanged)
|
||||
- Update `selectedDate` array dynamically based on mode:
|
||||
- Year mode: `['YYYY']`
|
||||
- Month mode: `['YYYY', 'MM']`
|
||||
|
||||
#### 3. Display Logic
|
||||
- Nav bar title: `currentYear年` when `currentMonth === 0`, else `currentYear年currentMonth月`
|
||||
- Chart titles: Update to reflect year or year-month scope
|
||||
|
||||
#### 4. API Calls
|
||||
- Pass `month: currentMonth.value || 0` to all API calls
|
||||
- Backend will handle month=0 as year-only query
|
||||
|
||||
### Backend Implementation Strategy
|
||||
|
||||
#### 1. Repository Layer Change
|
||||
**File**: `Repository/TransactionRecordRepository.cs`
|
||||
**Method**: `BuildQuery()` lines 81-86
|
||||
|
||||
```csharp
|
||||
if (year.HasValue)
|
||||
{
|
||||
if (month.HasValue && month.Value > 0)
|
||||
{
|
||||
// Specific month
|
||||
var dateStart = new DateTime(year.Value, month.Value, 1);
|
||||
var dateEnd = dateStart.AddMonths(1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Entire year
|
||||
var dateStart = new DateTime(year.Value, 1, 1);
|
||||
var dateEnd = new DateTime(year.Value + 1, 1, 1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Service Layer
|
||||
- No changes needed - services already pass month parameter to repository
|
||||
- Services will receive month=0 for year-only queries
|
||||
|
||||
#### 3. API Controller
|
||||
- No changes needed - already accepts year/month parameters
|
||||
|
||||
### Testing Strategy
|
||||
|
||||
#### Backend Tests
|
||||
- Test year-only query returns all transactions for that year
|
||||
- Test month-specific query still works
|
||||
- Test edge cases: year boundaries, leap years
|
||||
|
||||
#### Frontend Tests
|
||||
- Test toggle switches picker mode correctly
|
||||
- Test year selection updates state and fetches data
|
||||
- Test display updates correctly for year vs year-month
|
||||
|
||||
### User Experience Flow
|
||||
|
||||
1. User clicks date picker in nav bar
|
||||
2. Popup opens with toggle: "按月 | 按年"
|
||||
3. User selects mode (default: 按月 for backward compatibility)
|
||||
4. User selects date(s) and confirms
|
||||
5. Statistics refresh with new scope
|
||||
6. Display updates to show scope (year or year-month)
|
||||
27
.sisyphus/notepads/statistics-year-selection/issues.md
Normal file
27
.sisyphus/notepads/statistics-year-selection/issues.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Issues - Statistics Year Selection Enhancement
|
||||
|
||||
## [2026-01-28] Backend Repository Limitation
|
||||
|
||||
### Issue
|
||||
`TransactionRecordRepository.BuildQuery()` requires both year AND month parameters to be present. Year-only queries (month=null or month=0) are not supported.
|
||||
|
||||
### Impact
|
||||
- Cannot query full-year statistics from the frontend
|
||||
- Current implementation only supports month-level granularity
|
||||
- All statistics endpoints rely on `QueryAsync(year, month, ...)`
|
||||
|
||||
### Solution
|
||||
Modify `BuildQuery()` method in `Repository/TransactionRecordRepository.cs` to support:
|
||||
1. Year-only queries (when year provided, month is null or 0)
|
||||
2. Month-specific queries (when both year and month provided - current behavior)
|
||||
|
||||
### Implementation Location
|
||||
- File: `Repository/TransactionRecordRepository.cs`
|
||||
- Method: `BuildQuery()` lines 81-86
|
||||
- Also need to update service layer to handle month=0 or null
|
||||
|
||||
### Testing Requirements
|
||||
- Test year-only query returns all transactions for that year
|
||||
- Test month-specific query still works as before
|
||||
- Test edge cases: leap years, year boundaries
|
||||
- Verify all statistics endpoints work with year-only mode
|
||||
181
.sisyphus/notepads/statistics-year-selection/learnings.md
Normal file
181
.sisyphus/notepads/statistics-year-selection/learnings.md
Normal file
@@ -0,0 +1,181 @@
|
||||
# Learnings - Statistics Year Selection Enhancement
|
||||
|
||||
## [2026-01-28] Initial Analysis
|
||||
|
||||
### Current Implementation
|
||||
- **File**: `Web/src/views/StatisticsView.vue`
|
||||
- **Current picker**: `columns-type="['year', 'month']` (year-month only)
|
||||
- **State variables**:
|
||||
- `currentYear` - integer year
|
||||
- `currentMonth` - integer month (1-12)
|
||||
- `selectedDate` - array `['YYYY', 'MM']` for picker
|
||||
- **API calls**: All endpoints use `{ year, month }` parameters
|
||||
|
||||
### Vant UI Year-Only Pattern
|
||||
- **Key prop**: `columns-type="['year']"`
|
||||
- **Picker value**: Single-element array `['YYYY']`
|
||||
- **Confirmation**: `selectedValues[0]` contains year string
|
||||
|
||||
### Implementation Strategy
|
||||
1. Add UI toggle to switch between year-month and year-only modes
|
||||
2. When year-only selected, set `currentMonth = 0` or null to indicate full year
|
||||
3. Backend API already supports year-only queries (when month=0 or null)
|
||||
4. Update display logic to show "YYYY年" vs "YYYY年MM月"
|
||||
|
||||
### API Compatibility - CRITICAL FINDING
|
||||
- **Backend limitation**: `TransactionRecordRepository.BuildQuery()` (lines 81-86) requires BOTH year AND month
|
||||
- Current logic: `if (year.HasValue && month.HasValue)` - year-only queries are NOT supported
|
||||
- **Must modify repository** to support year-only queries:
|
||||
- When year provided but month is null/0: query entire year (Jan 1 to Dec 31)
|
||||
- When both year and month provided: query specific month (current behavior)
|
||||
- All statistics endpoints use `QueryAsync(year, month, ...)` pattern
|
||||
|
||||
### Required Backend Changes
|
||||
**File**: `Repository/TransactionRecordRepository.cs`
|
||||
**Method**: `BuildQuery()` lines 81-86
|
||||
**Change**: Modify year/month filtering logic to support year-only queries
|
||||
|
||||
```csharp
|
||||
// Current (line 81-86):
|
||||
if (year.HasValue && month.HasValue)
|
||||
{
|
||||
var dateStart = new DateTime(year.Value, month.Value, 1);
|
||||
var dateEnd = dateStart.AddMonths(1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
|
||||
// Needed:
|
||||
if (year.HasValue)
|
||||
{
|
||||
if (month.HasValue && month.Value > 0)
|
||||
{
|
||||
// Specific month
|
||||
var dateStart = new DateTime(year.Value, month.Value, 1);
|
||||
var dateEnd = dateStart.AddMonths(1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Entire year
|
||||
var dateStart = new DateTime(year.Value, 1, 1);
|
||||
var dateEnd = new DateTime(year.Value + 1, 1, 1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Existing Patterns
|
||||
- BudgetView.vue uses same year-month picker pattern
|
||||
- Dayjs used for all date formatting: `dayjs().format('YYYY-MM-DD')`
|
||||
- Date picker values always arrays for Vant UI
|
||||
## [2026-01-28] Repository BuildQuery() Enhancement
|
||||
|
||||
### Implementation Completed
|
||||
- **File Modified**: `Repository/TransactionRecordRepository.cs` lines 81-94
|
||||
- **Change**: Updated year/month filtering logic to support year-only queries
|
||||
|
||||
### Logic Changes
|
||||
```csharp
|
||||
// Old: Required both year AND month
|
||||
if (year.HasValue && month.HasValue) { ... }
|
||||
|
||||
// New: Support year-only queries
|
||||
if (year.HasValue)
|
||||
{
|
||||
if (month.HasValue && month.Value > 0)
|
||||
{
|
||||
// 查询指定年月
|
||||
var dateStart = new DateTime(year.Value, month.Value, 1);
|
||||
var dateEnd = dateStart.AddMonths(1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 查询整年数据(1月1日到下年1月1日)
|
||||
var dateStart = new DateTime(year.Value, 1, 1);
|
||||
var dateEnd = new DateTime(year.Value + 1, 1, 1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Behavior
|
||||
- **Month-specific** (month.HasValue && month.Value > 0): Query from 1st of month to 1st of next month
|
||||
- **Year-only** (month is null or 0): Query from Jan 1 to Jan 1 of next year
|
||||
- **No year provided**: No date filtering applied
|
||||
|
||||
### Verification
|
||||
- All 14 tests pass: `dotnet test WebApi.Test/WebApi.Test.csproj`
|
||||
- No breaking changes to existing functionality
|
||||
- Chinese comments added for business logic clarity
|
||||
|
||||
### Key Pattern
|
||||
- Use `month.Value > 0` check to distinguish year-only (0/null) from month-specific (1-12)
|
||||
- Date range is exclusive on upper bound (`< dateEnd`) to avoid including boundary dates
|
||||
|
||||
## [2026-01-28] Frontend Year-Only Selection Implementation
|
||||
|
||||
### Changes Made
|
||||
**File**: `Web/src/views/StatisticsView.vue`
|
||||
|
||||
#### 1. Nav Bar Title Display (Line 12)
|
||||
- Updated to show "YYYY年" when `currentMonth === 0`
|
||||
- Shows "YYYY年MM月" when month is selected
|
||||
- Template: `{{ currentMonth === 0 ? \`${currentYear}年\` : \`${currentYear}年${currentMonth}月\` }}`
|
||||
|
||||
#### 2. Date Picker Popup (Lines 268-289)
|
||||
- Added toggle switch using `van-tabs` component
|
||||
- Two modes: "按月" (month) and "按年" (year)
|
||||
- Tabs positioned above the date picker
|
||||
- Dynamic `columns-type` based on selection mode:
|
||||
- Year mode: `['year']`
|
||||
- Month mode: `['year', 'month']`
|
||||
|
||||
#### 3. State Management (Line 347)
|
||||
- Added `dateSelectionMode` ref: `'month'` | `'year'`
|
||||
- Default: `'month'` for backward compatibility
|
||||
- `currentMonth` set to `0` when year-only selected
|
||||
|
||||
#### 4. Confirmation Handler (Lines 532-544)
|
||||
- Updated to handle both year-only and year-month modes
|
||||
- When year mode: `newMonth = 0`
|
||||
- When month mode: `newMonth = parseInt(selectedValues[1])`
|
||||
|
||||
#### 5. API Calls (All Statistics Endpoints)
|
||||
- Updated all API calls to use `month: currentMonth.value || 0`
|
||||
- Ensures backend receives `0` for year-only queries
|
||||
- Modified functions:
|
||||
- `fetchMonthlyData()` (line 574)
|
||||
- `fetchCategoryData()` (lines 592, 610, 626)
|
||||
- `fetchDailyData()` (line 649)
|
||||
- `fetchBalanceData()` (line 672)
|
||||
- `loadCategoryBills()` (line 1146)
|
||||
|
||||
#### 6. Mode Switching Watcher (Lines 1355-1366)
|
||||
- Added `watch(dateSelectionMode)` to update `selectedDate` array
|
||||
- When switching to year mode: `selectedDate = [year.toString()]`
|
||||
- When switching to month mode: `selectedDate = [year, month]`
|
||||
|
||||
#### 7. Styling (Lines 1690-1705)
|
||||
- Added `.date-picker-header` styles for tabs
|
||||
- Clean, minimal design matching Vant UI conventions
|
||||
- Proper spacing and background colors
|
||||
|
||||
### Vant UI Patterns Used
|
||||
- **van-tabs**: For mode switching toggle
|
||||
- **van-date-picker**: Dynamic `columns-type` prop
|
||||
- **van-popup**: Container for picker and tabs
|
||||
- Composition API with `watch` for reactive updates
|
||||
|
||||
### User Experience
|
||||
1. Click nav bar date → popup opens with "按月" default
|
||||
2. Switch to "按年" → picker shows only year column
|
||||
3. Select year and confirm → `currentMonth = 0`
|
||||
4. Nav bar shows "2025年" instead of "2025年1月"
|
||||
5. All statistics refresh with year-only data
|
||||
|
||||
### Verification
|
||||
- Build succeeds: `cd Web && pnpm build`
|
||||
- No TypeScript errors
|
||||
- No breaking changes to existing functionality
|
||||
- Backward compatible with month-only selection
|
||||
218
AGENTS.md
Normal file
218
AGENTS.md
Normal file
@@ -0,0 +1,218 @@
|
||||
# PROJECT KNOWLEDGE BASE - EmailBill
|
||||
|
||||
**Generated:** 2026-01-28
|
||||
**Commit:** 5c9d7c5
|
||||
**Branch:** main
|
||||
|
||||
## OVERVIEW
|
||||
Full-stack budget tracking app with .NET 10 backend and Vue 3 frontend.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
EmailBill/
|
||||
├── Common/ # Shared utilities and abstractions
|
||||
├── Entity/ # Database entities (FreeSql ORM)
|
||||
├── Repository/ # Data access layer
|
||||
├── Service/ # Business logic layer
|
||||
├── WebApi/ # ASP.NET Core Web API
|
||||
├── WebApi.Test/ # Backend tests (xUnit)
|
||||
└── Web/ # Vue 3 frontend (Vite + Vant UI)
|
||||
```
|
||||
|
||||
## WHERE TO LOOK
|
||||
| Task | Location | Notes |
|
||||
|------|----------|-------|
|
||||
| Entity definitions | Entity/ | BaseEntity pattern, FreeSql attributes |
|
||||
| Data access | Repository/ | BaseRepository, GlobalUsings |
|
||||
| Business logic | Service/ | Jobs, Email services, App settings |
|
||||
| API endpoints | WebApi/Controllers/ | DTO patterns, REST controllers |
|
||||
| Frontend views | Web/src/views/ | Vue composition API |
|
||||
| API clients | Web/src/api/ | Axios-based HTTP clients |
|
||||
| Tests | WebApi.Test/ | xUnit + NSubstitute + FluentAssertions |
|
||||
|
||||
## Build & Test Commands
|
||||
|
||||
### Backend (.NET 10)
|
||||
```bash
|
||||
# Build and run
|
||||
dotnet build EmailBill.sln
|
||||
dotnet run --project WebApi/WebApi.csproj
|
||||
|
||||
# Run all tests
|
||||
dotnet test WebApi.Test/WebApi.Test.csproj
|
||||
|
||||
# Run single test class
|
||||
dotnet test --filter "FullyQualifiedName~BudgetStatsTest"
|
||||
|
||||
# Run single test method
|
||||
dotnet test --filter "FullyQualifiedName~BudgetStatsTest.GetCategoryStats_月度_Test"
|
||||
|
||||
# Clean
|
||||
dotnet clean EmailBill.sln
|
||||
```
|
||||
|
||||
### Frontend (Vue 3)
|
||||
```bash
|
||||
cd Web
|
||||
|
||||
# Setup and dev
|
||||
pnpm install
|
||||
pnpm dev
|
||||
|
||||
# Build and preview
|
||||
pnpm build
|
||||
pnpm preview
|
||||
|
||||
# Lint and format
|
||||
pnpm lint # ESLint with auto-fix
|
||||
pnpm format # Prettier formatting
|
||||
```
|
||||
|
||||
## C# Code Style
|
||||
|
||||
**Namespaces & Imports:**
|
||||
- File-scoped namespaces: `namespace Entity;`
|
||||
- Global usings in `Common/GlobalUsings.cs`
|
||||
- Sort using statements alphabetically
|
||||
|
||||
**Naming:**
|
||||
- Classes/Methods: `PascalCase`
|
||||
- Interfaces: `IPascalCase`
|
||||
- Private fields: `_camelCase`
|
||||
- Parameters/locals: `camelCase`
|
||||
|
||||
**Entities:**
|
||||
- Inherit from `BaseEntity`
|
||||
- Use `[Column]` attributes for FreeSql ORM
|
||||
- IDs via Snowflake: `YitIdHelper.NextId()`
|
||||
- Use XML docs (`///`) for public APIs
|
||||
- **Chinese comments for business logic** (per `.github/csharpe.prompt.md`)
|
||||
|
||||
**Best Practices:**
|
||||
- Use modern C# syntax (records, pattern matching, nullable types)
|
||||
- Use `IDateTimeProvider` instead of `DateTime.Now` for testability
|
||||
- Avoid deep nesting, keep code flat and readable
|
||||
- Reuse utilities from `Common` project
|
||||
|
||||
**Example:**
|
||||
```csharp
|
||||
namespace Entity;
|
||||
|
||||
/// <summary>
|
||||
/// 实体基类
|
||||
/// </summary>
|
||||
public abstract class BaseEntity
|
||||
{
|
||||
[Column(IsPrimary = true)]
|
||||
public long Id { get; set; } = YitIdHelper.NextId();
|
||||
|
||||
public DateTime CreateTime { get; set; } = DateTime.Now;
|
||||
}
|
||||
```
|
||||
|
||||
## Vue/TypeScript Style
|
||||
|
||||
**Component Structure:**
|
||||
```vue
|
||||
<template>
|
||||
<van-config-provider :theme="theme">
|
||||
<div class="component-name">
|
||||
<!-- Content -->
|
||||
</div>
|
||||
</van-config-provider>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useMessageStore } from '@/stores/message'
|
||||
|
||||
const messageStore = useMessageStore()
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.component-name {
|
||||
padding: 16px;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
**Rules:**
|
||||
- Composition API with `<script setup lang="ts">`
|
||||
- Import order: Vue APIs → external libs → internal modules
|
||||
- Use `@/` alias for absolute imports, avoid `../../../`
|
||||
- Vant UI components: `<van-*>`
|
||||
- Pinia for state, Vue Router for navigation
|
||||
- SCSS with BEM naming, mobile-first design
|
||||
|
||||
**ESLint Rules (see `Web/eslint.config.js`):**
|
||||
- 2-space indentation
|
||||
- Single quotes, no semicolons
|
||||
- `const` over `let`, no `var`
|
||||
- Always use `===` (strict equality)
|
||||
- `space-before-function-paren: 'always'`
|
||||
- Max 1 empty line between blocks
|
||||
- Vue: multi-word component names disabled
|
||||
|
||||
**Prettier Rules (see `Web/.prettierrc.json`):**
|
||||
- Single quotes, no semicolons
|
||||
- Trailing commas: none
|
||||
- Print width: 100 chars
|
||||
|
||||
## Testing
|
||||
|
||||
**Backend (xUnit + NSubstitute + FluentAssertions):**
|
||||
```csharp
|
||||
public class BudgetStatsTest : BaseTest
|
||||
{
|
||||
private readonly IBudgetRepository _repo = Substitute.For<IBudgetRepository>();
|
||||
|
||||
[Fact]
|
||||
public async Task GetCategoryStats_月度_Test()
|
||||
{
|
||||
// Arrange
|
||||
_repo.GetAllAsync().Returns(testData);
|
||||
|
||||
// Act
|
||||
var result = await _service.GetCategoryStatsAsync(category, date);
|
||||
|
||||
// Assert
|
||||
result.Month.Limit.Should().Be(2500);
|
||||
}
|
||||
}
|
||||
```
|
||||
- Arrange-Act-Assert pattern
|
||||
- Constructor injection for dependencies
|
||||
- Use Chinese test method names for domain clarity
|
||||
|
||||
**Frontend:**
|
||||
- Vue Test Utils for components
|
||||
- axios-mock-adapter for API mocking
|
||||
|
||||
## Development Workflow
|
||||
|
||||
1. **Before committing backend:** `dotnet test`
|
||||
2. **Before committing frontend:** `pnpm lint && pnpm build`
|
||||
3. **Database migrations:** Use FreeSql (check `Repository/`)
|
||||
4. **API docs:** Scalar OpenAPI viewer
|
||||
|
||||
## Environment
|
||||
|
||||
**Required:**
|
||||
- .NET 10 SDK
|
||||
- Node.js 20.19+ or 22.12+
|
||||
- pnpm
|
||||
|
||||
**Database:** SQLite (embedded)
|
||||
|
||||
**Config:**
|
||||
- Backend: `appsettings.json`
|
||||
- Frontend: `.env.development` / `.env.production`
|
||||
|
||||
## Critical Guidelines (from `.github/csharpe.prompt.md`)
|
||||
|
||||
- 优先使用新C#语法 (Use modern C# syntax)
|
||||
- 优先使用中文注释 (Prefer Chinese comments for business logic)
|
||||
- 优先复用已有方法 (Reuse existing methods)
|
||||
- 不要深嵌套代码 (Avoid deep nesting)
|
||||
- 保持代码简洁易读 (Keep code clean and readable)
|
||||
3
Common/GlobalUsings.cs
Normal file
3
Common/GlobalUsings.cs
Normal file
@@ -0,0 +1,3 @@
|
||||
global using System.Reflection;
|
||||
global using System.Text.Json;
|
||||
global using Microsoft.Extensions.DependencyInjection;
|
||||
11
Common/IDateTimeProvider.cs
Normal file
11
Common/IDateTimeProvider.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace Common;
|
||||
|
||||
public interface IDateTimeProvider
|
||||
{
|
||||
DateTime Now { get; }
|
||||
}
|
||||
|
||||
public class DateTimeProvider : IDateTimeProvider
|
||||
{
|
||||
public DateTime Now => DateTime.Now;
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
using System.Reflection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Common;
|
||||
namespace Common;
|
||||
|
||||
public static class TypeExtensions
|
||||
{
|
||||
@@ -10,8 +7,8 @@ public static class TypeExtensions
|
||||
/// </summary>
|
||||
public static T? DeepClone<T>(this T source)
|
||||
{
|
||||
var json = System.Text.Json.JsonSerializer.Serialize(source);
|
||||
return System.Text.Json.JsonSerializer.Deserialize<T>(json);
|
||||
var json = JsonSerializer.Serialize(source);
|
||||
return JsonSerializer.Deserialize<T>(json);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,13 +22,14 @@ public static class ServiceExtension
|
||||
/// </summary>
|
||||
public static IServiceCollection AddServices(this IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<IDateTimeProvider, DateTimeProvider>();
|
||||
// 扫描程序集
|
||||
var serviceAssembly = Assembly.Load("Service");
|
||||
var repositoryAssembly = Assembly.Load("Repository");
|
||||
|
||||
// 注册所有服务实现
|
||||
RegisterServices(services, serviceAssembly);
|
||||
|
||||
|
||||
// 注册所有仓储实现
|
||||
RegisterRepositories(services, repositoryAssembly);
|
||||
|
||||
@@ -41,7 +39,7 @@ public static class ServiceExtension
|
||||
private static void RegisterServices(IServiceCollection services, Assembly assembly)
|
||||
{
|
||||
var types = assembly.GetTypes()
|
||||
.Where(t => t.IsClass && !t.IsAbstract);
|
||||
.Where(t => t is { IsClass: true, IsAbstract: false });
|
||||
|
||||
foreach (var type in types)
|
||||
{
|
||||
@@ -71,14 +69,13 @@ public static class ServiceExtension
|
||||
private static void RegisterRepositories(IServiceCollection services, Assembly assembly)
|
||||
{
|
||||
var types = assembly.GetTypes()
|
||||
.Where(t => t.IsClass && !t.IsAbstract);
|
||||
.Where(t => t is { IsClass: true, IsAbstract: false });
|
||||
|
||||
foreach (var type in types)
|
||||
{
|
||||
var interfaces = type.GetInterfaces()
|
||||
.Where(i => i.Name.StartsWith("I")
|
||||
&& i.Namespace == "Repository"
|
||||
&& !i.IsGenericType); // 排除泛型接口如 IBaseRepository<T>
|
||||
.Where(i => i.Name.StartsWith("I")
|
||||
&& i is { Namespace: "Repository", IsGenericType: false }); // 排除泛型接口如 IBaseRepository<T>
|
||||
|
||||
foreach (var @interface in interfaces)
|
||||
{
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<Project>
|
||||
<ItemGroup>
|
||||
<!-- Email & MIME Libraries -->
|
||||
<PackageVersion Include="FreeSql" Version="3.5.304" />
|
||||
<PackageVersion Include="FreeSql" Version="3.5.305" />
|
||||
<PackageVersion Include="FreeSql.Extensions.JsonMap" Version="3.5.305" />
|
||||
<PackageVersion Include="JetBrains.Annotations" Version="2025.2.4" />
|
||||
<PackageVersion Include="MailKit" Version="4.14.1" />
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.1" />
|
||||
<PackageVersion Include="MimeKit" Version="4.14.0" />
|
||||
@@ -20,7 +22,7 @@
|
||||
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0" />
|
||||
<PackageVersion Include="Scalar.AspNetCore" Version="2.11.9" />
|
||||
<!-- Database -->
|
||||
<PackageVersion Include="FreeSql.Provider.Sqlite" Version="3.5.304" />
|
||||
<PackageVersion Include="FreeSql.Provider.Sqlite" Version="3.5.305" />
|
||||
<PackageVersion Include="WebPush" Version="1.0.12" />
|
||||
<PackageVersion Include="Yitter.IdGenerator" Version="1.0.14" />
|
||||
<!-- File Processing -->
|
||||
@@ -33,5 +35,12 @@
|
||||
<!-- Text Processing -->
|
||||
<PackageVersion Include="JiebaNet.Analyser" Version="1.0.6" />
|
||||
<PackageVersion Include="Newtonsoft.Json" Version="13.0.4" />
|
||||
<!-- Testing -->
|
||||
<PackageVersion Include="coverlet.collector" Version="6.0.4"/>
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/>
|
||||
<PackageVersion Include="xunit" Version="2.9.3"/>
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.4"/>
|
||||
<PackageVersion Include="NSubstitute" Version="5.3.0" />
|
||||
<PackageVersion Include="FluentAssertions" Version="8.0.1" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,6 +1,6 @@
|
||||
# 多阶段构建 Dockerfile
|
||||
# 第一阶段:构建前端
|
||||
FROM node:20-alpine AS frontend-build
|
||||
FROM node:20-slim AS frontend-build
|
||||
|
||||
WORKDIR /app/frontend
|
||||
|
||||
@@ -31,6 +31,7 @@ COPY Entity/*.csproj ./Entity/
|
||||
COPY Repository/*.csproj ./Repository/
|
||||
COPY Service/*.csproj ./Service/
|
||||
COPY WebApi/*.csproj ./WebApi/
|
||||
COPY WebApi.Test/*.csproj ./WebApi.Test/
|
||||
|
||||
# 还原依赖
|
||||
RUN dotnet restore
|
||||
|
||||
@@ -13,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csp
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Entity", "Entity\Entity.csproj", "{B1BCD944-C4F5-406E-AE66-864E4BA21522}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApi.Test", "WebApi.Test\WebApi.Test.csproj", "{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -83,6 +85,18 @@ Global
|
||||
{B1BCD944-C4F5-406E-AE66-864E4BA21522}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B1BCD944-C4F5-406E-AE66-864E4BA21522}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B1BCD944-C4F5-406E-AE66-864E4BA21522}.Release|x86.Build.0 = Release|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Release|x64.Build.0 = Release|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{9CD457C8-A985-4DEA-9774-3B1D33CAFF51}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=fsql/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Ccsvc/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=fsql/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=strftime/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
|
||||
44
Entity/AGENTS.md
Normal file
44
Entity/AGENTS.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# ENTITY LAYER KNOWLEDGE BASE
|
||||
|
||||
**Generated:** 2026-01-28
|
||||
**Parent:** EmailBill/AGENTS.md
|
||||
|
||||
## OVERVIEW
|
||||
Database entities using FreeSql ORM with BaseEntity inheritance pattern.
|
||||
|
||||
## STRUCTURE
|
||||
```
|
||||
Entity/
|
||||
├── BaseEntity.cs # Base entity with Snowflake ID
|
||||
├── GlobalUsings.cs # Common imports
|
||||
├── BudgetRecord.cs # Budget tracking entity
|
||||
├── TransactionRecord.cs # Transaction entity
|
||||
├── EmailMessage.cs # Email processing entity
|
||||
└── MessageRecord.cs # Message entity
|
||||
```
|
||||
|
||||
## WHERE TO LOOK
|
||||
| Task | Location | Notes |
|
||||
|------|----------|-------|
|
||||
| Base entity pattern | BaseEntity.cs | Snowflake ID, audit fields |
|
||||
| Budget entities | BudgetRecord.cs, BudgetArchive.cs | Budget tracking |
|
||||
| Transaction entities | TransactionRecord.cs, TransactionPeriodic.cs | Financial transactions |
|
||||
| Email entities | EmailMessage.cs, MessageRecord.cs | Email processing |
|
||||
|
||||
## CONVENTIONS
|
||||
- Inherit from BaseEntity for all entities
|
||||
- Use [Column] attributes for FreeSql mapping
|
||||
- Snowflake IDs via YitIdHelper.NextId()
|
||||
- Chinese comments for business logic
|
||||
- XML docs for public APIs
|
||||
|
||||
## ANTI-PATTERNS (THIS LAYER)
|
||||
- Never use DateTime.Now (use IDateTimeProvider)
|
||||
- Don't skip BaseEntity inheritance
|
||||
- Avoid complex business logic in entities
|
||||
- No database queries in entity classes
|
||||
|
||||
## UNIQUE STYLES
|
||||
- Fluent Chinese naming for business concepts
|
||||
- Audit fields (CreateTime, UpdateTime) automatic
|
||||
- Soft delete patterns via UpdateTime nullability
|
||||
@@ -2,31 +2,6 @@
|
||||
|
||||
public class BudgetArchive : BaseEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// 预算Id
|
||||
/// </summary>
|
||||
public long BudgetId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 预算周期类型
|
||||
/// </summary>
|
||||
public BudgetPeriodType BudgetType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 预算金额
|
||||
/// </summary>
|
||||
public decimal BudgetedAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期内实际发生金额
|
||||
/// </summary>
|
||||
public decimal RealizedAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 详细描述
|
||||
/// </summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 归档目标年份
|
||||
/// </summary>
|
||||
@@ -37,8 +12,79 @@ public class BudgetArchive : BaseEntity
|
||||
/// </summary>
|
||||
public int Month { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 归档内容
|
||||
/// </summary>
|
||||
[JsonMap]
|
||||
public BudgetArchiveContent[] Content { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 归档日期
|
||||
/// </summary>
|
||||
public DateTime ArchiveDate { get; set; } = DateTime.Now;
|
||||
|
||||
/// <summary>
|
||||
/// 支出结余(预算 - 实际,正数表示省钱,负数表示超支)
|
||||
/// </summary>
|
||||
public decimal ExpenseSurplus { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 收入结余(实际 - 预算,正数表示超额收入,负数表示未达预期)
|
||||
/// </summary>
|
||||
public decimal IncomeSurplus { get; set; }
|
||||
|
||||
public string? Summary { get; set; }
|
||||
}
|
||||
|
||||
public record BudgetArchiveContent
|
||||
{
|
||||
/// <summary>
|
||||
/// 预算ID
|
||||
/// </summary>
|
||||
public long Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 预算名称
|
||||
/// </summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 统计周期
|
||||
/// </summary>
|
||||
public BudgetPeriodType Type { get; set; } = BudgetPeriodType.Month;
|
||||
|
||||
/// <summary>
|
||||
/// 预算金额
|
||||
/// </summary>
|
||||
public decimal Limit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 实际金额
|
||||
/// </summary>
|
||||
public decimal Actual { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 预算类别
|
||||
/// </summary>
|
||||
public BudgetCategory Category { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 相关分类 (逗号分隔的分类名称)
|
||||
/// </summary>
|
||||
public string[] SelectedCategories { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 不记额预算
|
||||
/// </summary>
|
||||
public bool NoLimit { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 硬性消费
|
||||
/// </summary>
|
||||
public bool IsMandatoryExpense { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 描述说明
|
||||
/// </summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -34,6 +34,16 @@ public class BudgetRecord : BaseEntity
|
||||
/// 开始日期
|
||||
/// </summary>
|
||||
public DateTime StartDate { get; set; } = DateTime.Now;
|
||||
|
||||
/// <summary>
|
||||
/// 不记额预算(选中后该预算没有预算金额,发生的收入或支出直接在存款中加减)
|
||||
/// </summary>
|
||||
public bool NoLimit { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 硬性消费(固定消费,如房租、水电等。当是当前年月且为硬性消费时,会根据经过的天数累加Current)
|
||||
/// </summary>
|
||||
public bool IsMandatoryExpense { get; set; } = false;
|
||||
}
|
||||
|
||||
public enum BudgetPeriodType
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Entity;
|
||||
namespace Entity;
|
||||
|
||||
/// <summary>
|
||||
/// 邮件消息实体
|
||||
@@ -39,7 +37,7 @@ public class EmailMessage : BaseEntity
|
||||
public string ComputeBodyHash()
|
||||
{
|
||||
using var md5 = MD5.Create();
|
||||
var inputBytes = System.Text.Encoding.UTF8.GetBytes(Body + HtmlBody);
|
||||
var inputBytes = Encoding.UTF8.GetBytes(Body + HtmlBody);
|
||||
var hashBytes = md5.ComputeHash(inputBytes);
|
||||
return Convert.ToHexString(hashBytes);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FreeSql" />
|
||||
<PackageReference Include="FreeSql.Extensions.JsonMap" />
|
||||
<PackageReference Include="Yitter.IdGenerator" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
global using FreeSql.DataAnnotations;
|
||||
global using FreeSql.DataAnnotations;
|
||||
global using System.Security.Cryptography;
|
||||
global using System.Text;
|
||||
@@ -12,6 +12,6 @@ public class PushSubscription : BaseEntity
|
||||
public string? Auth { get; set; }
|
||||
|
||||
public string? UserId { get; set; } // Optional: if you have user authentication
|
||||
|
||||
|
||||
public string? UserAgent { get; set; }
|
||||
}
|
||||
@@ -14,4 +14,11 @@ public class TransactionCategory : BaseEntity
|
||||
/// 交易类型(支出/收入)
|
||||
/// </summary>
|
||||
public TransactionType Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 图标(SVG格式,JSON数组存储5个图标供选择)
|
||||
/// 示例:["<svg>...</svg>", "<svg>...</svg>", ...]
|
||||
/// </summary>
|
||||
[Column(StringLength = -1)]
|
||||
public string? Icon { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Entity;
|
||||
namespace Entity;
|
||||
|
||||
/// <summary>
|
||||
/// 银行交易记录(由邮件解析生成)
|
||||
@@ -20,11 +20,6 @@ public class TransactionRecord : BaseEntity
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 退款金额
|
||||
/// </summary>
|
||||
public decimal RefundAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 交易后余额
|
||||
/// </summary>
|
||||
@@ -69,6 +64,11 @@ public class TransactionRecord : BaseEntity
|
||||
/// 导入来源
|
||||
/// </summary>
|
||||
public string ImportFrom { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 退款金额
|
||||
/// </summary>
|
||||
public decimal RefundAmount { get; set; }
|
||||
}
|
||||
|
||||
public enum TransactionType
|
||||
|
||||
156
REFACTORING_SUMMARY.md
Normal file
156
REFACTORING_SUMMARY.md
Normal file
@@ -0,0 +1,156 @@
|
||||
# TransactionRecordRepository 重构总结
|
||||
|
||||
## 重构目标
|
||||
|
||||
简化账单仓储,移除内存聚合逻辑,将聚合逻辑移到Service层,提高代码可测试性和可维护性。
|
||||
|
||||
## 主要变更
|
||||
|
||||
### 1. 创建新的仓储层 (TransactionRecordRepository.cs)
|
||||
|
||||
**简化后的接口方法:**
|
||||
- `QueryAsync` - 统一的查询方法,支持多种筛选条件和分页
|
||||
- `CountAsync` - 统一的计数方法
|
||||
- `GetDistinctClassifyAsync` - 获取所有分类
|
||||
- `GetByEmailIdAsync` - 按邮件ID查询
|
||||
- `GetUnclassifiedAsync` - 获取未分类账单
|
||||
- `GetClassifiedByKeywordsAsync` - 关键词查询已分类账单
|
||||
- `GetUnconfirmedRecordsAsync` - 获取待确认账单
|
||||
- `BatchUpdateByReasonAsync` - 批量更新分类
|
||||
- `UpdateCategoryNameAsync` - 更新分类名称
|
||||
- `ConfirmAllUnconfirmedAsync` - 确认待确认分类
|
||||
- `ExistsByEmailMessageIdAsync` - 检查邮件是否存在
|
||||
- `ExistsByImportNoAsync` - 检查导入编号是否存在
|
||||
|
||||
**移除的方法(移到Service层):**
|
||||
- `GetDailyStatisticsAsync` - 日统计
|
||||
- `GetDailyStatisticsByRangeAsync` - 范围日统计
|
||||
- `GetMonthlyStatisticsAsync` - 月度统计
|
||||
- `GetCategoryStatisticsAsync` - 分类统计
|
||||
- `GetTrendStatisticsAsync` - 趋势统计
|
||||
- `GetReasonGroupsAsync` - 按摘要分组统计
|
||||
- `GetClassifiedByKeywordsWithScoreAsync` - 关键词匹配(带分数)
|
||||
- `GetFilteredTrendStatisticsAsync` - 过滤趋势统计
|
||||
- `GetAmountGroupByClassifyAsync` - 按分类分组统计
|
||||
|
||||
### 2. 创建统计服务层 (TransactionStatisticsService.cs)
|
||||
|
||||
新增 `ITransactionStatisticsService` 接口和实现,负责所有聚合统计逻辑:
|
||||
|
||||
**主要方法:**
|
||||
- `GetDailyStatisticsAsync` - 日统计(内存聚合)
|
||||
- `GetDailyStatisticsByRangeAsync` - 范围日统计(内存聚合)
|
||||
- `GetMonthlyStatisticsAsync` - 月度统计(内存聚合)
|
||||
- `GetCategoryStatisticsAsync` - 分类统计(内存聚合)
|
||||
- `GetTrendStatisticsAsync` - 趋势统计(内存聚合)
|
||||
- `GetReasonGroupsAsync` - 按摘要分组统计(内存聚合,解决N+1问题)
|
||||
- `GetClassifiedByKeywordsWithScoreAsync` - 关键词匹配(内存计算相关度)
|
||||
- `GetFilteredTrendStatisticsAsync` - 过滤趋势统计(内存聚合)
|
||||
- `GetAmountGroupByClassifyAsync` - 按分类分组统计(内存聚合)
|
||||
|
||||
### 3. 创建DTO文件 (TransactionStatisticsDto.cs)
|
||||
|
||||
将统计相关的DTO类从Repository移到独立文件:
|
||||
- `ReasonGroupDto` - 按摘要分组统计DTO
|
||||
- `MonthlyStatistics` - 月度统计数据
|
||||
- `CategoryStatistics` - 分类统计数据
|
||||
- `TrendStatistics` - 趋势统计数据
|
||||
|
||||
### 4. 更新Controller (TransactionRecordController.cs)
|
||||
|
||||
- 注入 `ITransactionStatisticsService`
|
||||
- 将所有统计方法的调用从 `transactionRepository` 改为 `transactionStatisticsService`
|
||||
- 将 `GetPagedListAsync` 改为 `QueryAsync`
|
||||
- 将 `GetTotalCountAsync` 改为 `CountAsync`
|
||||
- 将 `GetByDateRangeAsync` 改为 `QueryAsync`
|
||||
- 将 `GetUnclassifiedCountAsync` 改为 `CountAsync`
|
||||
|
||||
### 5. 更新Service层
|
||||
|
||||
**SmartHandleService:**
|
||||
- 注入 `ITransactionStatisticsService`
|
||||
- 将 `GetClassifiedByKeywordsWithScoreAsync` 调用改为使用统计服务
|
||||
|
||||
**BudgetService:**
|
||||
- 注入 `ITransactionStatisticsService`
|
||||
- 将 `GetCategoryStatisticsAsync` 调用改为使用统计服务
|
||||
|
||||
**BudgetStatsService:**
|
||||
- 注入 `ITransactionStatisticsService`
|
||||
- 将所有 `GetFilteredTrendStatisticsAsync` 调用改为使用统计服务
|
||||
|
||||
**BudgetSavingsService:**
|
||||
- 注入 `ITransactionStatisticsService`
|
||||
- 将所有 `GetAmountGroupByClassifyAsync` 调用改为使用统计服务
|
||||
|
||||
### 6. 更新测试文件
|
||||
|
||||
**BudgetStatsTest.cs:**
|
||||
- 添加 `ITransactionStatisticsService` Mock
|
||||
- 更新构造函数参数
|
||||
- 将所有 `GetFilteredTrendStatisticsAsync` Mock调用改为使用统计服务
|
||||
|
||||
**BudgetSavingsTest.cs:**
|
||||
- 添加 `ITransactionStatisticsService` Mock
|
||||
- 更新构造函数参数
|
||||
- 将所有 `GetAmountGroupByClassifyAsync` Mock调用改为使用统计服务
|
||||
|
||||
## 重构优势
|
||||
|
||||
### 1. 职责分离
|
||||
- **Repository层**:只负责数据查询,返回原始数据
|
||||
- **Service层**:负责业务逻辑和数据聚合
|
||||
|
||||
### 2. 可测试性提升
|
||||
- Repository层的方法更简单,易于Mock
|
||||
- Service层可以独立测试聚合逻辑
|
||||
- 测试时可以精确控制聚合行为
|
||||
|
||||
### 3. 性能优化
|
||||
- 解决了 `GetReasonGroupsAsync` 中的N+1查询问题
|
||||
- 将内存聚合逻辑集中管理,便于后续优化
|
||||
- 减少了数据库聚合操作,避免大数据量时的性能问题
|
||||
|
||||
### 4. 代码可维护性
|
||||
- 统一的查询接口 `QueryAsync` 和 `CountAsync`
|
||||
- 减少了代码重复
|
||||
- 更清晰的职责划分
|
||||
|
||||
### 5. 扩展性
|
||||
- 新增统计功能只需在Service层添加
|
||||
- Repository层保持稳定,不受业务逻辑变化影响
|
||||
|
||||
## 测试结果
|
||||
|
||||
所有测试通过:
|
||||
- BudgetStatsTest: 7个测试全部通过
|
||||
- BudgetSavingsTest: 7个测试全部通过
|
||||
- 总计: 14个测试全部通过
|
||||
|
||||
## 注意事项
|
||||
|
||||
### 1. 性能考虑
|
||||
- 当前使用内存聚合,适合中小数据量
|
||||
- 如果数据量很大,可以考虑在Service层使用分页查询+增量聚合
|
||||
- 对于需要实时聚合的场景,可以考虑缓存
|
||||
|
||||
### 2. 警告处理
|
||||
编译时有3个未使用参数的警告:
|
||||
- `TransactionStatisticsService` 的 `textSegmentService` 参数未使用
|
||||
- `BudgetStatsService` 的 `transactionRecordRepository` 参数未使用
|
||||
- `BudgetSavingsService` 的 `transactionsRepository` 参数未使用
|
||||
|
||||
这些参数暂时保留,可能在未来使用,可以通过添加 `_ = parameter;` 来消除警告。
|
||||
|
||||
### 3. 向后兼容
|
||||
- Controller的API接口保持不变
|
||||
- 前端无需修改
|
||||
- 数据库结构无变化
|
||||
|
||||
## 后续优化建议
|
||||
|
||||
1. **添加缓存**:对于频繁查询的统计数据,可以添加缓存机制
|
||||
2. **分页聚合**:对于大数据量的聚合,可以实现分页聚合策略
|
||||
3. **异步优化**:某些聚合操作可以并行执行以提高性能
|
||||
4. **监控指标**:添加聚合查询的性能监控
|
||||
5. **单元测试**:为 `TransactionStatisticsService` 添加专门的单元测试
|
||||
46
Repository/AGENTS.md
Normal file
46
Repository/AGENTS.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# REPOSITORY LAYER KNOWLEDGE BASE
|
||||
|
||||
**Generated:** 2026-01-28
|
||||
**Parent:** EmailBill/AGENTS.md
|
||||
|
||||
## OVERVIEW
|
||||
Data access layer using FreeSql with BaseRepository pattern and global usings.
|
||||
|
||||
## STRUCTURE
|
||||
```
|
||||
Repository/
|
||||
├── BaseRepository.cs # Generic repository base
|
||||
├── GlobalUsings.cs # Common imports
|
||||
├── BudgetRepository.cs # Budget data access
|
||||
├── TransactionRecordRepository.cs # Transaction data access
|
||||
├── EmailMessageRepository.cs # Email data access
|
||||
└── TransactionStatisticsDto.cs # Statistics DTOs
|
||||
```
|
||||
|
||||
## WHERE TO LOOK
|
||||
| Task | Location | Notes |
|
||||
|------|----------|-------|
|
||||
| Base patterns | BaseRepository.cs | Generic CRUD operations |
|
||||
| Budget data | BudgetRepository.cs | Budget queries and updates |
|
||||
| Transaction data | TransactionRecordRepository.cs | Financial data access |
|
||||
| Email data | EmailMessageRepository.cs | Email processing storage |
|
||||
| Statistics | TransactionStatisticsDto.cs | Data transfer objects |
|
||||
|
||||
## CONVENTIONS
|
||||
- Inherit from BaseRepository<T> for all repositories
|
||||
- Use GlobalUsings.cs for shared imports
|
||||
- Async/await pattern for all database operations
|
||||
- Method names: GetAllAsync, GetByIdAsync, InsertAsync, UpdateAsync
|
||||
- Return domain entities, not DTOs (except in query results)
|
||||
|
||||
## ANTI-PATTERNS (THIS LAYER)
|
||||
- Never return anonymous types from methods
|
||||
- Don't expose FreeSql ISelect directly
|
||||
- Avoid business logic in repositories
|
||||
- No synchronous database calls
|
||||
- Don't mix data access with service logic
|
||||
|
||||
## UNIQUE STYLES
|
||||
- Generic constraints: where T : BaseEntity
|
||||
- Fluent query building with FreeSql extension methods
|
||||
- Paged query patterns for large datasets
|
||||
@@ -170,10 +170,10 @@ public abstract class BaseRepository<T>(IFreeSql freeSql) : IBaseRepository<T> w
|
||||
var dt = await FreeSql.Ado.ExecuteDataTableAsync(completeSql);
|
||||
var result = new List<dynamic>();
|
||||
|
||||
foreach (System.Data.DataRow row in dt.Rows)
|
||||
foreach (DataRow row in dt.Rows)
|
||||
{
|
||||
var expando = new System.Dynamic.ExpandoObject() as IDictionary<string, object>;
|
||||
foreach (System.Data.DataColumn column in dt.Columns)
|
||||
var expando = new ExpandoObject() as IDictionary<string, object>;
|
||||
foreach (DataColumn column in dt.Columns)
|
||||
{
|
||||
expando[column.ColumnName] = row[column];
|
||||
}
|
||||
|
||||
@@ -2,19 +2,21 @@
|
||||
|
||||
public interface IBudgetArchiveRepository : IBaseRepository<BudgetArchive>
|
||||
{
|
||||
Task<BudgetArchive?> GetArchiveAsync(long budgetId, int year, int month);
|
||||
Task<BudgetArchive?> GetArchiveAsync(int year, int month);
|
||||
|
||||
Task<List<BudgetArchive>> GetListAsync(int year, int month);
|
||||
|
||||
Task<List<BudgetArchive>> GetArchivesByYearAsync(int year);
|
||||
}
|
||||
|
||||
public class BudgetArchiveRepository(
|
||||
IFreeSql freeSql
|
||||
) : BaseRepository<BudgetArchive>(freeSql), IBudgetArchiveRepository
|
||||
{
|
||||
public async Task<BudgetArchive?> GetArchiveAsync(long budgetId, int year, int month)
|
||||
public async Task<BudgetArchive?> GetArchiveAsync(int year, int month)
|
||||
{
|
||||
return await FreeSql.Select<BudgetArchive>()
|
||||
.Where(a => a.BudgetId == budgetId &&
|
||||
a.Year == year &&
|
||||
.Where(a => a.Year == year &&
|
||||
a.Month == month)
|
||||
.ToOneAsync();
|
||||
}
|
||||
@@ -22,13 +24,15 @@ public class BudgetArchiveRepository(
|
||||
public async Task<List<BudgetArchive>> GetListAsync(int year, int month)
|
||||
{
|
||||
return await FreeSql.Select<BudgetArchive>()
|
||||
.Where(
|
||||
a => a.BudgetType == BudgetPeriodType.Month &&
|
||||
a.Year == year &&
|
||||
a.Month == month ||
|
||||
a.BudgetType == BudgetPeriodType.Year &&
|
||||
a.Year == year
|
||||
)
|
||||
.Where(a => a.Year == year && a.Month == month)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<List<BudgetArchive>> GetArchivesByYearAsync(int year)
|
||||
{
|
||||
return await FreeSql.Select<BudgetArchive>()
|
||||
.Where(a => a.Year == year)
|
||||
.OrderBy(a => a.Month)
|
||||
.ToListAsync();
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
public interface IBudgetRepository : IBaseRepository<BudgetRecord>
|
||||
{
|
||||
Task<decimal> GetCurrentAmountAsync(BudgetRecord budget, DateTime startDate, DateTime endDate);
|
||||
|
||||
|
||||
Task UpdateBudgetCategoryNameAsync(string oldName, string newName, TransactionType type);
|
||||
}
|
||||
|
||||
@@ -28,10 +28,6 @@ public class BudgetRepository(IFreeSql freeSql) : BaseRepository<BudgetRecord>(f
|
||||
{
|
||||
query = query.Where(t => t.Type == TransactionType.Income);
|
||||
}
|
||||
else if (budget.Category == BudgetCategory.Savings)
|
||||
{
|
||||
query = query.Where(t => t.Type == TransactionType.None);
|
||||
}
|
||||
|
||||
return await query.SumAsync(t => t.Amount);
|
||||
}
|
||||
@@ -39,16 +35,15 @@ public class BudgetRepository(IFreeSql freeSql) : BaseRepository<BudgetRecord>(f
|
||||
public async Task UpdateBudgetCategoryNameAsync(string oldName, string newName, TransactionType type)
|
||||
{
|
||||
var records = await FreeSql.Select<BudgetRecord>()
|
||||
.Where(b => b.SelectedCategories.Contains(oldName) &&
|
||||
.Where(b => b.SelectedCategories.Contains(oldName) &&
|
||||
((type == TransactionType.Expense && b.Category == BudgetCategory.Expense) ||
|
||||
(type == TransactionType.Income && b.Category == BudgetCategory.Income) ||
|
||||
(type == TransactionType.None && b.Category == BudgetCategory.Savings)))
|
||||
(type == TransactionType.Income && b.Category == BudgetCategory.Income)))
|
||||
.ToListAsync();
|
||||
|
||||
foreach (var record in records)
|
||||
{
|
||||
var categories = record.SelectedCategories.Split(',').ToList();
|
||||
for (int i = 0; i < categories.Count; i++)
|
||||
for (var i = 0; i < categories.Count; i++)
|
||||
{
|
||||
if (categories[i] == oldName)
|
||||
{
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
public interface IEmailMessageRepository : IBaseRepository<EmailMessage>
|
||||
{
|
||||
Task<EmailMessage?> ExistsAsync(string md5);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 分页获取邮件列表(游标分页)
|
||||
/// </summary>
|
||||
@@ -12,7 +12,7 @@ public interface IEmailMessageRepository : IBaseRepository<EmailMessage>
|
||||
/// <param name="pageSize">每页数量</param>
|
||||
/// <returns>邮件列表、最后接收时间和最后ID</returns>
|
||||
Task<(List<EmailMessage> list, DateTime? lastReceivedDate, long lastId)> GetPagedListAsync(DateTime? lastReceivedDate, long? lastId, int pageSize = 20);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取总数
|
||||
/// </summary>
|
||||
@@ -31,20 +31,20 @@ public class EmailMessageRepository(IFreeSql freeSql) : BaseRepository<EmailMess
|
||||
public async Task<(List<EmailMessage> list, DateTime? lastReceivedDate, long lastId)> GetPagedListAsync(DateTime? lastReceivedDate, long? lastId, int pageSize = 20)
|
||||
{
|
||||
var query = FreeSql.Select<EmailMessage>();
|
||||
|
||||
|
||||
// 如果提供了游标,则获取小于游标位置的记录
|
||||
if (lastReceivedDate.HasValue && lastId.HasValue)
|
||||
{
|
||||
query = query.Where(e => e.ReceivedDate < lastReceivedDate.Value ||
|
||||
query = query.Where(e => e.ReceivedDate < lastReceivedDate.Value ||
|
||||
(e.ReceivedDate == lastReceivedDate.Value && e.Id < lastId.Value));
|
||||
}
|
||||
|
||||
|
||||
var list = await query
|
||||
.OrderByDescending(e => e.ReceivedDate)
|
||||
.OrderByDescending(e => e.Id)
|
||||
.Page(1, pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
|
||||
var lastRecord = list.Count > 0 ? list.Last() : null;
|
||||
return (list, lastRecord?.ReceivedDate, lastRecord?.Id ?? 0);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
|
||||
global using Entity;
|
||||
global using FreeSql;
|
||||
global using System.Linq;
|
||||
global using System.Data;
|
||||
global using System.Dynamic;
|
||||
global using FreeSql;
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ public class MessageRecordRepository(IFreeSql freeSql) : BaseRepository<MessageR
|
||||
.Count(out var total)
|
||||
.Page(pageIndex, pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
|
||||
return (list, total);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,12 +29,12 @@ public interface ITransactionPeriodicRepository : IBaseRepository<TransactionPer
|
||||
/// <summary>
|
||||
/// 周期性账单仓储实现
|
||||
/// </summary>
|
||||
public class TransactionPeriodicRepository(IFreeSql freeSql)
|
||||
public class TransactionPeriodicRepository(IFreeSql freeSql)
|
||||
: BaseRepository<TransactionPeriodic>(freeSql), ITransactionPeriodicRepository
|
||||
{
|
||||
public async Task<IEnumerable<TransactionPeriodic>> GetPagedListAsync(
|
||||
int pageIndex,
|
||||
int pageSize,
|
||||
int pageIndex,
|
||||
int pageSize,
|
||||
string? searchKeyword = null)
|
||||
{
|
||||
var query = FreeSql.Select<TransactionPeriodic>();
|
||||
@@ -42,8 +42,8 @@ public class TransactionPeriodicRepository(IFreeSql freeSql)
|
||||
// 搜索关键词
|
||||
if (!string.IsNullOrWhiteSpace(searchKeyword))
|
||||
{
|
||||
query = query.Where(x =>
|
||||
x.Reason.Contains(searchKeyword) ||
|
||||
query = query.Where(x =>
|
||||
x.Reason.Contains(searchKeyword) ||
|
||||
x.Classify.Contains(searchKeyword));
|
||||
}
|
||||
|
||||
@@ -60,8 +60,8 @@ public class TransactionPeriodicRepository(IFreeSql freeSql)
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(searchKeyword))
|
||||
{
|
||||
query = query.Where(x =>
|
||||
x.Reason.Contains(searchKeyword) ||
|
||||
query = query.Where(x =>
|
||||
x.Reason.Contains(searchKeyword) ||
|
||||
x.Classify.Contains(searchKeyword));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Repository;
|
||||
namespace Repository;
|
||||
|
||||
public interface ITransactionRecordRepository : IBaseRepository<TransactionRecord>
|
||||
{
|
||||
@@ -6,202 +6,102 @@ public interface ITransactionRecordRepository : IBaseRepository<TransactionRecor
|
||||
|
||||
Task<TransactionRecord?> ExistsByImportNoAsync(string importNo, string importFrom);
|
||||
|
||||
/// <summary>
|
||||
/// 分页获取交易记录列表
|
||||
/// </summary>
|
||||
/// <param name="pageIndex">页码,从1开始</param>
|
||||
/// <param name="pageSize">每页数量</param>
|
||||
/// <param name="searchKeyword">搜索关键词(搜索交易摘要和分类)</param>
|
||||
/// <param name="classifies">筛选分类列表</param>
|
||||
/// <param name="type">筛选交易类型</param>
|
||||
/// <param name="year">筛选年份</param>
|
||||
/// <param name="month">筛选月份</param>
|
||||
/// <param name="startDate">筛选开始日期</param>
|
||||
/// <param name="endDate">筛选结束日期</param>
|
||||
/// <param name="reason">筛选交易摘要</param>
|
||||
/// <param name="sortByAmount">是否按金额降序排列,默认为false按时间降序</param>
|
||||
/// <returns>交易记录列表</returns>
|
||||
Task<List<TransactionRecord>> GetPagedListAsync(
|
||||
int pageIndex = 1,
|
||||
int pageSize = 20,
|
||||
string? searchKeyword = null,
|
||||
string[]? classifies = null,
|
||||
TransactionType? type = null,
|
||||
Task<List<TransactionRecord>> QueryAsync(
|
||||
int? year = null,
|
||||
int? month = null,
|
||||
DateTime? startDate = null,
|
||||
DateTime? endDate = null,
|
||||
TransactionType? type = null,
|
||||
string[]? classifies = null,
|
||||
string? searchKeyword = null,
|
||||
string? reason = null,
|
||||
int pageIndex = 1,
|
||||
int pageSize = int.MaxValue,
|
||||
bool sortByAmount = false);
|
||||
|
||||
/// <summary>
|
||||
/// 获取总数
|
||||
/// </summary>
|
||||
Task<long> GetTotalCountAsync(
|
||||
string? searchKeyword = null,
|
||||
string[]? classifies = null,
|
||||
TransactionType? type = null,
|
||||
Task<long> CountAsync(
|
||||
int? year = null,
|
||||
int? month = null,
|
||||
DateTime? startDate = null,
|
||||
DateTime? endDate = null,
|
||||
TransactionType? type = null,
|
||||
string[]? classifies = null,
|
||||
string? searchKeyword = null,
|
||||
string? reason = null);
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有不同的交易分类
|
||||
/// </summary>
|
||||
Task<List<string>> GetDistinctClassifyAsync();
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定月份每天的消费统计
|
||||
/// </summary>
|
||||
/// <param name="year">年份</param>
|
||||
/// <param name="month">月份</param>
|
||||
/// <returns>每天的消费笔数和金额</returns>
|
||||
Task<Dictionary<string, (int count, decimal amount)>> GetDailyStatisticsAsync(int year, int month);
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定日期范围内的交易记录
|
||||
/// </summary>
|
||||
/// <param name="startDate">开始日期</param>
|
||||
/// <param name="endDate">结束日期</param>
|
||||
/// <returns>交易记录列表</returns>
|
||||
Task<List<TransactionRecord>> GetByDateRangeAsync(DateTime startDate, DateTime endDate);
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定邮件的交易记录数量
|
||||
/// </summary>
|
||||
/// <param name="emailMessageId">邮件ID</param>
|
||||
/// <returns>交易记录数量</returns>
|
||||
Task<int> GetCountByEmailIdAsync(long emailMessageId);
|
||||
|
||||
/// <summary>
|
||||
/// 获取月度统计数据
|
||||
/// </summary>
|
||||
/// <param name="year">年份</param>
|
||||
/// <param name="month">月份</param>
|
||||
/// <returns>月度统计数据</returns>
|
||||
Task<MonthlyStatistics> GetMonthlyStatisticsAsync(int year, int month);
|
||||
|
||||
/// <summary>
|
||||
/// 获取分类统计数据
|
||||
/// </summary>
|
||||
/// <param name="year">年份</param>
|
||||
/// <param name="month">月份</param>
|
||||
/// <param name="type">交易类型(0:支出, 1:收入)</param>
|
||||
/// <returns>分类统计列表</returns>
|
||||
Task<List<CategoryStatistics>> GetCategoryStatisticsAsync(int year, int month, TransactionType type);
|
||||
|
||||
/// <summary>
|
||||
/// 获取多个月的趋势统计数据
|
||||
/// </summary>
|
||||
/// <param name="startYear">开始年份</param>
|
||||
/// <param name="startMonth">开始月份</param>
|
||||
/// <param name="monthCount">月份数量</param>
|
||||
/// <returns>趋势统计列表</returns>
|
||||
Task<List<TrendStatistics>> GetTrendStatisticsAsync(int startYear, int startMonth, int monthCount);
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定邮件的交易记录列表
|
||||
/// </summary>
|
||||
/// <param name="emailMessageId">邮件ID</param>
|
||||
/// <returns>交易记录列表</returns>
|
||||
Task<List<TransactionRecord>> GetByEmailIdAsync(long emailMessageId);
|
||||
|
||||
/// <summary>
|
||||
/// 获取未分类的账单数量
|
||||
/// </summary>
|
||||
/// <returns>未分类账单数量</returns>
|
||||
Task<int> GetUnclassifiedCountAsync();
|
||||
Task<int> GetCountByEmailIdAsync(long emailMessageId);
|
||||
|
||||
/// <summary>
|
||||
/// 获取未分类的账单列表
|
||||
/// </summary>
|
||||
/// <param name="pageSize">每页数量</param>
|
||||
/// <returns>未分类账单列表</returns>
|
||||
Task<List<TransactionRecord>> GetUnclassifiedAsync(int pageSize = 10);
|
||||
|
||||
/// <summary>
|
||||
/// 获取按交易摘要(Reason)分组的统计信息(支持分页)
|
||||
/// </summary>
|
||||
/// <param name="pageIndex">页码,从1开始</param>
|
||||
/// <param name="pageSize">每页数量</param>
|
||||
/// <returns>分组统计列表和总数</returns>
|
||||
Task<(List<ReasonGroupDto> list, int total)> GetReasonGroupsAsync(int pageIndex = 1, int pageSize = 20);
|
||||
|
||||
/// <summary>
|
||||
/// 按摘要批量更新交易记录的分类
|
||||
/// </summary>
|
||||
/// <param name="reason">交易摘要</param>
|
||||
/// <param name="type">交易类型</param>
|
||||
/// <param name="classify">分类名称</param>
|
||||
/// <returns>更新的记录数量</returns>
|
||||
Task<int> BatchUpdateByReasonAsync(string reason, TransactionType type, string classify);
|
||||
|
||||
/// <summary>
|
||||
/// 根据关键词查询交易记录(模糊匹配Reason字段)
|
||||
/// </summary>
|
||||
/// <param name="keyword">关键词</param>
|
||||
/// <returns>匹配的交易记录列表</returns>
|
||||
Task<List<TransactionRecord>> QueryByWhereAsync(string sql);
|
||||
|
||||
/// <summary>
|
||||
/// 执行完整的SQL查询
|
||||
/// </summary>
|
||||
/// <param name="completeSql">完整的SELECT SQL语句</param>
|
||||
/// <returns>查询结果列表</returns>
|
||||
Task<List<TransactionRecord>> ExecuteRawSqlAsync(string completeSql);
|
||||
|
||||
/// <summary>
|
||||
/// 根据关键词查询已分类的账单(用于智能分类参考)
|
||||
/// </summary>
|
||||
/// <param name="keywords">关键词列表</param>
|
||||
/// <param name="limit">返回结果数量限制</param>
|
||||
/// <returns>已分类的账单列表</returns>
|
||||
Task<List<TransactionRecord>> GetClassifiedByKeywordsAsync(List<string> keywords, int limit = 10);
|
||||
|
||||
/// <summary>
|
||||
/// 根据关键词查询已分类的账单,并计算相关度分数
|
||||
/// </summary>
|
||||
/// <param name="keywords">关键词列表</param>
|
||||
/// <param name="minMatchRate">最小匹配率(0.0-1.0),默认0.3表示至少匹配30%的关键词</param>
|
||||
/// <param name="limit">返回结果数量限制</param>
|
||||
/// <returns>带相关度分数的已分类账单列表</returns>
|
||||
Task<List<(TransactionRecord record, double relevanceScore)>> GetClassifiedByKeywordsWithScoreAsync(List<string> keywords, double minMatchRate = 0.3, int limit = 10);
|
||||
|
||||
/// <summary>
|
||||
/// 获取抵账候选列表
|
||||
/// </summary>
|
||||
/// <param name="currentId">当前交易ID</param>
|
||||
/// <param name="amount">当前交易金额</param>
|
||||
/// <param name="currentType">当前交易类型</param>
|
||||
/// <returns>候选交易列表</returns>
|
||||
Task<List<TransactionRecord>> GetCandidatesForOffsetAsync(long currentId, decimal amount, TransactionType currentType);
|
||||
|
||||
/// <summary>
|
||||
/// 获取待确认分类的账单列表
|
||||
/// </summary>
|
||||
/// <returns>待确认账单列表</returns>
|
||||
Task<List<TransactionRecord>> GetUnconfirmedRecordsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// 全部确认待确认的分类
|
||||
/// </summary>
|
||||
/// <returns>影响行数</returns>
|
||||
Task<int> ConfirmAllUnconfirmedAsync(long[] ids);
|
||||
Task<int> BatchUpdateByReasonAsync(string reason, TransactionType type, string classify);
|
||||
|
||||
/// <summary>
|
||||
/// 更新分类名称
|
||||
/// </summary>
|
||||
/// <param name="oldName">旧分类名称</param>
|
||||
/// <param name="newName">新分类名称</param>
|
||||
/// <param name="type">交易类型</param>
|
||||
/// <returns>影响行数</returns>
|
||||
Task<int> UpdateCategoryNameAsync(string oldName, string newName, TransactionType type);
|
||||
|
||||
Task<int> ConfirmAllUnconfirmedAsync(long[] ids);
|
||||
}
|
||||
|
||||
public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<TransactionRecord>(freeSql), ITransactionRecordRepository
|
||||
{
|
||||
private ISelect<TransactionRecord> BuildQuery(
|
||||
int? year = null,
|
||||
int? month = null,
|
||||
DateTime? startDate = null,
|
||||
DateTime? endDate = null,
|
||||
TransactionType? type = null,
|
||||
string[]? classifies = null,
|
||||
string? searchKeyword = null,
|
||||
string? reason = null)
|
||||
{
|
||||
var query = FreeSql.Select<TransactionRecord>();
|
||||
|
||||
query = query.WhereIf(!string.IsNullOrWhiteSpace(searchKeyword),
|
||||
t => t.Reason.Contains(searchKeyword!) ||
|
||||
t.Classify.Contains(searchKeyword!) ||
|
||||
t.Card.Contains(searchKeyword!) ||
|
||||
t.ImportFrom.Contains(searchKeyword!))
|
||||
.WhereIf(!string.IsNullOrWhiteSpace(reason),
|
||||
t => t.Reason == reason);
|
||||
|
||||
if (classifies is { Length: > 0 })
|
||||
{
|
||||
var filterClassifies = classifies.Select(c => c == "未分类" ? string.Empty : c).ToList();
|
||||
query = query.Where(t => filterClassifies.Contains(t.Classify));
|
||||
}
|
||||
|
||||
query = query.WhereIf(type.HasValue, t => t.Type == type!.Value);
|
||||
|
||||
if (year.HasValue)
|
||||
{
|
||||
if (month.HasValue && month.Value > 0)
|
||||
{
|
||||
// 查询指定年月
|
||||
var dateStart = new DateTime(year.Value, month.Value, 1);
|
||||
var dateEnd = dateStart.AddMonths(1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 查询整年数据(1月1日到下年1月1日)
|
||||
var dateStart = new DateTime(year.Value, 1, 1);
|
||||
var dateEnd = new DateTime(year.Value + 1, 1, 1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
}
|
||||
|
||||
query = query.WhereIf(startDate.HasValue, t => t.OccurredAt >= startDate!.Value)
|
||||
.WhereIf(endDate.HasValue, t => t.OccurredAt <= endDate!.Value);
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
public async Task<TransactionRecord?> ExistsByEmailMessageIdAsync(long emailMessageId, DateTime occurredAt)
|
||||
{
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
@@ -216,116 +116,48 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
|
||||
.FirstAsync();
|
||||
}
|
||||
|
||||
public async Task<List<TransactionRecord>> GetPagedListAsync(
|
||||
int pageIndex = 1,
|
||||
int pageSize = 20,
|
||||
string? searchKeyword = null,
|
||||
string[]? classifies = null,
|
||||
TransactionType? type = null,
|
||||
public async Task<List<TransactionRecord>> QueryAsync(
|
||||
int? year = null,
|
||||
int? month = null,
|
||||
DateTime? startDate = null,
|
||||
DateTime? endDate = null,
|
||||
TransactionType? type = null,
|
||||
string[]? classifies = null,
|
||||
string? searchKeyword = null,
|
||||
string? reason = null,
|
||||
int pageIndex = 1,
|
||||
int pageSize = int.MaxValue,
|
||||
bool sortByAmount = false)
|
||||
{
|
||||
var query = FreeSql.Select<TransactionRecord>();
|
||||
var query = BuildQuery(year, month, startDate, endDate, type, classifies, searchKeyword, reason);
|
||||
|
||||
// 如果提供了搜索关键词,则添加搜索条件
|
||||
query = query.WhereIf(!string.IsNullOrWhiteSpace(searchKeyword),
|
||||
t => t.Reason.Contains(searchKeyword!) ||
|
||||
t.Classify.Contains(searchKeyword!) ||
|
||||
t.Card.Contains(searchKeyword!) ||
|
||||
t.ImportFrom.Contains(searchKeyword!))
|
||||
.WhereIf(!string.IsNullOrWhiteSpace(reason),
|
||||
t => t.Reason == reason);
|
||||
|
||||
// 按分类筛选
|
||||
if (classifies != null && classifies.Length > 0)
|
||||
{
|
||||
var filterClassifies = classifies.Select(c => c == "未分类" ? string.Empty : c).ToList();
|
||||
query = query.Where(t => filterClassifies.Contains(t.Classify));
|
||||
}
|
||||
|
||||
// 按交易类型筛选
|
||||
query = query.WhereIf(type.HasValue, t => t.Type == type!.Value);
|
||||
|
||||
// 按年月筛选
|
||||
if (year.HasValue && month.HasValue)
|
||||
{
|
||||
var dateStart = new DateTime(year.Value, month.Value, 1);
|
||||
var dateEnd = dateStart.AddMonths(1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
|
||||
// 按日期范围筛选
|
||||
query = query.WhereIf(startDate.HasValue, t => t.OccurredAt >= startDate!.Value)
|
||||
.WhereIf(endDate.HasValue, t => t.OccurredAt <= endDate!.Value);
|
||||
|
||||
// 根据sortByAmount参数决定排序方式
|
||||
if (sortByAmount)
|
||||
{
|
||||
// 按金额降序排列
|
||||
return await query
|
||||
.OrderByDescending(t => t.Amount)
|
||||
.OrderByDescending(t => t.Id)
|
||||
.Page(pageIndex, pageSize)
|
||||
.ToListAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 按时间降序排列
|
||||
return await query
|
||||
.OrderByDescending(t => t.OccurredAt)
|
||||
.OrderByDescending(t => t.Id)
|
||||
.Page(pageIndex, pageSize)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
return await query
|
||||
.OrderByDescending(t => t.OccurredAt)
|
||||
.OrderByDescending(t => t.Id)
|
||||
.Page(pageIndex, pageSize)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<long> GetTotalCountAsync(
|
||||
string? searchKeyword = null,
|
||||
string[]? classifies = null,
|
||||
TransactionType? type = null,
|
||||
public async Task<long> CountAsync(
|
||||
int? year = null,
|
||||
int? month = null,
|
||||
DateTime? startDate = null,
|
||||
DateTime? endDate = null,
|
||||
TransactionType? type = null,
|
||||
string[]? classifies = null,
|
||||
string? searchKeyword = null,
|
||||
string? reason = null)
|
||||
{
|
||||
var query = FreeSql.Select<TransactionRecord>();
|
||||
|
||||
// 如果提供了搜索关键词,则添加搜索条件
|
||||
query = query.WhereIf(!string.IsNullOrWhiteSpace(searchKeyword),
|
||||
t => t.Reason.Contains(searchKeyword!) ||
|
||||
t.Classify.Contains(searchKeyword!) ||
|
||||
t.Card.Contains(searchKeyword!) ||
|
||||
t.ImportFrom.Contains(searchKeyword!))
|
||||
.WhereIf(!string.IsNullOrWhiteSpace(reason),
|
||||
t => t.Reason == reason);
|
||||
|
||||
// 按分类筛选
|
||||
if (classifies != null && classifies.Length > 0)
|
||||
{
|
||||
var filterClassifies = classifies.Select(c => c == "未分类" ? string.Empty : c).ToList();
|
||||
query = query.Where(t => filterClassifies.Contains(t.Classify));
|
||||
}
|
||||
|
||||
// 按交易类型筛选
|
||||
query = query.WhereIf(type.HasValue, t => t.Type == type!.Value);
|
||||
|
||||
// 按年月筛选
|
||||
if (year.HasValue && month.HasValue)
|
||||
{
|
||||
var dateStart = new DateTime(year.Value, month.Value, 1);
|
||||
var dateEnd = dateStart.AddMonths(1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
|
||||
// 按日期范围筛选
|
||||
query = query.WhereIf(startDate.HasValue, t => t.OccurredAt >= startDate!.Value)
|
||||
.WhereIf(endDate.HasValue, t => t.OccurredAt <= endDate!.Value);
|
||||
|
||||
var query = BuildQuery(year, month, startDate, endDate, type, classifies, searchKeyword, reason);
|
||||
return await query.CountAsync();
|
||||
}
|
||||
|
||||
@@ -337,48 +169,6 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
|
||||
.ToListAsync(t => t.Classify);
|
||||
}
|
||||
|
||||
public async Task<Dictionary<string, (int count, decimal amount)>> GetDailyStatisticsAsync(int year, int month)
|
||||
{
|
||||
var startDate = new DateTime(year, month, 1);
|
||||
var endDate = startDate.AddMonths(1);
|
||||
|
||||
var records = await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.OccurredAt >= startDate && t.OccurredAt < endDate)
|
||||
.ToListAsync();
|
||||
|
||||
var statistics = records
|
||||
.GroupBy(t => t.OccurredAt.ToString("yyyy-MM-dd"))
|
||||
.ToDictionary(
|
||||
g => g.Key,
|
||||
g =>
|
||||
{
|
||||
// 分别统计收入和支出
|
||||
var income = g.Where(t => t.Type == TransactionType.Income).Sum(t => t.Amount);
|
||||
var expense = g.Where(t => t.Type == TransactionType.Expense).Sum(t => t.Amount);
|
||||
// 净额 = 收入 - 支出(消费大于收入时为负数)
|
||||
var netAmount = income - expense;
|
||||
return (count: g.Count(), amount: netAmount);
|
||||
}
|
||||
);
|
||||
|
||||
return statistics;
|
||||
}
|
||||
|
||||
public async Task<List<TransactionRecord>> GetByDateRangeAsync(DateTime startDate, DateTime endDate)
|
||||
{
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.OccurredAt >= startDate && t.OccurredAt <= endDate)
|
||||
.OrderBy(t => t.OccurredAt)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<int> GetCountByEmailIdAsync(long emailMessageId)
|
||||
{
|
||||
return (int)await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.EmailMessageId == emailMessageId)
|
||||
.CountAsync();
|
||||
}
|
||||
|
||||
public async Task<List<TransactionRecord>> GetByEmailIdAsync(long emailMessageId)
|
||||
{
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
@@ -387,10 +177,10 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<int> GetUnclassifiedCountAsync()
|
||||
public async Task<int> GetCountByEmailIdAsync(long emailMessageId)
|
||||
{
|
||||
return (int)await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => string.IsNullOrEmpty(t.Classify))
|
||||
.Where(t => t.EmailMessageId == emailMessageId)
|
||||
.CountAsync();
|
||||
}
|
||||
|
||||
@@ -403,207 +193,16 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<(List<ReasonGroupDto> list, int total)> GetReasonGroupsAsync(int pageIndex = 1, int pageSize = 20)
|
||||
{
|
||||
// 先按照Reason分组,统计每个Reason的数量和总金额
|
||||
var groups = await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => !string.IsNullOrEmpty(t.Reason))
|
||||
.Where(t => string.IsNullOrEmpty(t.Classify)) // 只统计未分类的
|
||||
.GroupBy(t => t.Reason)
|
||||
.ToListAsync(g => new
|
||||
{
|
||||
Reason = g.Key,
|
||||
Count = g.Count(),
|
||||
TotalAmount = g.Sum(g.Value.Amount)
|
||||
});
|
||||
|
||||
// 按总金额绝对值降序排序
|
||||
var sortedGroups = groups.OrderByDescending(g => Math.Abs(g.TotalAmount)).ToList();
|
||||
var total = sortedGroups.Count;
|
||||
|
||||
// 分页
|
||||
var pagedGroups = sortedGroups
|
||||
.Skip((pageIndex - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToList();
|
||||
|
||||
// 为每个分组获取详细信息
|
||||
var result = new List<ReasonGroupDto>();
|
||||
foreach (var group in pagedGroups)
|
||||
{
|
||||
// 获取该分组的所有记录
|
||||
var records = await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.Reason == group.Reason)
|
||||
.Where(t => string.IsNullOrEmpty(t.Classify))
|
||||
.ToListAsync();
|
||||
|
||||
if (records.Count > 0)
|
||||
{
|
||||
var sample = records.First();
|
||||
result.Add(new ReasonGroupDto
|
||||
{
|
||||
Reason = group.Reason,
|
||||
Count = (int)group.Count,
|
||||
SampleType = sample.Type,
|
||||
SampleClassify = sample.Classify ?? string.Empty,
|
||||
TransactionIds = records.Select(r => r.Id).ToList(),
|
||||
TotalAmount = Math.Abs(group.TotalAmount)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (result, total);
|
||||
}
|
||||
|
||||
public async Task<int> BatchUpdateByReasonAsync(string reason, TransactionType type, string classify)
|
||||
{
|
||||
return await FreeSql.Update<TransactionRecord>()
|
||||
.Set(t => t.Type, type)
|
||||
.Set(t => t.Classify, classify)
|
||||
.Where(t => t.Reason == reason)
|
||||
.ExecuteAffrowsAsync();
|
||||
}
|
||||
|
||||
public async Task<List<TransactionRecord>> QueryByWhereAsync(string sql)
|
||||
{
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
.Where(sql)
|
||||
.OrderByDescending(t => t.OccurredAt)
|
||||
.ToListAsync();
|
||||
}
|
||||
public async Task<List<TransactionRecord>> ExecuteRawSqlAsync(string completeSql)
|
||||
{
|
||||
return await FreeSql.Ado.QueryAsync<TransactionRecord>(completeSql);
|
||||
}
|
||||
|
||||
public async Task<MonthlyStatistics> GetMonthlyStatisticsAsync(int year, int month)
|
||||
{
|
||||
var startDate = new DateTime(year, month, 1);
|
||||
var endDate = startDate.AddMonths(1);
|
||||
|
||||
var records = await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.OccurredAt >= startDate && t.OccurredAt < endDate)
|
||||
.ToListAsync();
|
||||
|
||||
var statistics = new MonthlyStatistics
|
||||
{
|
||||
Year = year,
|
||||
Month = month
|
||||
};
|
||||
|
||||
foreach (var record in records)
|
||||
{
|
||||
var amount = Math.Abs(record.Amount);
|
||||
|
||||
if (record.Type == TransactionType.Expense)
|
||||
{
|
||||
statistics.TotalExpense += amount;
|
||||
statistics.ExpenseCount++;
|
||||
if (amount > statistics.MaxExpense)
|
||||
{
|
||||
statistics.MaxExpense = amount;
|
||||
}
|
||||
}
|
||||
else if (record.Type == TransactionType.Income)
|
||||
{
|
||||
statistics.TotalIncome += amount;
|
||||
statistics.IncomeCount++;
|
||||
if (amount > statistics.MaxIncome)
|
||||
{
|
||||
statistics.MaxIncome = amount;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
statistics.Balance = statistics.TotalIncome - statistics.TotalExpense;
|
||||
statistics.TotalCount = records.Count;
|
||||
|
||||
return statistics;
|
||||
}
|
||||
|
||||
public async Task<List<CategoryStatistics>> GetCategoryStatisticsAsync(int year, int month, TransactionType type)
|
||||
{
|
||||
var startDate = new DateTime(year, month, 1);
|
||||
var endDate = startDate.AddMonths(1);
|
||||
|
||||
var records = await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.OccurredAt >= startDate && t.OccurredAt < endDate && t.Type == type)
|
||||
.ToListAsync();
|
||||
|
||||
var categoryGroups = records
|
||||
.GroupBy(t => t.Classify ?? "未分类")
|
||||
.Select(g => new CategoryStatistics
|
||||
{
|
||||
Classify = g.Key,
|
||||
Amount = g.Sum(t => Math.Abs(t.Amount)),
|
||||
Count = g.Count()
|
||||
})
|
||||
.OrderByDescending(c => c.Amount)
|
||||
.ToList();
|
||||
|
||||
// 计算百分比
|
||||
var total = categoryGroups.Sum(c => c.Amount);
|
||||
if (total > 0)
|
||||
{
|
||||
foreach (var category in categoryGroups)
|
||||
{
|
||||
category.Percent = Math.Round((category.Amount / total) * 100, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return categoryGroups;
|
||||
}
|
||||
|
||||
public async Task<List<TrendStatistics>> GetTrendStatisticsAsync(int startYear, int startMonth, int monthCount)
|
||||
{
|
||||
var trends = new List<TrendStatistics>();
|
||||
|
||||
for (int i = 0; i < monthCount; i++)
|
||||
{
|
||||
var targetYear = startYear;
|
||||
var targetMonth = startMonth + i;
|
||||
|
||||
// 处理月份溢出
|
||||
while (targetMonth > 12)
|
||||
{
|
||||
targetMonth -= 12;
|
||||
targetYear++;
|
||||
}
|
||||
|
||||
var startDate = new DateTime(targetYear, targetMonth, 1);
|
||||
var endDate = startDate.AddMonths(1);
|
||||
|
||||
var records = await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.OccurredAt >= startDate && t.OccurredAt < endDate)
|
||||
.ToListAsync();
|
||||
|
||||
var expense = records.Where(t => t.Type == TransactionType.Expense).Sum(t => Math.Abs(t.Amount));
|
||||
var income = records.Where(t => t.Type == TransactionType.Income).Sum(t => Math.Abs(t.Amount));
|
||||
|
||||
trends.Add(new TrendStatistics
|
||||
{
|
||||
Year = targetYear,
|
||||
Month = targetMonth,
|
||||
Expense = expense,
|
||||
Income = income,
|
||||
Balance = income - expense
|
||||
});
|
||||
}
|
||||
|
||||
return trends;
|
||||
}
|
||||
|
||||
public async Task<List<TransactionRecord>> GetClassifiedByKeywordsAsync(List<string> keywords, int limit = 10)
|
||||
{
|
||||
if (keywords == null || keywords.Count == 0)
|
||||
if (keywords.Count == 0)
|
||||
{
|
||||
return new List<TransactionRecord>();
|
||||
return [];
|
||||
}
|
||||
|
||||
var query = FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.Classify != ""); // 只查询已分类的账单
|
||||
.Where(t => t.Classify != "");
|
||||
|
||||
// 构建OR条件:Reason包含任意一个关键词
|
||||
if (keywords.Count > 0)
|
||||
{
|
||||
query = query.Where(t => keywords.Any(keyword => t.Reason.Contains(keyword)));
|
||||
@@ -615,71 +214,21 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<List<(TransactionRecord record, double relevanceScore)>> GetClassifiedByKeywordsWithScoreAsync(List<string> keywords, double minMatchRate = 0.3, int limit = 10)
|
||||
public async Task<List<TransactionRecord>> GetUnconfirmedRecordsAsync()
|
||||
{
|
||||
if (keywords == null || keywords.Count == 0)
|
||||
{
|
||||
return new List<(TransactionRecord, double)>();
|
||||
}
|
||||
|
||||
// 查询所有已分类且包含任意关键词的账单
|
||||
var candidates = await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.Classify != "")
|
||||
.Where(t => keywords.Any(keyword => t.Reason.Contains(keyword)))
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.UnconfirmedClassify != null && t.UnconfirmedClassify != "")
|
||||
.OrderByDescending(t => t.OccurredAt)
|
||||
.ToListAsync();
|
||||
|
||||
// 计算每个候选账单的相关度分数
|
||||
var scoredResults = candidates
|
||||
.Select(record =>
|
||||
{
|
||||
var matchedCount = keywords.Count(keyword => record.Reason.Contains(keyword, StringComparison.OrdinalIgnoreCase));
|
||||
var matchRate = (double)matchedCount / keywords.Count;
|
||||
|
||||
// 额外加分:完全匹配整个摘要(相似度更高)
|
||||
var exactMatchBonus = keywords.Any(k => record.Reason.Equals(k, StringComparison.OrdinalIgnoreCase)) ? 0.2 : 0.0;
|
||||
|
||||
// 长度相似度加分:长度越接近,相关度越高
|
||||
var avgKeywordLength = keywords.Average(k => k.Length);
|
||||
var lengthSimilarity = 1.0 - Math.Min(1.0, Math.Abs(record.Reason.Length - avgKeywordLength) / Math.Max(record.Reason.Length, avgKeywordLength));
|
||||
var lengthBonus = lengthSimilarity * 0.1;
|
||||
|
||||
var score = matchRate + exactMatchBonus + lengthBonus;
|
||||
return (record, score);
|
||||
})
|
||||
.Where(x => x.score >= minMatchRate) // 过滤低相关度结果
|
||||
.OrderByDescending(x => x.score) // 按相关度降序
|
||||
.ThenByDescending(x => x.record.OccurredAt) // 相同分数时,按时间降序
|
||||
.Take(limit)
|
||||
.ToList();
|
||||
|
||||
return scoredResults;
|
||||
}
|
||||
|
||||
public async Task<List<TransactionRecord>> GetCandidatesForOffsetAsync(long currentId, decimal amount, TransactionType currentType)
|
||||
public async Task<int> BatchUpdateByReasonAsync(string reason, TransactionType type, string classify)
|
||||
{
|
||||
var absAmount = Math.Abs(amount);
|
||||
var minAmount = absAmount - 5;
|
||||
var maxAmount = absAmount + 5;
|
||||
|
||||
var currentRecord = await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.Id == currentId)
|
||||
.FirstAsync();
|
||||
|
||||
if (currentRecord == null)
|
||||
{
|
||||
return new List<TransactionRecord>();
|
||||
}
|
||||
|
||||
var list = await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.Id != currentId)
|
||||
.Where(t => t.Type != currentType)
|
||||
.Where(t => Math.Abs(t.Amount) >= minAmount && Math.Abs(t.Amount) <= maxAmount)
|
||||
.Take(50)
|
||||
.ToListAsync();
|
||||
|
||||
return list.OrderBy(t => Math.Abs(Math.Abs(t.Amount) - absAmount))
|
||||
.ThenBy(x=> Math.Abs((x.OccurredAt - currentRecord.OccurredAt).TotalSeconds))
|
||||
.ToList();
|
||||
return await FreeSql.Update<TransactionRecord>()
|
||||
.Set(t => t.Type, type)
|
||||
.Set(t => t.Classify, classify)
|
||||
.Where(t => t.Reason == reason)
|
||||
.ExecuteAffrowsAsync();
|
||||
}
|
||||
|
||||
public async Task<int> UpdateCategoryNameAsync(string oldName, string newName, TransactionType type)
|
||||
@@ -690,14 +239,6 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
|
||||
.ExecuteAffrowsAsync();
|
||||
}
|
||||
|
||||
public async Task<List<TransactionRecord>> GetUnconfirmedRecordsAsync()
|
||||
{
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.UnconfirmedClassify != null && t.UnconfirmedClassify != "")
|
||||
.OrderByDescending(t => t.OccurredAt)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<int> ConfirmAllUnconfirmedAsync(long[] ids)
|
||||
{
|
||||
return await FreeSql.Update<TransactionRecord>()
|
||||
@@ -709,80 +250,4 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
|
||||
.Where(t => ids.Contains(t.Id))
|
||||
.ExecuteAffrowsAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按Reason分组统计DTO
|
||||
/// </summary>
|
||||
public class ReasonGroupDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 交易摘要
|
||||
/// </summary>
|
||||
public string Reason { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 该摘要的记录数量
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 示例交易类型(该分组中第一条记录的类型)
|
||||
/// </summary>
|
||||
public TransactionType SampleType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 示例分类(该分组中第一条记录的分类)
|
||||
/// </summary>
|
||||
public string SampleClassify { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 该分组的所有账单ID列表
|
||||
/// </summary>
|
||||
public List<long> TransactionIds { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 该分组的总金额(绝对值)
|
||||
/// </summary>
|
||||
public decimal TotalAmount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 月度统计数据
|
||||
/// </summary>
|
||||
public class MonthlyStatistics
|
||||
{
|
||||
public int Year { get; set; }
|
||||
public int Month { get; set; }
|
||||
public decimal TotalExpense { get; set; }
|
||||
public decimal TotalIncome { get; set; }
|
||||
public decimal Balance { get; set; }
|
||||
public int ExpenseCount { get; set; }
|
||||
public int IncomeCount { get; set; }
|
||||
public int TotalCount { get; set; }
|
||||
public decimal MaxExpense { get; set; }
|
||||
public decimal MaxIncome { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分类统计数据
|
||||
/// </summary>
|
||||
public class CategoryStatistics
|
||||
{
|
||||
public string Classify { get; set; } = string.Empty;
|
||||
public decimal Amount { get; set; }
|
||||
public int Count { get; set; }
|
||||
public decimal Percent { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 趋势统计数据
|
||||
/// </summary>
|
||||
public class TrendStatistics
|
||||
{
|
||||
public int Year { get; set; }
|
||||
public int Month { get; set; }
|
||||
public decimal Expense { get; set; }
|
||||
public decimal Income { get; set; }
|
||||
public decimal Balance { get; set; }
|
||||
}
|
||||
456
Repository/TransactionRecordRepository.md
Normal file
456
Repository/TransactionRecordRepository.md
Normal file
@@ -0,0 +1,456 @@
|
||||
# TransactionRecordRepository 查询语句文档
|
||||
|
||||
本文档整理了所有与账单(TransactionRecord)相关的查询语句,包括仓储层、服务层中的SQL查询。
|
||||
|
||||
## 目录
|
||||
|
||||
1. [TransactionRecordRepository 查询方法](#transactionrecordrepository-查询方法)
|
||||
2. [其他仓储中的账单查询](#其他仓储中的账单查询)
|
||||
3. [服务层中的SQL查询](#服务层中的sql查询)
|
||||
4. [总结](#总结)
|
||||
|
||||
---
|
||||
|
||||
## TransactionRecordRepository 查询方法
|
||||
|
||||
### 1. 基础查询
|
||||
|
||||
#### 1.1 根据邮件ID和交易时间检查是否存在
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:94-99
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.EmailMessageId == emailMessageId && t.OccurredAt == occurredAt)
|
||||
.FirstAsync();
|
||||
```
|
||||
|
||||
#### 1.2 根据导入编号检查是否存在
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:101-106
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.ImportNo == importNo && t.ImportFrom == importFrom)
|
||||
.FirstAsync();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 核心查询构建器
|
||||
|
||||
#### 2.1 BuildQuery() 私有方法 - 统一查询构建
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:53-92
|
||||
private ISelect<TransactionRecord> BuildQuery(
|
||||
int? year = null,
|
||||
int? month = null,
|
||||
DateTime? startDate = null,
|
||||
DateTime? endDate = null,
|
||||
TransactionType? type = null,
|
||||
string[]? classifies = null,
|
||||
string? searchKeyword = null,
|
||||
string? reason = null)
|
||||
{
|
||||
var query = FreeSql.Select<TransactionRecord>();
|
||||
|
||||
// 搜索关键词条件(Reason/Classify/Card/ImportFrom)
|
||||
query = query.WhereIf(!string.IsNullOrWhiteSpace(searchKeyword),
|
||||
t => t.Reason.Contains(searchKeyword!) ||
|
||||
t.Classify.Contains(searchKeyword!) ||
|
||||
t.Card.Contains(searchKeyword!) ||
|
||||
t.ImportFrom.Contains(searchKeyword!))
|
||||
.WhereIf(!string.IsNullOrWhiteSpace(reason),
|
||||
t => t.Reason == reason);
|
||||
|
||||
// 按分类筛选(处理"未分类"特殊情况)
|
||||
if (classifies is { Length: > 0 })
|
||||
{
|
||||
var filterClassifies = classifies.Select(c => c == "未分类" ? string.Empty : c).ToList();
|
||||
query = query.Where(t => filterClassifies.Contains(t.Classify));
|
||||
}
|
||||
|
||||
// 按交易类型筛选
|
||||
query = query.WhereIf(type.HasValue, t => t.Type == type!.Value);
|
||||
|
||||
// 按年月筛选
|
||||
if (year.HasValue && month.HasValue)
|
||||
{
|
||||
var dateStart = new DateTime(year.Value, month.Value, 1);
|
||||
var dateEnd = dateStart.AddMonths(1);
|
||||
query = query.Where(t => t.OccurredAt >= dateStart && t.OccurredAt < dateEnd);
|
||||
}
|
||||
|
||||
// 按日期范围筛选
|
||||
query = query.WhereIf(startDate.HasValue, t => t.OccurredAt >= startDate!.Value)
|
||||
.WhereIf(endDate.HasValue, t => t.OccurredAt <= endDate!.Value);
|
||||
|
||||
return query;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. 分页查询与统计
|
||||
|
||||
#### 3.1 分页获取交易记录列表
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:108-137
|
||||
var query = BuildQuery(year, month, startDate, endDate, type, classifies, searchKeyword, reason);
|
||||
|
||||
// 排序:按金额或按时间
|
||||
if (sortByAmount)
|
||||
{
|
||||
return await query
|
||||
.OrderByDescending(t => t.Amount)
|
||||
.OrderByDescending(t => t.Id)
|
||||
.Page(pageIndex, pageSize)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
return await query
|
||||
.OrderByDescending(t => t.OccurredAt)
|
||||
.OrderByDescending(t => t.Id)
|
||||
.Page(pageIndex, pageSize)
|
||||
.ToListAsync();
|
||||
```
|
||||
|
||||
#### 3.2 获取总数(与分页查询条件相同)
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:139-151
|
||||
var query = BuildQuery(year, month, startDate, endDate, type, classifies, searchKeyword, reason);
|
||||
return await query.CountAsync();
|
||||
```
|
||||
|
||||
#### 3.3 获取所有不同的交易分类
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:153-159
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => !string.IsNullOrEmpty(t.Classify))
|
||||
.Distinct()
|
||||
.ToListAsync(t => t.Classify);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. 按邮件相关查询
|
||||
|
||||
#### 4.1 获取指定邮件的交易记录列表
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:161-167
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.EmailMessageId == emailMessageId)
|
||||
.OrderBy(t => t.OccurredAt)
|
||||
.ToListAsync();
|
||||
```
|
||||
|
||||
#### 4.2 获取指定邮件的交易记录数量
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:169-174
|
||||
return (int)await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.EmailMessageId == emailMessageId)
|
||||
.CountAsync();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 未分类账单查询
|
||||
|
||||
#### 5.1 获取未分类的账单列表
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:176-183
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => string.IsNullOrEmpty(t.Classify))
|
||||
.OrderByDescending(t => t.OccurredAt)
|
||||
.Page(1, pageSize)
|
||||
.ToListAsync();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6. 智能分类相关查询
|
||||
|
||||
#### 6.1 根据关键词查询已分类的账单
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:185-204
|
||||
if (keywords.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var query = FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.Classify != "");
|
||||
|
||||
// 构建OR条件:Reason包含任意一个关键词
|
||||
if (keywords.Count > 0)
|
||||
{
|
||||
query = query.Where(t => keywords.Any(keyword => t.Reason.Contains(keyword)));
|
||||
}
|
||||
|
||||
return await query
|
||||
.OrderByDescending(t => t.OccurredAt)
|
||||
.Limit(limit)
|
||||
.ToListAsync();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 7. 待确认分类查询
|
||||
|
||||
#### 7.1 获取待确认分类的账单列表
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:206-212
|
||||
return await FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.UnconfirmedClassify != null && t.UnconfirmedClassify != "")
|
||||
.OrderByDescending(t => t.OccurredAt)
|
||||
.ToListAsync();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 8. 批量更新操作
|
||||
|
||||
#### 8.1 按摘要批量更新交易记录的分类
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:214-221
|
||||
return await FreeSql.Update<TransactionRecord>()
|
||||
.Set(t => t.Type, type)
|
||||
.Set(t => t.Classify, classify)
|
||||
.Where(t => t.Reason == reason)
|
||||
.ExecuteAffrowsAsync();
|
||||
```
|
||||
|
||||
#### 8.2 更新分类名称
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:223-229
|
||||
return await FreeSql.Update<TransactionRecord>()
|
||||
.Set(a => a.Classify, newName)
|
||||
.Where(a => a.Classify == oldName && a.Type == type)
|
||||
.ExecuteAffrowsAsync();
|
||||
```
|
||||
|
||||
#### 8.3 确认待确认的分类
|
||||
```csharp
|
||||
/// 位置: TransactionRecordRepository.cs:231-241
|
||||
return await FreeSql.Update<TransactionRecord>()
|
||||
.Set(t => t.Classify == t.UnconfirmedClassify)
|
||||
.Set(t => t.Type == (t.UnconfirmedType ?? t.Type))
|
||||
.Set(t => t.UnconfirmedClassify, null)
|
||||
.Set(t => t.UnconfirmedType, null)
|
||||
.Where(t => t.UnconfirmedClassify != null && t.UnconfirmedClassify != "")
|
||||
.Where(t => ids.Contains(t.Id))
|
||||
.ExecuteAffrowsAsync();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 其他仓储中的账单查询
|
||||
|
||||
### BudgetRepository
|
||||
|
||||
#### 1. 获取预算当前金额
|
||||
```csharp
|
||||
/// 位置: BudgetRepository.cs:12-33
|
||||
var query = FreeSql.Select<TransactionRecord>()
|
||||
.Where(t => t.OccurredAt >= startDate && t.OccurredAt <= endDate);
|
||||
|
||||
if (!string.IsNullOrEmpty(budget.SelectedCategories))
|
||||
{
|
||||
var categoryList = budget.SelectedCategories.Split(',');
|
||||
query = query.Where(t => categoryList.Contains(t.Classify));
|
||||
}
|
||||
|
||||
if (budget.Category == BudgetCategory.Expense)
|
||||
{
|
||||
query = query.Where(t => t.Type == TransactionType.Expense);
|
||||
}
|
||||
else if (budget.Category == BudgetCategory.Income)
|
||||
{
|
||||
query = query.Where(t => t.Type == TransactionType.Income);
|
||||
}
|
||||
|
||||
return await query.SumAsync(t => t.Amount);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### TransactionCategoryRepository
|
||||
|
||||
#### 1. 检查分类是否被使用
|
||||
```csharp
|
||||
/// 位置: TransactionCategoryRepository.cs:53-63
|
||||
var count = await FreeSql.Select<TransactionRecord>()
|
||||
.Where(r => r.Classify == category.Name && r.Type == category.Type)
|
||||
.CountAsync();
|
||||
|
||||
return count > 0;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 服务层中的SQL查询
|
||||
|
||||
### SmartHandleService
|
||||
|
||||
#### 1. 智能分析账单 - 执行AI生成的SQL
|
||||
```csharp
|
||||
/// 位置: SmartHandleService.cs:351
|
||||
queryResults = await transactionRepository.ExecuteDynamicSqlAsync(sqlText);
|
||||
```
|
||||
|
||||
**说明**: 此方法接收AI生成的SQL语句并执行,SQL内容由AI根据用户问题动态生成,例如:
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
COUNT(*) AS TransactionCount,
|
||||
SUM(ABS(Amount)) AS TotalAmount,
|
||||
Type,
|
||||
Classify
|
||||
FROM TransactionRecord
|
||||
WHERE OccurredAt >= '2025-01-01'
|
||||
AND OccurredAt < '2026-01-01'
|
||||
GROUP BY Type, Classify
|
||||
ORDER BY TotalAmount DESC
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### BudgetService
|
||||
|
||||
#### 1. 获取归档摘要 - 年度交易统计
|
||||
```csharp
|
||||
/// 位置: BudgetService.cs:239-252
|
||||
var yearTransactions = await transactionRecordRepository.ExecuteDynamicSqlAsync(
|
||||
$"""
|
||||
SELECT
|
||||
COUNT(*) AS TransactionCount,
|
||||
SUM(ABS(Amount)) AS TotalAmount,
|
||||
Type,
|
||||
Classify
|
||||
FROM TransactionRecord
|
||||
WHERE OccurredAt >= '{year}-01-01'
|
||||
AND OccurredAt < '{year + 1}-01-01'
|
||||
GROUP BY Type, Classify
|
||||
ORDER BY TotalAmount DESC
|
||||
"""
|
||||
);
|
||||
```
|
||||
|
||||
#### 2. 获取归档摘要 - 月度交易统计
|
||||
```csharp
|
||||
/// 位置: BudgetService.cs:254-267
|
||||
var monthYear = new DateTime(year, month, 1).AddMonths(1);
|
||||
var monthTransactions = await transactionRecordRepository.ExecuteDynamicSqlAsync(
|
||||
$"""
|
||||
SELECT
|
||||
COUNT(*) AS TransactionCount,
|
||||
SUM(ABS(Amount)) AS TotalAmount,
|
||||
Type,
|
||||
Classify
|
||||
FROM TransactionRecord
|
||||
WHERE OccurredAt >= '{year}-{month:00}-01'
|
||||
AND OccurredAt < '{monthYear:yyyy-MM-dd}'
|
||||
GROUP BY Type, Classify
|
||||
ORDER BY TotalAmount DESC
|
||||
"""
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### BudgetSavingsService
|
||||
|
||||
#### 1. 获取按分类分组的交易金额(用于存款预算计算)
|
||||
```csharp
|
||||
/// 位置: BudgetSavingsService.cs:62-65
|
||||
var transactionClassify = await transactionsRepository.GetAmountGroupByClassifyAsync(
|
||||
new DateTime(year, month, 1),
|
||||
new DateTime(year, month, 1).AddMonths(1)
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 总结
|
||||
|
||||
### 查询方法分类
|
||||
|
||||
| 分类 | 方法数 | 说明 |
|
||||
|------|--------|------|
|
||||
| 基础查询 | 2 | 检查记录是否存在(去重) |
|
||||
| 核心构建器 | 1 | BuildQuery() 私有方法,统一查询逻辑 |
|
||||
| 分页查询 | 2 | 分页列表 + 总数统计 |
|
||||
| 分类查询 | 1 | 获取所有不同分类 |
|
||||
| 邮件相关 | 2 | 按邮件ID查询列表和数量 |
|
||||
| 未分类查询 | 1 | 获取未分类账单列表 |
|
||||
| 智能分类 | 1 | 关键词匹配查询 |
|
||||
| 待确认分类 | 1 | 获取待确认账单列表 |
|
||||
| 批量更新 | 3 | 批量更新分类和确认操作 |
|
||||
| 其他仓储查询 | 2 | 预算/分类仓储中的账单查询 |
|
||||
| 服务层SQL | 3 | AI生成SQL + 归档统计 |
|
||||
|
||||
### 关键发现
|
||||
|
||||
1. **简化的架构**:新实现移除了复杂的统计方法,专注于核心的CRUD操作和查询功能。
|
||||
|
||||
2. **统一的查询构建**:`BuildQuery()` 私有方法(第53-92行)被 `QueryAsync()` 和 `CountAsync()` 共享使用,确保查询逻辑一致性。
|
||||
|
||||
3. **去重检查**:`ExistsByEmailMessageIdAsync()` 和 `ExistsByImportNoAsync()` 用于防止重复导入。
|
||||
|
||||
4. **灵活的查询条件**:支持按年月、日期范围、交易类型、分类、关键词等多维度筛选。
|
||||
|
||||
5. **批量操作优化**:提供批量更新分类、确认待确认记录等高效操作。
|
||||
|
||||
6. **服务层SQL保持不变**:AI生成SQL和归档统计等高级查询功能仍然通过 `ExecuteDynamicSqlAsync()` 实现。
|
||||
|
||||
### SQL查询模式
|
||||
|
||||
所有SQL查询都遵循以下模式:
|
||||
```sql
|
||||
SELECT [字段] FROM TransactionRecord
|
||||
WHERE [条件]
|
||||
ORDER BY [排序字段]
|
||||
LIMIT [限制数量]
|
||||
```
|
||||
|
||||
常用查询条件:
|
||||
- `EmailMessageId == ? AND OccurredAt == ?` - 精确匹配去重
|
||||
- `ImportNo == ? AND ImportFrom == ?` - 导入记录去重
|
||||
- `Classify != ""` - 已分类记录
|
||||
- `Classify == "" OR Classify IS NULL` - 未分类记录
|
||||
- `UnconfirmedClassify != ""` - 待确认记录
|
||||
- `Reason.Contains(?) OR Classify.Contains(?)` - 关键词搜索
|
||||
|
||||
### 字段说明
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| Id | bigint | 主键 |
|
||||
| Card | nvarchar | 卡号 |
|
||||
| Reason | nvarchar | 交易原因/摘要 |
|
||||
| Amount | decimal | 交易金额(支出为负数,收入为正数) |
|
||||
| OccurredAt | datetime | 交易发生时间 |
|
||||
| Type | int | 交易类型(0=支出, 1=收入, 2=不计入收支) |
|
||||
| Classify | nvarchar | 交易分类(空字符串表示未分类) |
|
||||
| EmailMessageId | bigint | 关联邮件ID |
|
||||
| ImportNo | nvarchar | 导入编号 |
|
||||
| ImportFrom | nvarchar | 导入来源 |
|
||||
| UnconfirmedClassify | nvarchar | 待确认分类 |
|
||||
| UnconfirmedType | int? | 待确认类型 |
|
||||
|
||||
### 接口方法总览
|
||||
|
||||
**ITransactionRecordRepository 接口定义(17个方法):**
|
||||
|
||||
1. `ExistsByEmailMessageIdAsync()` - 邮件去重检查
|
||||
2. `ExistsByImportNoAsync()` - 导入去重检查
|
||||
3. `QueryAsync()` - 分页查询(支持多维度筛选)
|
||||
4. `CountAsync()` - 总数统计(与QueryAsync条件相同)
|
||||
5. `GetDistinctClassifyAsync()` - 获取所有分类
|
||||
6. `GetByEmailIdAsync()` - 按邮件ID查询记录
|
||||
7. `GetCountByEmailIdAsync()` - 按邮件ID统计数量
|
||||
8. `GetUnclassifiedAsync()` - 获取未分类记录
|
||||
9. `GetClassifiedByKeywordsAsync()` - 关键词匹配查询
|
||||
10. `GetUnconfirmedRecordsAsync()` - 获取待确认记录
|
||||
11. `BatchUpdateByReasonAsync()` - 按摘要批量更新
|
||||
12. `UpdateCategoryNameAsync()` - 更新分类名称
|
||||
13. `ConfirmAllUnconfirmedAsync()` - 确认待确认记录
|
||||
|
||||
**私有辅助方法:**
|
||||
- `BuildQuery()` - 统一查询构建器(被QueryAsync和CountAsync使用)
|
||||
55
Service/AGENTS.md
Normal file
55
Service/AGENTS.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# SERVICE LAYER KNOWLEDGE BASE
|
||||
|
||||
**Generated:** 2026-01-28
|
||||
**Parent:** EmailBill/AGENTS.md
|
||||
|
||||
## OVERVIEW
|
||||
Business logic layer with job scheduling, email processing, and application services.
|
||||
|
||||
## STRUCTURE
|
||||
```
|
||||
Service/
|
||||
├── GlobalUsings.cs # Common imports
|
||||
├── Jobs/ # Background jobs
|
||||
│ ├── BudgetArchiveJob.cs # Budget archiving
|
||||
│ ├── DbBackupJob.cs # Database backups
|
||||
│ ├── EmailSyncJob.cs # Email synchronization
|
||||
│ └── PeriodicBillJob.cs # Periodic bill processing
|
||||
├── EmailServices/ # Email processing
|
||||
│ ├── EmailHandleService.cs # Email handling logic
|
||||
│ ├── EmailFetchService.cs # Email fetching
|
||||
│ ├── EmailSyncService.cs # Email synchronization
|
||||
│ └── EmailParse/ # Email parsing services
|
||||
├── AppSettingModel/ # Configuration models
|
||||
├── Budget/ # Budget services
|
||||
└── [Various service classes] # Core business services
|
||||
```
|
||||
|
||||
## WHERE TO LOOK
|
||||
| Task | Location | Notes |
|
||||
|------|----------|-------|
|
||||
| Background jobs | Jobs/ | Scheduled tasks, cron patterns |
|
||||
| Email processing | EmailServices/ | Email parsing, handling, sync |
|
||||
| Budget logic | Budget/ | Budget calculations, stats |
|
||||
| Configuration | AppSettingModel/ | Settings models, validation |
|
||||
| Core services | *.cs | Main business logic |
|
||||
|
||||
## CONVENTIONS
|
||||
- Service classes end with "Service" suffix
|
||||
- Jobs inherit from appropriate base job classes
|
||||
- Use IDateTimeProvider for time operations
|
||||
- Async/await for I/O operations
|
||||
- Dependency injection via constructor
|
||||
|
||||
## ANTI-PATTERNS (THIS LAYER)
|
||||
- Never access database directly (use repositories)
|
||||
- Don't return domain entities to controllers (use DTOs)
|
||||
- Avoid long-running operations in main thread
|
||||
- No hardcoded configuration values
|
||||
- Don't mix service responsibilities
|
||||
|
||||
## UNIQUE STYLES
|
||||
- Email parsing with multiple format handlers
|
||||
- Background job patterns with error handling
|
||||
- Configuration models with validation attributes
|
||||
- Service composition patterns
|
||||
@@ -1,25 +1,25 @@
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
namespace Service;
|
||||
namespace Service.AI;
|
||||
|
||||
public interface IOpenAiService
|
||||
{
|
||||
Task<string?> ChatAsync(string systemPrompt, string userPrompt);
|
||||
Task<string?> ChatAsync(string prompt);
|
||||
Task<string?> ChatAsync(string systemPrompt, string userPrompt, int timeoutSeconds = 15);
|
||||
Task<string?> ChatAsync(string prompt, int timeoutSeconds = 15);
|
||||
IAsyncEnumerable<string> ChatStreamAsync(string systemPrompt, string userPrompt);
|
||||
IAsyncEnumerable<string> ChatStreamAsync(string prompt);
|
||||
}
|
||||
|
||||
public class OpenAiService(
|
||||
IOptions<AISettings> aiSettings,
|
||||
IOptions<AiSettings> aiSettings,
|
||||
ILogger<OpenAiService> logger
|
||||
) : IOpenAiService
|
||||
{
|
||||
public async Task<string?> ChatAsync(string systemPrompt, string userPrompt)
|
||||
public async Task<string?> ChatAsync(string systemPrompt, string userPrompt, int timeoutSeconds = 15)
|
||||
{
|
||||
var cfg = aiSettings.Value;
|
||||
if (string.IsNullOrWhiteSpace(cfg.Endpoint) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Key) ||
|
||||
if (string.IsNullOrWhiteSpace(cfg.Endpoint) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Key) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Model))
|
||||
{
|
||||
logger.LogWarning("未配置 OpenAI/DeepSeek 接口,无法调用 AI");
|
||||
@@ -27,7 +27,7 @@ public class OpenAiService(
|
||||
}
|
||||
|
||||
using var http = new HttpClient();
|
||||
http.Timeout = TimeSpan.FromSeconds(15);
|
||||
http.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
|
||||
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", cfg.Key);
|
||||
|
||||
var payload = new
|
||||
@@ -44,7 +44,7 @@ public class OpenAiService(
|
||||
var url = cfg.Endpoint.TrimEnd('/') + "/chat/completions";
|
||||
var json = JsonSerializer.Serialize(payload);
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
using var resp = await http.PostAsync(url, content);
|
||||
@@ -72,11 +72,11 @@ public class OpenAiService(
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string?> ChatAsync(string prompt)
|
||||
public async Task<string?> ChatAsync(string prompt, int timeoutSeconds = 15)
|
||||
{
|
||||
var cfg = aiSettings.Value;
|
||||
if (string.IsNullOrWhiteSpace(cfg.Endpoint) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Key) ||
|
||||
if (string.IsNullOrWhiteSpace(cfg.Endpoint) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Key) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Model))
|
||||
{
|
||||
logger.LogWarning("未配置 OpenAI/DeepSeek 接口,无法调用 AI");
|
||||
@@ -84,7 +84,7 @@ public class OpenAiService(
|
||||
}
|
||||
|
||||
using var http = new HttpClient();
|
||||
http.Timeout = TimeSpan.FromSeconds(60 * 5);
|
||||
http.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
|
||||
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", cfg.Key);
|
||||
|
||||
var payload = new
|
||||
@@ -100,7 +100,7 @@ public class OpenAiService(
|
||||
var url = cfg.Endpoint.TrimEnd('/') + "/chat/completions";
|
||||
var json = JsonSerializer.Serialize(payload);
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
using var resp = await http.PostAsync(url, content);
|
||||
@@ -131,8 +131,8 @@ public class OpenAiService(
|
||||
public async IAsyncEnumerable<string> ChatStreamAsync(string prompt)
|
||||
{
|
||||
var cfg = aiSettings.Value;
|
||||
if (string.IsNullOrWhiteSpace(cfg.Endpoint) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Key) ||
|
||||
if (string.IsNullOrWhiteSpace(cfg.Endpoint) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Key) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Model))
|
||||
{
|
||||
logger.LogWarning("未配置 OpenAI/DeepSeek 接口,无法调用 AI");
|
||||
@@ -157,13 +157,11 @@ public class OpenAiService(
|
||||
var url = cfg.Endpoint.TrimEnd('/') + "/chat/completions";
|
||||
var json = JsonSerializer.Serialize(payload);
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, url)
|
||||
{
|
||||
Content = content
|
||||
};
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, url);
|
||||
request.Content = content;
|
||||
using var resp = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
|
||||
|
||||
|
||||
if (!resp.IsSuccessStatusCode)
|
||||
{
|
||||
var err = await resp.Content.ReadAsStringAsync();
|
||||
@@ -203,8 +201,8 @@ public class OpenAiService(
|
||||
public async IAsyncEnumerable<string> ChatStreamAsync(string systemPrompt, string userPrompt)
|
||||
{
|
||||
var cfg = aiSettings.Value;
|
||||
if (string.IsNullOrWhiteSpace(cfg.Endpoint) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Key) ||
|
||||
if (string.IsNullOrWhiteSpace(cfg.Endpoint) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Key) ||
|
||||
string.IsNullOrWhiteSpace(cfg.Model))
|
||||
{
|
||||
logger.LogWarning("未配置 OpenAI/DeepSeek 接口,无法调用 AI");
|
||||
@@ -230,14 +228,12 @@ public class OpenAiService(
|
||||
var url = cfg.Endpoint.TrimEnd('/') + "/chat/completions";
|
||||
var json = JsonSerializer.Serialize(payload);
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
|
||||
|
||||
// 使用 SendAsync 来支持 HttpCompletionOption
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, url)
|
||||
{
|
||||
Content = content
|
||||
};
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, url);
|
||||
request.Content = content;
|
||||
using var resp = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
|
||||
|
||||
|
||||
if (!resp.IsSuccessStatusCode)
|
||||
{
|
||||
var err = await resp.Content.ReadAsStringAsync();
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace Service;
|
||||
using Service.Transaction;
|
||||
|
||||
namespace Service.AI;
|
||||
|
||||
public interface ISmartHandleService
|
||||
{
|
||||
@@ -11,6 +13,7 @@ public interface ISmartHandleService
|
||||
|
||||
public class SmartHandleService(
|
||||
ITransactionRecordRepository transactionRepository,
|
||||
ITransactionStatisticsService transactionStatisticsService,
|
||||
ITextSegmentService textSegmentService,
|
||||
ILogger<SmartHandleService> logger,
|
||||
ITransactionCategoryRepository categoryRepository,
|
||||
@@ -61,7 +64,7 @@ public class SmartHandleService(
|
||||
{
|
||||
// 查询包含这些关键词且已分类的账单(带相关度评分)
|
||||
// minMatchRate=0.4 表示至少匹配40%的关键词才被认为是相似的
|
||||
var similarClassifiedWithScore = await transactionRepository.GetClassifiedByKeywordsWithScoreAsync(keywords, minMatchRate: 0.4, limit: 10);
|
||||
var similarClassifiedWithScore = await transactionStatisticsService.GetClassifiedByKeywordsWithScoreAsync(keywords, minMatchRate: 0.4, limit: 10);
|
||||
|
||||
if (similarClassifiedWithScore.Count > 0)
|
||||
{
|
||||
@@ -143,7 +146,7 @@ public class SmartHandleService(
|
||||
chunkAction(("start", $"开始分类,共 {sampleRecords.Length} 条账单"));
|
||||
|
||||
var classifyResults = new List<(string Reason, string Classify, TransactionType Type)>();
|
||||
var sendedIds = new HashSet<long>();
|
||||
var sentIds = new HashSet<long>();
|
||||
|
||||
// 将流解析逻辑提取为本地函数以减少嵌套
|
||||
void HandleResult(GroupClassifyResult? result)
|
||||
@@ -154,16 +157,18 @@ public class SmartHandleService(
|
||||
if (group == null) return;
|
||||
foreach (var id in group.Ids)
|
||||
{
|
||||
if (sendedIds.Add(id))
|
||||
if (!sentIds.Add(id))
|
||||
{
|
||||
var resultJson = JsonSerializer.Serialize(new
|
||||
{
|
||||
id,
|
||||
result.Classify,
|
||||
result.Type
|
||||
});
|
||||
chunkAction(("data", resultJson));
|
||||
continue;
|
||||
}
|
||||
|
||||
var resultJson = JsonSerializer.Serialize(new
|
||||
{
|
||||
id,
|
||||
result.Classify,
|
||||
result.Type
|
||||
});
|
||||
chunkAction(("data", resultJson));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,7 +198,7 @@ public class SmartHandleService(
|
||||
}
|
||||
catch (Exception exArr)
|
||||
{
|
||||
logger.LogDebug(exArr, "按数组解析AI返回失败,回退到逐对象解析。预览: {Preview}", arrJson?.Length > 200 ? arrJson.Substring(0, 200) + "..." : arrJson);
|
||||
logger.LogDebug(exArr, "按数组解析AI返回失败,回退到逐对象解析。预览: {Preview}", arrJson.Length > 200 ? arrJson.Substring(0, 200) + "..." : arrJson);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -336,7 +341,7 @@ public class SmartHandleService(
|
||||
{
|
||||
content = $"""
|
||||
<pre style="max-height: 80px; font-size: 8px; overflow-y: auto; padding: 8px; border: 1px solid #3c3c3c">
|
||||
{System.Net.WebUtility.HtmlEncode(sqlText)}
|
||||
{WebUtility.HtmlEncode(sqlText)}
|
||||
</pre>
|
||||
"""
|
||||
})
|
||||
@@ -361,7 +366,7 @@ public class SmartHandleService(
|
||||
var dataJson = JsonSerializer.Serialize(queryResults, new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
});
|
||||
|
||||
var userPromptExtra = await configService.GetConfigByKeyAsync<string>("BillAnalysisPrompt");
|
||||
@@ -429,7 +434,6 @@ public class SmartHandleService(
|
||||
{
|
||||
// 获取所有分类
|
||||
var categories = await categoryRepository.GetAllAsync();
|
||||
var categoryList = string.Join("、", categories.Select(c => $"{GetTypeName(c.Type)}-{c.Name}"));
|
||||
|
||||
// 构建分类信息
|
||||
var categoryInfo = new StringBuilder();
|
||||
@@ -490,8 +494,8 @@ public class SmartHandleService(
|
||||
/// </summary>
|
||||
private static int FindMatchingBrace(string str, int startPos)
|
||||
{
|
||||
int braceCount = 0;
|
||||
for (int i = startPos; i < str.Length; i++)
|
||||
var braceCount = 0;
|
||||
for (var i = startPos; i < str.Length; i++)
|
||||
{
|
||||
if (str[i] == '{') braceCount++;
|
||||
else if (str[i] == '}')
|
||||
@@ -542,13 +546,13 @@ public class SmartHandleService(
|
||||
public record GroupClassifyResult
|
||||
{
|
||||
[JsonPropertyName("reason")]
|
||||
public string Reason { get; set; } = string.Empty;
|
||||
public string Reason { get; init; } = string.Empty;
|
||||
|
||||
[JsonPropertyName("classify")]
|
||||
public string? Classify { get; set; }
|
||||
public string? Classify { get; init; }
|
||||
|
||||
[JsonPropertyName("type")]
|
||||
public TransactionType Type { get; set; }
|
||||
public TransactionType Type { get; init; }
|
||||
}
|
||||
|
||||
public record TransactionParseResult(string OccurredAt, string Classify, decimal Amount, string Reason, TransactionType Type);
|
||||
@@ -1,8 +1,7 @@
|
||||
namespace Service;
|
||||
|
||||
using JiebaNet.Analyser;
|
||||
using JiebaNet.Segmenter;
|
||||
using JiebaNet.Analyser;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Service.AI;
|
||||
|
||||
/// <summary>
|
||||
/// 文本分词服务接口
|
||||
@@ -39,7 +38,7 @@ public class TextSegmentService : ITextSegmentService
|
||||
_logger = logger;
|
||||
_segmenter = new JiebaSegmenter();
|
||||
_extractor = new TfidfExtractor();
|
||||
|
||||
|
||||
// 仅添加JiebaNet词典中可能缺失的特定业务词汇
|
||||
AddCustomWords();
|
||||
}
|
||||
@@ -78,7 +77,7 @@ public class TextSegmentService : ITextSegmentService
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return new List<string>();
|
||||
return [];
|
||||
}
|
||||
|
||||
try
|
||||
@@ -110,7 +109,7 @@ public class TextSegmentService : ITextSegmentService
|
||||
filteredKeywords.Add(text.Length > 10 ? text.Substring(0, 10) : text);
|
||||
}
|
||||
|
||||
_logger.LogDebug("从文本 '{Text}' 中提取关键词: {Keywords}",
|
||||
_logger.LogDebug("从文本 '{Text}' 中提取关键词: {Keywords}",
|
||||
text, string.Join(", ", filteredKeywords));
|
||||
|
||||
return filteredKeywords;
|
||||
@@ -119,7 +118,7 @@ public class TextSegmentService : ITextSegmentService
|
||||
{
|
||||
_logger.LogError(ex, "提取关键词失败,文本: {Text}", text);
|
||||
// 降级处理:返回原文
|
||||
return new List<string> { text.Length > 10 ? text.Substring(0, 10) : text };
|
||||
return [text.Length > 10 ? text.Substring(0, 10) : text];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,7 +126,7 @@ public class TextSegmentService : ITextSegmentService
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return new List<string>();
|
||||
return [];
|
||||
}
|
||||
|
||||
try
|
||||
@@ -146,7 +145,7 @@ public class TextSegmentService : ITextSegmentService
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "分词失败,文本: {Text}", text);
|
||||
return new List<string> { text };
|
||||
return [text];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace Service.AppSettingModel;
|
||||
|
||||
public class AISettings
|
||||
public class AiSettings
|
||||
{
|
||||
public string Endpoint { get; set; } = string.Empty;
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
929
Service/Budget/BudgetSavingsService.cs
Normal file
929
Service/Budget/BudgetSavingsService.cs
Normal file
@@ -0,0 +1,929 @@
|
||||
using Service.Transaction;
|
||||
|
||||
namespace Service.Budget;
|
||||
|
||||
public interface IBudgetSavingsService
|
||||
{
|
||||
Task<BudgetResult> GetSavingsDtoAsync(
|
||||
BudgetPeriodType periodType,
|
||||
DateTime? referenceDate = null,
|
||||
IEnumerable<BudgetRecord>? existingBudgets = null);
|
||||
}
|
||||
|
||||
public class BudgetSavingsService(
|
||||
IBudgetRepository budgetRepository,
|
||||
IBudgetArchiveRepository budgetArchiveRepository,
|
||||
ITransactionStatisticsService transactionStatisticsService,
|
||||
IConfigService configService,
|
||||
IDateTimeProvider dateTimeProvider
|
||||
) : IBudgetSavingsService
|
||||
{
|
||||
public async Task<BudgetResult> GetSavingsDtoAsync(
|
||||
BudgetPeriodType periodType,
|
||||
DateTime? referenceDate = null,
|
||||
IEnumerable<BudgetRecord>? existingBudgets = null)
|
||||
{
|
||||
var budgets = existingBudgets;
|
||||
|
||||
if (existingBudgets == null)
|
||||
{
|
||||
budgets = await budgetRepository.GetAllAsync();
|
||||
}
|
||||
|
||||
if (budgets == null)
|
||||
{
|
||||
throw new InvalidOperationException("No budgets found.");
|
||||
}
|
||||
|
||||
budgets = budgets
|
||||
// 排序顺序 1.硬性预算 2.月度->年度 3.实际金额倒叙
|
||||
.OrderBy(b => b.IsMandatoryExpense)
|
||||
.ThenBy(b => b.Type)
|
||||
.ThenByDescending(b => b.Limit);
|
||||
|
||||
var year = referenceDate?.Year ?? dateTimeProvider.Now.Year;
|
||||
var month = referenceDate?.Month ?? dateTimeProvider.Now.Month;
|
||||
|
||||
if (periodType == BudgetPeriodType.Month)
|
||||
{
|
||||
return await GetForMonthAsync(budgets, year, month);
|
||||
}
|
||||
else if (periodType == BudgetPeriodType.Year)
|
||||
{
|
||||
return await GetForYearAsync(budgets, year);
|
||||
}
|
||||
|
||||
throw new NotSupportedException($"Period type {periodType} is not supported.");
|
||||
}
|
||||
|
||||
private async Task<BudgetResult> GetForMonthAsync(
|
||||
IEnumerable<BudgetRecord> budgets,
|
||||
int year,
|
||||
int month)
|
||||
{
|
||||
var transactionClassify = await transactionStatisticsService.GetAmountGroupByClassifyAsync(
|
||||
new DateTime(year, month, 1),
|
||||
new DateTime(year, month, 1).AddMonths(1)
|
||||
);
|
||||
|
||||
var monthlyIncomeItems = new List<(string name, decimal limit, decimal current, bool isMandatory)>();
|
||||
var monthlyExpenseItems = new List<(string name, decimal limit, decimal current, bool isMandatory)>();
|
||||
var monthlyBudgets = budgets
|
||||
.Where(b => b.Type == BudgetPeriodType.Month);
|
||||
foreach (var budget in monthlyBudgets)
|
||||
{
|
||||
var classifyList = budget.SelectedCategories.Split(',', StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
decimal currentAmount = 0;
|
||||
var transactionType = budget.Category switch
|
||||
{
|
||||
BudgetCategory.Income => TransactionType.Income,
|
||||
BudgetCategory.Expense => TransactionType.Expense,
|
||||
_ => throw new NotSupportedException($"Budget category {budget.Category} is not supported.")
|
||||
};
|
||||
|
||||
foreach (var classify in classifyList)
|
||||
{
|
||||
// 获取分类+收入支出类型一致的金额
|
||||
if (transactionClassify.TryGetValue((classify, transactionType), out var amount))
|
||||
{
|
||||
currentAmount += amount;
|
||||
}
|
||||
}
|
||||
|
||||
// 硬性预算 如果实际发生金额小于 应(总天数/实际天数)发生金额
|
||||
// 直接取应发生金额(为了预算的准确性)
|
||||
if (budget.IsMandatoryExpense && currentAmount == 0)
|
||||
{
|
||||
currentAmount = budget.Limit / DateTime.DaysInMonth(year, month) * dateTimeProvider.Now.Day;
|
||||
}
|
||||
|
||||
if (budget.Category == BudgetCategory.Income)
|
||||
{
|
||||
monthlyIncomeItems.Add((
|
||||
name: budget.Name,
|
||||
limit: budget.Limit,
|
||||
current: currentAmount,
|
||||
isMandatory: budget.IsMandatoryExpense
|
||||
));
|
||||
}
|
||||
else if (budget.Category == BudgetCategory.Expense)
|
||||
{
|
||||
monthlyExpenseItems.Add((
|
||||
name: budget.Name,
|
||||
limit: budget.Limit,
|
||||
current: currentAmount,
|
||||
isMandatory: budget.IsMandatoryExpense
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
var yearlyIncomeItems = new List<(string name, decimal limit, decimal current)>();
|
||||
var yearlyExpenseItems = new List<(string name, decimal limit, decimal current)>();
|
||||
var yearlyBudgets = budgets
|
||||
.Where(b => b.Type == BudgetPeriodType.Year);
|
||||
// 只需要考虑实际发生在本月的年度预算 因为他会影响到月度的结余情况
|
||||
foreach (var budget in yearlyBudgets)
|
||||
{
|
||||
var classifyList = budget.SelectedCategories.Split(',', StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
decimal currentAmount = 0;
|
||||
var transactionType = budget.Category switch
|
||||
{
|
||||
BudgetCategory.Income => TransactionType.Income,
|
||||
BudgetCategory.Expense => TransactionType.Expense,
|
||||
_ => throw new NotSupportedException($"Budget category {budget.Category} is not supported.")
|
||||
};
|
||||
|
||||
foreach (var classify in classifyList)
|
||||
{
|
||||
// 获取分类+收入支出类型一致的金额
|
||||
if (transactionClassify.TryGetValue((classify, transactionType), out var amount))
|
||||
{
|
||||
currentAmount += amount;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentAmount == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (budget.Category == BudgetCategory.Income)
|
||||
{
|
||||
yearlyIncomeItems.Add((
|
||||
name: budget.Name,
|
||||
limit: budget.Limit,
|
||||
current: currentAmount
|
||||
));
|
||||
}
|
||||
else if (budget.Category == BudgetCategory.Expense)
|
||||
{
|
||||
yearlyExpenseItems.Add((
|
||||
name: budget.Name,
|
||||
limit: budget.Limit,
|
||||
current: currentAmount
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
var description = new StringBuilder();
|
||||
|
||||
#region 构建月度收入支出明细表格
|
||||
description.AppendLine("<h3>月度预算收入明细</h3>");
|
||||
description.AppendLine("""
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>预算</th>
|
||||
<th>硬性收入</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
""");
|
||||
|
||||
foreach (var item in monthlyIncomeItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{item.name}</td>
|
||||
<td>{item.limit:N0}</td>
|
||||
<td>{(item.isMandatory ? "是" : "否")}</td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
|
||||
description.AppendLine("</tbody></table>");
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
收入合计:
|
||||
<span class='income-value'>
|
||||
<strong>{monthlyIncomeItems.Sum(item => item.limit):N0}</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
|
||||
description.AppendLine("<h3>月度预算支出明细</h3>");
|
||||
description.AppendLine("""
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>预算</th>
|
||||
<th>硬性支出</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
""");
|
||||
foreach (var item in monthlyExpenseItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{item.name}</td>
|
||||
<td>{item.limit:N0}</td>
|
||||
<td>{(item.isMandatory ? "是" : "否")}</td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
description.AppendLine("</tbody></table>");
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
支出合计:
|
||||
<span class='expense-value'>
|
||||
<strong>{monthlyExpenseItems.Sum(item => item.limit):N0}</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
#endregion
|
||||
|
||||
#region 构建发生在本月的年度预算收入支出明细表格
|
||||
if (yearlyIncomeItems.Any())
|
||||
{
|
||||
description.AppendLine("<h3>年度收入预算(发生在本月)</h3>");
|
||||
description.AppendLine("""
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>预算</th>
|
||||
<th>本月收入</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
""");
|
||||
|
||||
foreach (var item in yearlyIncomeItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{item.name}</td>
|
||||
<td>{(item.limit == 0 ? "不限额" : item.limit.ToString("N0"))}</td>
|
||||
<td><span class='income-value'>{item.current:N0}</span></td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
|
||||
description.AppendLine("</tbody></table>");
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
收入合计:
|
||||
<span class='income-value'>
|
||||
<strong>{yearlyIncomeItems.Sum(item => item.current):N0}</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
}
|
||||
|
||||
if (yearlyExpenseItems.Any())
|
||||
{
|
||||
description.AppendLine("<h3>年度支出预算(发生在本月)</h3>");
|
||||
description.AppendLine("""
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>预算</th>
|
||||
<th>本月支出</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
""");
|
||||
foreach (var item in yearlyExpenseItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{item.name}</td>
|
||||
<td>{(item.limit == 0 ? "不限额" : item.limit.ToString("N0"))}</td>
|
||||
<td><span class='expense-value'>{item.current:N0}</span></td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
description.AppendLine("</tbody></table>");
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
支出合计:
|
||||
<span class='expense-value'>
|
||||
<strong>{yearlyExpenseItems.Sum(item => item.current):N0}</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 总结
|
||||
|
||||
description.AppendLine("<h3>存款计划结论</h3>");
|
||||
var plannedIncome = monthlyIncomeItems.Sum(item => item.limit == 0 ? item.current : item.limit) + yearlyIncomeItems.Sum(item => item.current);
|
||||
var plannedExpense = monthlyExpenseItems.Sum(item => item.limit == 0 ? item.current : item.limit) + yearlyExpenseItems.Sum(item => item.current);
|
||||
var expectedSavings = plannedIncome - plannedExpense;
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
计划存款:
|
||||
<span class='income-value'>
|
||||
<strong>{expectedSavings:N0}</strong>
|
||||
</span>
|
||||
=
|
||||
</p>
|
||||
<p>
|
||||
|
||||
计划收入:
|
||||
<span class='income-value'>
|
||||
<strong>{monthlyIncomeItems.Sum(item => item.limit):N0}</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
if (yearlyIncomeItems.Count > 0)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
|
||||
+ 本月发生的年度预算收入:
|
||||
<span class='income-value'>
|
||||
<strong>{yearlyIncomeItems.Sum(item => item.current):N0}</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
}
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
|
||||
- 计划支出:
|
||||
<span class='expense-value'>
|
||||
<strong>{monthlyExpenseItems.Sum(item => item.limit):N0}</strong>
|
||||
</span>
|
||||
""");
|
||||
if (yearlyExpenseItems.Count > 0)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
|
||||
- 本月发生的年度预算支出:
|
||||
<span class='expense-value'>
|
||||
<strong>{yearlyExpenseItems.Sum(item => item.current):N0}</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
}
|
||||
description.AppendLine($"""
|
||||
</p>
|
||||
""");
|
||||
#endregion
|
||||
|
||||
var savingsCategories = await configService.GetConfigByKeyAsync<string>("SavingsCategories") ?? string.Empty;
|
||||
var currentActual = 0m;
|
||||
if (!string.IsNullOrEmpty(savingsCategories))
|
||||
{
|
||||
var cats = new HashSet<string>(savingsCategories.Split(',', StringSplitOptions.RemoveEmptyEntries));
|
||||
foreach (var kvp in transactionClassify)
|
||||
{
|
||||
if (cats.Contains(kvp.Key.Item1))
|
||||
{
|
||||
currentActual += kvp.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var record = new BudgetRecord
|
||||
{
|
||||
Id = -2,
|
||||
Name = "月度存款计划",
|
||||
Type = BudgetPeriodType.Month,
|
||||
Limit = expectedSavings,
|
||||
Category = BudgetCategory.Savings,
|
||||
SelectedCategories = savingsCategories,
|
||||
StartDate = new DateTime(year, month, 1),
|
||||
NoLimit = false,
|
||||
IsMandatoryExpense = false,
|
||||
CreateTime = dateTimeProvider.Now,
|
||||
UpdateTime = dateTimeProvider.Now
|
||||
};
|
||||
|
||||
return BudgetResult.FromEntity(
|
||||
record,
|
||||
currentActual,
|
||||
new DateTime(year, month, 1),
|
||||
description.ToString()
|
||||
);
|
||||
}
|
||||
|
||||
private async Task<BudgetResult> GetForYearAsync(
|
||||
IEnumerable<BudgetRecord> budgets,
|
||||
int year)
|
||||
{
|
||||
// 因为非当前月份的读取归档数据,这边依然是读取当前月份的数据
|
||||
var currentMonth = dateTimeProvider.Now.Month;
|
||||
var transactionClassify = await transactionStatisticsService.GetAmountGroupByClassifyAsync(
|
||||
new DateTime(year, currentMonth, 1),
|
||||
new DateTime(year, currentMonth, 1).AddMonths(1)
|
||||
);
|
||||
|
||||
var currentMonthlyIncomeItems = new List<(long id, string name, decimal limit, int factor, decimal current, bool isMandatory)>();
|
||||
var currentYearlyIncomeItems = new List<(long id, string name, decimal limit, int factor, decimal current, bool isMandatory)>();
|
||||
var currentMonthlyExpenseItems = new List<(long id, string name, decimal limit, int factor, decimal current, bool isMandatory)>();
|
||||
var currentYearlyExpenseItems = new List<(long id, string name, decimal limit, int factor, decimal current, bool isMandatory)>();
|
||||
// 归档的预算收入支出明细
|
||||
var archiveIncomeItems = new List<(long id, string name, int[] months, decimal limit, decimal current)>();
|
||||
var archiveExpenseItems = new List<(long id, string name, int[] months, decimal limit, decimal current)>();
|
||||
var archiveSavingsItems = new List<(long id, string name, int[] months, decimal limit, decimal current)>();
|
||||
// 获取归档数据
|
||||
var archives = await budgetArchiveRepository.GetArchivesByYearAsync(year);
|
||||
var archiveBudgetGroups = archives
|
||||
.SelectMany(a => a.Content.Select(x => (a.Month, Archive: x)))
|
||||
.Where(b => b.Archive.Type == BudgetPeriodType.Month) // 因为本来就是当前年度预算的生成 ,归档无需关心年度, 以最新地为准即可
|
||||
.GroupBy(b => (b.Archive.Id, b.Archive.Limit));
|
||||
|
||||
foreach (var archiveBudgetGroup in archiveBudgetGroups)
|
||||
{
|
||||
var (_, archive) = archiveBudgetGroup.First();
|
||||
var archiveItems = archive.Category switch
|
||||
{
|
||||
BudgetCategory.Income => archiveIncomeItems,
|
||||
BudgetCategory.Expense => archiveExpenseItems,
|
||||
BudgetCategory.Savings => archiveSavingsItems,
|
||||
_ => throw new NotSupportedException($"Category {archive.Category} is not supported.")
|
||||
};
|
||||
|
||||
archiveItems.Add((
|
||||
id: archiveBudgetGroup.Key.Id,
|
||||
name: archive.Name,
|
||||
months: archiveBudgetGroup.Select(x => x.Month).OrderBy(m => m).ToArray(),
|
||||
limit: archiveBudgetGroup.Key.Limit,
|
||||
current: archiveBudgetGroup.Sum(x => x.Archive.Actual)
|
||||
));
|
||||
}
|
||||
|
||||
// 处理当月最新地没有归档的预算
|
||||
foreach (var budget in budgets)
|
||||
{
|
||||
var currentAmount = 0m;
|
||||
|
||||
var classifyList = budget.SelectedCategories.Split(',', StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
var transactionType = budget.Category switch
|
||||
{
|
||||
BudgetCategory.Income => TransactionType.Income,
|
||||
BudgetCategory.Expense => TransactionType.Expense,
|
||||
_ => throw new NotSupportedException($"Budget category {budget.Category} is not supported.")
|
||||
};
|
||||
|
||||
foreach (var classify in classifyList)
|
||||
{
|
||||
// 获取分类+收入支出类型一致的金额
|
||||
if (transactionClassify.TryGetValue((classify, transactionType), out var amount))
|
||||
{
|
||||
currentAmount += amount;
|
||||
}
|
||||
}
|
||||
|
||||
// 硬性预算 如果实际发生金额小于 应(总天数/实际天数)发生金额
|
||||
// 直接取应发生金额(为了预算的准确性)
|
||||
if (budget.IsMandatoryExpense && currentAmount == 0)
|
||||
{
|
||||
currentAmount = budget.IsMandatoryExpense && currentAmount == 0
|
||||
? budget.Limit / (DateTime.IsLeapYear(year) ? 366 : 365) * dateTimeProvider.Now.DayOfYear
|
||||
: budget.Limit / DateTime.DaysInMonth(year, currentMonth) * dateTimeProvider.Now.Day;
|
||||
}
|
||||
|
||||
AddOrIncCurrentItem(
|
||||
budget.Id,
|
||||
budget.Type,
|
||||
budget.Category,
|
||||
budget.Name,
|
||||
budget.Limit,
|
||||
budget.Type == BudgetPeriodType.Year
|
||||
? 1
|
||||
: 12 - currentMonth + 1,
|
||||
currentAmount,
|
||||
budget.IsMandatoryExpense
|
||||
);
|
||||
}
|
||||
|
||||
var description = new StringBuilder();
|
||||
|
||||
#region 构建归档收入明细表格
|
||||
var archiveIncomeDiff = 0m;
|
||||
if (archiveIncomeItems.Any())
|
||||
{
|
||||
description.AppendLine("<h3>已归档收入明细</h3>");
|
||||
description.AppendLine("""
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>预算</th>
|
||||
<th>月</th>
|
||||
<th>合计</th>
|
||||
<th>实际</th>
|
||||
</tr>
|
||||
</thead>
|
||||
</tbody>
|
||||
""");
|
||||
// 已归档的收入
|
||||
foreach (var (_, name, months, limit, current) in archiveIncomeItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{name}</td>
|
||||
<td>{(limit == 0 ? "不限额" : limit.ToString("N0"))}</td>
|
||||
<td>{FormatMonths(months)}</td>
|
||||
<td>{limit * months.Length:N0}</td>
|
||||
<td><span class='income-value'>{current:N0}</span></td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
description.AppendLine("</tbody></table>");
|
||||
archiveIncomeDiff = archiveIncomeItems.Sum(i => i.current) - archiveIncomeItems.Sum(i => i.limit * i.months.Length);
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
<span class="highlight">已归档收入总结: </span>
|
||||
{(archiveIncomeDiff > 0 ? "超额收入" : "未达预期")}:
|
||||
<span class='{(archiveIncomeDiff > 0 ? "income-value" : "expense-value")}'>
|
||||
<strong>{archiveIncomeDiff:N0}</strong>
|
||||
</span>
|
||||
=
|
||||
<span class='income-value'>
|
||||
<strong>{archiveIncomeItems.Sum(i => i.limit * i.months.Length):N0}</strong>
|
||||
</span>
|
||||
-
|
||||
实际收入合计:
|
||||
<span class='income-value'>
|
||||
<strong>{archiveIncomeItems.Sum(i => i.current):N0}</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 构建年度预算收入明细表格
|
||||
description.AppendLine("<h3>预算收入明细</h3>");
|
||||
description.AppendLine("""
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>预算</th>
|
||||
<th>月/年</th>
|
||||
<th>合计</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
""");
|
||||
|
||||
// 当前预算
|
||||
foreach (var (_, name, limit, factor, _, _) in currentMonthlyIncomeItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{name}</td>
|
||||
<td>{(limit == 0 ? "不限额" : limit.ToString("N0"))}</td>
|
||||
<td>{FormatMonthsByFactor(factor)}</td>
|
||||
<td>{(limit == 0 ? "不限额" : (limit * factor).ToString("N0"))}</td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
|
||||
// 年预算
|
||||
foreach (var (_, name, limit, _, _, _) in currentYearlyIncomeItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{name}</td>
|
||||
<td>{(limit == 0 ? "不限额" : limit.ToString("N0"))}</td>
|
||||
<td>{year}年</td>
|
||||
<td>{(limit == 0 ? "不限额" : limit.ToString("N0"))}</td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
description.AppendLine("</tbody></table>");
|
||||
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
预算收入合计:
|
||||
<span class='expense-value'>
|
||||
<strong>
|
||||
{currentMonthlyIncomeItems.Sum(i => i.limit * i.factor)
|
||||
+ currentYearlyIncomeItems.Sum(i => i.limit):N0}
|
||||
</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
#endregion
|
||||
|
||||
#region 构建年度归档支出明细表格
|
||||
var archiveExpenseDiff = 0m;
|
||||
if (archiveExpenseItems.Any())
|
||||
{
|
||||
description.AppendLine("<h3>已归档支出明细</h3>");
|
||||
description.AppendLine("""
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>预算</th>
|
||||
<th>月</th>
|
||||
<th>合计</th>
|
||||
<th>实际</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
""");
|
||||
|
||||
// 已归档的支出
|
||||
foreach (var (_, name, months, limit, current) in archiveExpenseItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{name}</td>
|
||||
<td>{(limit == 0 ? "不限额" : limit.ToString("N0"))}</td>
|
||||
<td>{FormatMonths(months)}</td>
|
||||
<td>{limit * months.Length:N0}</td>
|
||||
<td><span class='expense-value'>{current:N0}</span></td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
description.AppendLine("</tbody></table>");
|
||||
|
||||
archiveExpenseDiff = archiveExpenseItems.Sum(i => i.limit * i.months.Length) - archiveExpenseItems.Sum(i => i.current);
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
<span class="highlight">已归档支出总结: </span>
|
||||
{(archiveExpenseDiff > 0 ? "节省支出" : "超支")}:
|
||||
<span class='{(archiveExpenseDiff > 0 ? "income-value" : "expense-value")}'>
|
||||
<strong>{archiveExpenseDiff:N0}</strong>
|
||||
</span>
|
||||
=
|
||||
<span class='expense-value'>
|
||||
<strong>{archiveExpenseItems.Sum(i => i.limit * i.months.Length):N0}</strong>
|
||||
</span>
|
||||
- 实际支出合计:
|
||||
<span class='expense-value'>
|
||||
<strong>{archiveExpenseItems.Sum(i => i.current):N0}</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
}
|
||||
#endregion
|
||||
#region 构建归档存款明细表格
|
||||
var archiveSavingsDiff = 0m;
|
||||
if (archiveSavingsItems.Any())
|
||||
{
|
||||
description.AppendLine("<h3>已归档存款明细</h3>");
|
||||
description.AppendLine("""
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>预算</th>
|
||||
<th>月</th>
|
||||
<th>合计</th>
|
||||
<th>实际</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
""");
|
||||
|
||||
// 已归档的存款
|
||||
foreach (var (_, name, months, limit, current) in archiveSavingsItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{name}</td>
|
||||
<td>{(limit == 0 ? "不限额" : limit.ToString("N0"))}</td>
|
||||
<td>{FormatMonths(months)}</td>
|
||||
<td>{limit * months.Length:N0}</td>
|
||||
<td><span class='income-value'>{current:N0}</span></td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
description.AppendLine("</tbody></table>");
|
||||
|
||||
archiveSavingsDiff = archiveSavingsItems.Sum(i => i.current) - archiveSavingsItems.Sum(i => i.limit * i.months.Length);
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
<span class="highlight">已归档存款总结: </span>
|
||||
{(archiveSavingsDiff > 0 ? "超额存款" : "未达预期")}:
|
||||
<span class='{(archiveSavingsDiff > 0 ? "income-value" : "expense-value")}'>
|
||||
<strong>{archiveSavingsDiff:N0}</strong>
|
||||
</span>
|
||||
=
|
||||
实际存款合计:
|
||||
<span class='income-value'>
|
||||
<strong>{archiveSavingsItems.Sum(i => i.current):N0}</strong>
|
||||
</span>
|
||||
-
|
||||
预算存款合计:
|
||||
<span class='income-value'>
|
||||
<strong>{archiveSavingsItems.Sum(i => i.limit * i.months.Length):N0}</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
}
|
||||
#endregion
|
||||
#region 构建当前年度预算支出明细表格
|
||||
description.AppendLine("<h3>预算支出明细</h3>");
|
||||
description.AppendLine("""
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>预算</th>
|
||||
<th>月/年</th>
|
||||
<th>合计</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
""");
|
||||
|
||||
// 未来月预算
|
||||
foreach (var (_, name, limit, factor, _, _) in currentMonthlyExpenseItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{name}</td>
|
||||
<td>{(limit == 0 ? "不限额" : limit.ToString("N0"))}</td>
|
||||
<td>{FormatMonthsByFactor(factor)}</td>
|
||||
<td>{(limit == 0 ? "不限额" : (limit * factor).ToString("N0"))}</td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
|
||||
// 年预算
|
||||
foreach (var (_, name, limit, _, _, _) in currentYearlyExpenseItems)
|
||||
{
|
||||
description.AppendLine($"""
|
||||
<tr>
|
||||
<td>{name}</td>
|
||||
<td>{(limit == 0 ? "不限额" : limit.ToString("N0"))}</td>
|
||||
<td>{year}年</td>
|
||||
<td>{(limit == 0 ? "不限额" : limit.ToString("N0"))}</td>
|
||||
</tr>
|
||||
""");
|
||||
}
|
||||
description.AppendLine("</tbody></table>");
|
||||
|
||||
// 合计
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
支出预算合计:
|
||||
<span class='expense-value'>
|
||||
<strong>
|
||||
{currentMonthlyExpenseItems.Sum(i => i.limit * i.factor)
|
||||
+ currentYearlyExpenseItems.Sum(i => i.limit):N0}
|
||||
</strong>
|
||||
</span>
|
||||
</p>
|
||||
""");
|
||||
#endregion
|
||||
|
||||
#region 总结
|
||||
var archiveIncomeBudget = archiveIncomeItems.Sum(i => i.limit * i.months.Length);
|
||||
var archiveExpenseBudget = archiveExpenseItems.Sum(i => i.limit * i.months.Length);
|
||||
// 如果有归档存款数据,直接使用;否则用收入-支出计算
|
||||
var archiveSavings = archiveSavingsItems.Any()
|
||||
? archiveSavingsItems.Sum(i => i.current)
|
||||
: archiveIncomeBudget - archiveExpenseBudget + archiveIncomeDiff + archiveExpenseDiff;
|
||||
|
||||
var expectedIncome = currentMonthlyIncomeItems.Sum(i => i.limit == 0 ? i.current : i.limit * i.factor) + currentYearlyIncomeItems.Sum(i => i.isMandatory || i.limit == 0 ? i.current : i.limit);
|
||||
var expectedExpense = currentMonthlyExpenseItems.Sum(i => i.limit == 0 ? i.current : i.limit * i.factor) + currentYearlyExpenseItems.Sum(i => i.isMandatory || i.limit == 0 ? i.current : i.limit);
|
||||
var expectedSavings = expectedIncome - expectedExpense;
|
||||
|
||||
description.AppendLine("<h3>存款计划结论</h3>");
|
||||
description.AppendLine($"""
|
||||
<p>
|
||||
<strong>归档存款:</strong>
|
||||
<span class='income-value'><strong>{archiveSavings:N0}</strong></span>
|
||||
=
|
||||
归档收入: <span class='income-value'>{archiveIncomeBudget:N0}</span>
|
||||
-
|
||||
归档支出: <span class='expense-value'>{archiveExpenseBudget:N0}</span>
|
||||
{(archiveIncomeDiff >= 0 ? " + 超额收入" : " - 未达预期收入")}: <span class='{(archiveIncomeDiff >= 0 ? "income-value" : "expense-value")}'>{(archiveIncomeDiff >= 0 ? archiveIncomeDiff : -archiveIncomeDiff):N0}</span>
|
||||
{(archiveExpenseDiff >= 0 ? " + 节省支出" : " - 超额支出")}: <span class='{(archiveExpenseDiff >= 0 ? "income-value" : "expense-value")}'>{(archiveExpenseDiff >= 0 ? archiveExpenseDiff : -archiveExpenseDiff):N0}</span>
|
||||
</p>
|
||||
<p>
|
||||
<strong>预计存款:</strong>
|
||||
<span class='income-value'><strong>{expectedSavings:N0}</strong></span>
|
||||
=
|
||||
预计收入: <span class='income-value'>{expectedIncome:N0}</span>
|
||||
-
|
||||
预计支出: <span class='expense-value'>{expectedExpense:N0}</span>
|
||||
</p>
|
||||
<p>
|
||||
<strong>存档总结:</strong>
|
||||
<span class='{(archiveSavings + expectedSavings > 0 ? "income-value" : "expense-value")}'>
|
||||
<strong>{archiveSavings + expectedSavings:N0}</strong>
|
||||
</span>
|
||||
=
|
||||
预计存款:
|
||||
<span class='income-value'>{expectedSavings:N0}</span>
|
||||
{(archiveSavings > 0 ? "+" : "-")}
|
||||
归档存款:
|
||||
<span class='{(archiveSavings > 0 ? "income-value" : "expense-value")}'>{Math.Abs(archiveSavings):N0}</span>
|
||||
</p>
|
||||
""");
|
||||
#endregion
|
||||
|
||||
var savingsCategories = await configService.GetConfigByKeyAsync<string>("SavingsCategories") ?? string.Empty;
|
||||
|
||||
var currentActual = 0m;
|
||||
if (!string.IsNullOrEmpty(savingsCategories))
|
||||
{
|
||||
var cats = new HashSet<string>(savingsCategories.Split(',', StringSplitOptions.RemoveEmptyEntries));
|
||||
foreach (var kvp in transactionClassify)
|
||||
{
|
||||
if (cats.Contains(kvp.Key.Item1))
|
||||
{
|
||||
currentActual += kvp.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var record = new BudgetRecord
|
||||
{
|
||||
Id = -1,
|
||||
Name = "年度存款计划",
|
||||
Type = BudgetPeriodType.Year,
|
||||
Limit = archiveSavings + expectedSavings,
|
||||
Category = BudgetCategory.Savings,
|
||||
SelectedCategories = savingsCategories,
|
||||
StartDate = new DateTime(year, 1, 1),
|
||||
NoLimit = false,
|
||||
IsMandatoryExpense = false,
|
||||
CreateTime = dateTimeProvider.Now,
|
||||
UpdateTime = dateTimeProvider.Now
|
||||
};
|
||||
|
||||
return BudgetResult.FromEntity(
|
||||
record,
|
||||
currentActual,
|
||||
new DateTime(year, 1, 1),
|
||||
description.ToString()
|
||||
);
|
||||
|
||||
void AddOrIncCurrentItem(
|
||||
long id,
|
||||
BudgetPeriodType periodType,
|
||||
BudgetCategory category,
|
||||
string name,
|
||||
decimal limit,
|
||||
int factor,
|
||||
decimal incAmount,
|
||||
bool isMandatory)
|
||||
{
|
||||
var current = (periodType, category) switch
|
||||
{
|
||||
(BudgetPeriodType.Month, BudgetCategory.Income) => currentMonthlyIncomeItems,
|
||||
(BudgetPeriodType.Month, BudgetCategory.Expense) => currentMonthlyExpenseItems,
|
||||
(BudgetPeriodType.Year, BudgetCategory.Income) => currentYearlyIncomeItems,
|
||||
(BudgetPeriodType.Year, BudgetCategory.Expense) => currentYearlyExpenseItems,
|
||||
_ => throw new NotSupportedException($"Category {category} is not supported.")
|
||||
};
|
||||
|
||||
if (current.Any(i => i.id == id))
|
||||
{
|
||||
var existing = current.First(i => i.id == id);
|
||||
current.Remove(existing);
|
||||
current.Add((id, existing.name, existing.limit, existing.factor + factor, existing.current + incAmount, isMandatory));
|
||||
}
|
||||
else
|
||||
{
|
||||
current.Add((id, name, limit, factor, incAmount, isMandatory));
|
||||
}
|
||||
}
|
||||
|
||||
string FormatMonthsByFactor(int factor)
|
||||
{
|
||||
var months = factor == 12
|
||||
? Enumerable.Range(1, 12).ToArray()
|
||||
: Enumerable.Range(dateTimeProvider.Now.Month, factor).ToArray();
|
||||
|
||||
return FormatMonths(months.ToArray());
|
||||
}
|
||||
|
||||
string FormatMonths(int[] months)
|
||||
{
|
||||
// 如果是连续的月份 则简化显示 1~3
|
||||
Array.Sort(months);
|
||||
if (months.Length >= 2)
|
||||
{
|
||||
var isContinuous = true;
|
||||
for (var i = 1; i < months.Length; i++)
|
||||
{
|
||||
if (months[i] != months[i - 1] + 1)
|
||||
{
|
||||
isContinuous = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (isContinuous)
|
||||
{
|
||||
return $"{months.First()}~{months.Last()}月";
|
||||
}
|
||||
}
|
||||
|
||||
return string.Join(", ", months) + "月";
|
||||
}
|
||||
}
|
||||
}
|
||||
548
Service/Budget/BudgetService.cs
Normal file
548
Service/Budget/BudgetService.cs
Normal file
@@ -0,0 +1,548 @@
|
||||
using Service.AI;
|
||||
using Service.Message;
|
||||
using Service.Transaction;
|
||||
|
||||
namespace Service.Budget;
|
||||
|
||||
public interface IBudgetService
|
||||
{
|
||||
Task<List<BudgetResult>> GetListAsync(DateTime referenceDate);
|
||||
|
||||
Task<string> ArchiveBudgetsAsync(int year, int month);
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定分类的统计信息(月度和年度)
|
||||
/// </summary>
|
||||
Task<BudgetCategoryStats> GetCategoryStatsAsync(BudgetCategory category, DateTime referenceDate);
|
||||
|
||||
/// <summary>
|
||||
/// 获取未被预算覆盖的分类统计信息
|
||||
/// </summary>
|
||||
Task<List<UncoveredCategoryDetail>> GetUncoveredCategoriesAsync(BudgetCategory category, DateTime? referenceDate = null);
|
||||
|
||||
Task<string?> GetArchiveSummaryAsync(int year, int month);
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定周期的存款预算信息
|
||||
/// </summary>
|
||||
Task<BudgetResult?> GetSavingsBudgetAsync(int year, int month, BudgetPeriodType type);
|
||||
}
|
||||
|
||||
[UsedImplicitly]
|
||||
public class BudgetService(
|
||||
IBudgetRepository budgetRepository,
|
||||
IBudgetArchiveRepository budgetArchiveRepository,
|
||||
ITransactionRecordRepository transactionRecordRepository,
|
||||
ITransactionStatisticsService transactionStatisticsService,
|
||||
IOpenAiService openAiService,
|
||||
IMessageService messageService,
|
||||
ILogger<BudgetService> logger,
|
||||
IBudgetSavingsService budgetSavingsService,
|
||||
IDateTimeProvider dateTimeProvider,
|
||||
IBudgetStatsService budgetStatsService
|
||||
) : IBudgetService
|
||||
{
|
||||
public async Task<List<BudgetResult>> GetListAsync(DateTime referenceDate)
|
||||
{
|
||||
var year = referenceDate.Year;
|
||||
var month = referenceDate.Month;
|
||||
|
||||
var isArchive = year < dateTimeProvider.Now.Year
|
||||
|| (year == dateTimeProvider.Now.Year && month < dateTimeProvider.Now.Month);
|
||||
|
||||
if (isArchive)
|
||||
{
|
||||
var archive = await budgetArchiveRepository.GetArchiveAsync(year, month);
|
||||
|
||||
if (archive != null)
|
||||
{
|
||||
var (start, end) = GetPeriodRange(dateTimeProvider.Now, BudgetPeriodType.Month, referenceDate);
|
||||
return [.. archive.Content.Select(c => new BudgetResult
|
||||
{
|
||||
Id = c.Id,
|
||||
Name = c.Name,
|
||||
Type = c.Type,
|
||||
Limit = c.Limit,
|
||||
Current = c.Actual,
|
||||
Category = c.Category,
|
||||
SelectedCategories = c.SelectedCategories,
|
||||
NoLimit = c.NoLimit,
|
||||
IsMandatoryExpense = c.IsMandatoryExpense,
|
||||
Description = c.Description,
|
||||
PeriodStart = start,
|
||||
PeriodEnd = end,
|
||||
})];
|
||||
}
|
||||
|
||||
logger.LogWarning("获取预算列表时发现归档数据缺失,Year: {Year}, Month: {Month}", year, month);
|
||||
}
|
||||
|
||||
var budgets = await budgetRepository.GetAllAsync();
|
||||
var dtos = new List<BudgetResult?>();
|
||||
|
||||
foreach (var budget in budgets)
|
||||
{
|
||||
var currentAmount = await CalculateCurrentAmountAsync(budget, referenceDate);
|
||||
dtos.Add(BudgetResult.FromEntity(budget, currentAmount, referenceDate));
|
||||
}
|
||||
|
||||
// 创造虚拟的存款预算
|
||||
dtos.Add(await budgetSavingsService.GetSavingsDtoAsync(
|
||||
BudgetPeriodType.Month,
|
||||
referenceDate,
|
||||
budgets));
|
||||
dtos.Add(await budgetSavingsService.GetSavingsDtoAsync(
|
||||
BudgetPeriodType.Year,
|
||||
referenceDate,
|
||||
budgets));
|
||||
|
||||
dtos = dtos
|
||||
.Where(x => x != null)
|
||||
.Cast<BudgetResult>()
|
||||
.OrderByDescending(x => x.IsMandatoryExpense)
|
||||
.ThenBy(x => x.Type)
|
||||
.ThenByDescending(x => x.Current)
|
||||
.ToList()!;
|
||||
|
||||
return [.. dtos.Where(dto => dto != null).Cast<BudgetResult>()];
|
||||
}
|
||||
|
||||
public async Task<BudgetResult?> GetSavingsBudgetAsync(int year, int month, BudgetPeriodType type)
|
||||
{
|
||||
var referenceDate = new DateTime(year, month, 1);
|
||||
return await budgetSavingsService.GetSavingsDtoAsync(type, referenceDate);
|
||||
}
|
||||
|
||||
public async Task<BudgetCategoryStats> GetCategoryStatsAsync(BudgetCategory category, DateTime referenceDate)
|
||||
{
|
||||
return await budgetStatsService.GetCategoryStatsAsync(category, referenceDate);
|
||||
}
|
||||
|
||||
public async Task<List<UncoveredCategoryDetail>> GetUncoveredCategoriesAsync(BudgetCategory category, DateTime? referenceDate = null)
|
||||
{
|
||||
var date = referenceDate ?? dateTimeProvider.Now;
|
||||
var transactionType = category switch
|
||||
{
|
||||
BudgetCategory.Expense => TransactionType.Expense,
|
||||
BudgetCategory.Income => TransactionType.Income,
|
||||
_ => TransactionType.None
|
||||
};
|
||||
|
||||
if (transactionType == TransactionType.None) return [];
|
||||
|
||||
// 1. 获取所有预算
|
||||
var budgets = (await budgetRepository.GetAllAsync()).ToList();
|
||||
var coveredCategories = budgets
|
||||
.Where(b => b.Category == category)
|
||||
.SelectMany(b => b.SelectedCategories.Split(',', StringSplitOptions.RemoveEmptyEntries))
|
||||
.ToHashSet();
|
||||
|
||||
// 2. 获取分类统计
|
||||
var stats = await transactionStatisticsService.GetCategoryStatisticsAsync(date.Year, date.Month, transactionType);
|
||||
|
||||
// 3. 过滤未覆盖的
|
||||
return stats
|
||||
.Where(s => !coveredCategories.Contains(s.Classify))
|
||||
.Select(s => new UncoveredCategoryDetail
|
||||
{
|
||||
Category = s.Classify,
|
||||
TransactionCount = s.Count,
|
||||
TotalAmount = s.Amount
|
||||
})
|
||||
.OrderByDescending(x => x.TotalAmount)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public async Task<string?> GetArchiveSummaryAsync(int year, int month)
|
||||
{
|
||||
var archive = await budgetArchiveRepository.GetArchiveAsync(year, month);
|
||||
return archive?.Summary;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public async Task<string> ArchiveBudgetsAsync(int year, int month)
|
||||
{
|
||||
var referenceDate = new DateTime(year, month, 1);
|
||||
|
||||
var budgets = await GetListAsync(referenceDate);
|
||||
|
||||
var expenseSurplus = budgets
|
||||
.Where(b => b.Category == BudgetCategory.Expense && !b.NoLimit && b.Type == BudgetPeriodType.Month)
|
||||
.Sum(b => b.Limit - b.Current);
|
||||
|
||||
var incomeSurplus = budgets
|
||||
.Where(b => b.Category == BudgetCategory.Income && !b.NoLimit && b.Type == BudgetPeriodType.Month)
|
||||
.Sum(b => b.Current - b.Limit);
|
||||
|
||||
var content = budgets.Select(b => new BudgetArchiveContent
|
||||
{
|
||||
Id = b.Id,
|
||||
Name = b.Name,
|
||||
Type = b.Type,
|
||||
Limit = b.Limit,
|
||||
Actual = b.Current,
|
||||
Category = b.Category,
|
||||
SelectedCategories = b.SelectedCategories,
|
||||
NoLimit = b.NoLimit,
|
||||
IsMandatoryExpense = b.IsMandatoryExpense,
|
||||
Description = b.Description
|
||||
}).ToArray();
|
||||
|
||||
var archive = await budgetArchiveRepository.GetArchiveAsync(year, month);
|
||||
|
||||
if (archive != null)
|
||||
{
|
||||
archive.Content = content;
|
||||
archive.ArchiveDate = dateTimeProvider.Now;
|
||||
archive.ExpenseSurplus = expenseSurplus;
|
||||
archive.IncomeSurplus = incomeSurplus;
|
||||
if (!await budgetArchiveRepository.UpdateAsync(archive))
|
||||
{
|
||||
return "更新预算归档失败";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
archive = new BudgetArchive
|
||||
{
|
||||
Year = year,
|
||||
Month = month,
|
||||
Content = content,
|
||||
ArchiveDate = dateTimeProvider.Now,
|
||||
ExpenseSurplus = expenseSurplus,
|
||||
IncomeSurplus = incomeSurplus
|
||||
};
|
||||
|
||||
if (!await budgetArchiveRepository.AddAsync(archive))
|
||||
{
|
||||
return "保存预算归档失败";
|
||||
}
|
||||
}
|
||||
|
||||
_ = NotifyAsync(year, month);
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private async Task NotifyAsync(int year, int month)
|
||||
{
|
||||
try
|
||||
{
|
||||
var archives = await budgetArchiveRepository.GetListAsync(year, month);
|
||||
|
||||
var archiveData = archives.SelectMany(a => a.Content.Select(c => new
|
||||
{
|
||||
c.Name,
|
||||
Type = c.Type.ToString(),
|
||||
c.Limit,
|
||||
c.Actual,
|
||||
Category = c.Category.ToString(),
|
||||
c.SelectedCategories
|
||||
})).ToList();
|
||||
|
||||
var yearTransactions = await transactionRecordRepository.ExecuteDynamicSqlAsync(
|
||||
$"""
|
||||
SELECT
|
||||
COUNT(*) AS TransactionCount,
|
||||
SUM(ABS(Amount)) AS TotalAmount,
|
||||
Type,
|
||||
Classify
|
||||
FROM TransactionRecord
|
||||
WHERE OccurredAt >= '{year}-01-01'
|
||||
AND OccurredAt < '{year + 1}-01-01'
|
||||
GROUP BY Type, Classify
|
||||
ORDER BY TotalAmount DESC
|
||||
"""
|
||||
);
|
||||
var monthYear = new DateTime(year, month, 1).AddMonths(1);
|
||||
var monthTransactions = await transactionRecordRepository.ExecuteDynamicSqlAsync(
|
||||
$"""
|
||||
SELECT
|
||||
COUNT(*) AS TransactionCount,
|
||||
SUM(ABS(Amount)) AS TotalAmount,
|
||||
Type,
|
||||
Classify
|
||||
FROM TransactionRecord
|
||||
WHERE OccurredAt >= '{year}-{month:00}-01'
|
||||
AND OccurredAt < '{monthYear:yyyy-MM-dd}'
|
||||
GROUP BY Type, Classify
|
||||
ORDER BY TotalAmount DESC
|
||||
"""
|
||||
);
|
||||
|
||||
// 分析未被预算覆盖的分类 (仅针对支出类型 Type=0)
|
||||
var budgetedCategories = archiveData
|
||||
.SelectMany(b => b.SelectedCategories)
|
||||
.Where(c => !string.IsNullOrEmpty(c))
|
||||
.Distinct()
|
||||
.ToHashSet();
|
||||
|
||||
var uncovered = monthTransactions
|
||||
.Where(t =>
|
||||
{
|
||||
var dict = (IDictionary<string, object>)t;
|
||||
var classify = dict["Classify"].ToString() ?? "";
|
||||
var type = Convert.ToInt32(dict["Type"]);
|
||||
return type == 0 && !budgetedCategories.Contains(classify);
|
||||
})
|
||||
.ToList();
|
||||
|
||||
logger.LogInformation("预算执行数据{JSON}", JsonSerializer.Serialize(archiveData));
|
||||
logger.LogInformation("本月消费明细{JSON}", JsonSerializer.Serialize(monthTransactions));
|
||||
logger.LogInformation("全年累计消费概况{JSON}", JsonSerializer.Serialize(yearTransactions));
|
||||
logger.LogInformation("未被预算覆盖的分类{JSON}", JsonSerializer.Serialize(uncovered));
|
||||
|
||||
var dataPrompt = $"""
|
||||
报告周期:{year}年{month}月
|
||||
|
||||
1. 预算执行数据(JSON):
|
||||
{JsonSerializer.Serialize(archiveData)}
|
||||
|
||||
2. 本月账单类目明细(按分类, JSON):
|
||||
{JsonSerializer.Serialize(monthTransactions)}
|
||||
|
||||
3. 全年累计账单类目明细(按分类, JSON):
|
||||
{JsonSerializer.Serialize(yearTransactions)}
|
||||
|
||||
4. 未被任何预算覆盖的支出分类(JSON):
|
||||
{JsonSerializer.Serialize(uncovered)}
|
||||
|
||||
请生成一份专业且美观的预算执行分析报告,严格遵守以下要求:
|
||||
|
||||
【内容要求】
|
||||
1. 概览:总结本月预算达成情况。
|
||||
2. 预算详情:使用 HTML 表格展示预算执行明细(预算项、预算额、实际额、使用/达成率、状态)。
|
||||
3. 超支/异常预警:重点分析超支项或支出异常的分类。
|
||||
4. 消费透视:针对“未被预算覆盖的支出”提供分析建议。分析这些账单产生的合理性,并评估是否需要为其中的大额或频发分类建立新预算。
|
||||
5. 改进建议:根据当前时间进度和预算完成进度,基于本月整体收入支出情况,给出下月预算调整或消费改进的专业化建议。
|
||||
6. 语言风格:专业、清晰、简洁,适合财务报告阅读。
|
||||
7. 如果报告月份是12月,需要报告年度预算的执行情况。
|
||||
|
||||
【格式要求】
|
||||
1. 使用HTML格式(移动端H5页面风格)
|
||||
2. 生成清晰的报告标题(基于用户问题)
|
||||
3. 使用表格展示统计数据(table > thead/tbody > tr > th/td),
|
||||
3.1 table要求不能超过屏幕宽度,尽可能简洁明了,避免冗余信息
|
||||
3.2 预算金额精确到整数即可,实际金额精确到小数点后1位
|
||||
4. 使用合适的HTML标签:h2(标题)、h3(小节)、p(段落)、table(表格)、ul/li(列表)、strong(强调)
|
||||
5. 支出金额用 <span class='expense-value'>金额</span> 包裹
|
||||
6. 收入金额用 <span class='income-value'>金额</span> 包裹
|
||||
7. 重要结论用 <span class='highlight'>内容</span> 高亮
|
||||
|
||||
【样式限制(重要)】
|
||||
8. 不要包含 html、body、head 标签
|
||||
9. 不要使用任何 style 属性或 <style> 标签
|
||||
10. 不要设置 background、background-color、color 等样式属性
|
||||
11. 不要使用 div 包裹大段内容
|
||||
|
||||
【系统信息】
|
||||
当前时间:{dateTimeProvider.Now:yyyy-MM-dd HH:mm:ss}
|
||||
预算归档周期:{year}年{month}月
|
||||
|
||||
直接输出纯净 HTML 内容,不要带有 Markdown 代码块包裹。
|
||||
""";
|
||||
|
||||
var htmlReport = await openAiService.ChatAsync(dataPrompt);
|
||||
if (!string.IsNullOrEmpty(htmlReport))
|
||||
{
|
||||
await messageService.AddAsync(
|
||||
title: $"{year}年{month}月 - 预算归档报告",
|
||||
content: htmlReport,
|
||||
type: MessageType.Html,
|
||||
url: "/balance?tab=message");
|
||||
|
||||
// 同时保存到归档总结
|
||||
var first = archives.First();
|
||||
first.Summary = htmlReport;
|
||||
await budgetArchiveRepository.UpdateAsync(first);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "生成预算执行通知报告失败");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<decimal> CalculateCurrentAmountAsync(BudgetRecord budget, DateTime? now = null)
|
||||
{
|
||||
var referenceDate = now ?? dateTimeProvider.Now;
|
||||
var (startDate, endDate) = GetPeriodRange(budget.StartDate, budget.Type, referenceDate);
|
||||
|
||||
var actualAmount = await budgetRepository.GetCurrentAmountAsync(budget, startDate, endDate);
|
||||
|
||||
// 如果是硬性消费,且是当前年当前月,则根据经过的天数累加
|
||||
if (actualAmount == 0
|
||||
&& budget.IsMandatoryExpense
|
||||
&& referenceDate.Year == startDate.Year
|
||||
&& (budget.Type == BudgetPeriodType.Year || referenceDate.Month == startDate.Month))
|
||||
{
|
||||
if (budget.Type == BudgetPeriodType.Month)
|
||||
{
|
||||
// 计算本月的天数
|
||||
var daysInMonth = DateTime.DaysInMonth(referenceDate.Year, referenceDate.Month);
|
||||
// 计算当前已经过的天数(包括今天)
|
||||
var daysElapsed = referenceDate.Day;
|
||||
// 根据预算金额和经过天数计算应累加的金额
|
||||
var mandatoryAccumulation = budget.Limit * daysElapsed / daysInMonth;
|
||||
// 返回实际消费和硬性消费累加中的较大值
|
||||
return mandatoryAccumulation;
|
||||
}
|
||||
|
||||
if (budget.Type == BudgetPeriodType.Year)
|
||||
{
|
||||
// 计算本年的天数(考虑闰年)
|
||||
var daysInYear = DateTime.IsLeapYear(referenceDate.Year) ? 366 : 365;
|
||||
// 计算当前已经过的天数(包括今天)
|
||||
var daysElapsed = referenceDate.DayOfYear;
|
||||
// 根据预算金额和经过天数计算应累加的金额
|
||||
var mandatoryAccumulation = budget.Limit * daysElapsed / daysInYear;
|
||||
// 返回实际消费和硬性消费累加中的较大值
|
||||
return mandatoryAccumulation;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return actualAmount;
|
||||
}
|
||||
|
||||
internal static (DateTime start, DateTime end) GetPeriodRange(DateTime startDate, BudgetPeriodType type, DateTime referenceDate)
|
||||
{
|
||||
DateTime start;
|
||||
DateTime end;
|
||||
|
||||
if (type == BudgetPeriodType.Month)
|
||||
{
|
||||
start = new DateTime(referenceDate.Year, referenceDate.Month, 1);
|
||||
end = start.AddMonths(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);
|
||||
}
|
||||
else if (type == BudgetPeriodType.Year)
|
||||
{
|
||||
start = new DateTime(referenceDate.Year, 1, 1);
|
||||
end = new DateTime(referenceDate.Year, 12, 31).AddHours(23).AddMinutes(59).AddSeconds(59);
|
||||
}
|
||||
else
|
||||
{
|
||||
start = startDate;
|
||||
end = DateTime.MaxValue;
|
||||
}
|
||||
|
||||
return (start, end);
|
||||
}
|
||||
}
|
||||
|
||||
public record BudgetResult
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public BudgetPeriodType Type { get; set; }
|
||||
public decimal Limit { get; set; }
|
||||
public decimal Current { get; set; }
|
||||
public BudgetCategory Category { get; set; }
|
||||
public string[] SelectedCategories { get; set; } = [];
|
||||
public string StartDate { get; set; } = string.Empty;
|
||||
public string Period { get; set; } = string.Empty;
|
||||
public DateTime? PeriodStart { get; set; }
|
||||
public DateTime? PeriodEnd { get; set; }
|
||||
public bool NoLimit { get; set; }
|
||||
public bool IsMandatoryExpense { get; set; }
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
public static BudgetResult FromEntity(
|
||||
BudgetRecord entity,
|
||||
decimal currentAmount,
|
||||
DateTime referenceDate,
|
||||
string description = "")
|
||||
{
|
||||
var date = referenceDate;
|
||||
var (start, end) = BudgetService.GetPeriodRange(entity.StartDate, entity.Type, date);
|
||||
|
||||
return new BudgetResult
|
||||
{
|
||||
Id = entity.Id,
|
||||
Name = entity.Name,
|
||||
Type = entity.Type,
|
||||
Limit = entity.Limit,
|
||||
Current = currentAmount,
|
||||
Category = entity.Category,
|
||||
SelectedCategories = string.IsNullOrEmpty(entity.SelectedCategories)
|
||||
? []
|
||||
: entity.SelectedCategories.Split(','),
|
||||
StartDate = entity.StartDate.ToString("yyyy-MM-dd"),
|
||||
Period = entity.Type switch
|
||||
{
|
||||
BudgetPeriodType.Year => $"{start:yy}年",
|
||||
BudgetPeriodType.Month => $"{start:yy}年第{start.Month}月",
|
||||
_ => $"{start:yyyy-MM-dd} ~ {end:yyyy-MM-dd}"
|
||||
},
|
||||
PeriodStart = start,
|
||||
PeriodEnd = end,
|
||||
NoLimit = entity.NoLimit,
|
||||
IsMandatoryExpense = entity.IsMandatoryExpense,
|
||||
Description = description
|
||||
};
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 预算统计结果 DTO
|
||||
/// </summary>
|
||||
public class BudgetStatsDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 统计周期类型(Month/Year)
|
||||
/// </summary>
|
||||
public BudgetPeriodType PeriodType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 使用率百分比(0-100)
|
||||
/// </summary>
|
||||
public decimal Rate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 实际金额
|
||||
/// </summary>
|
||||
public decimal Current { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 目标/限额金额
|
||||
/// </summary>
|
||||
public decimal Limit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 预算项数量
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 每日/每月累计金额趋势(对应当前周期内的实际发生额累计值)
|
||||
/// </summary>
|
||||
public List<decimal?> Trend { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// HTML 格式的详细描述(罗列每个预算的额度和实际值及计算公式)
|
||||
/// </summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分类统计结果
|
||||
/// </summary>
|
||||
public class BudgetCategoryStats
|
||||
{
|
||||
/// <summary>
|
||||
/// 月度统计
|
||||
/// </summary>
|
||||
public BudgetStatsDto Month { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 年度统计
|
||||
/// </summary>
|
||||
public BudgetStatsDto Year { get; set; } = new();
|
||||
}
|
||||
|
||||
public class UncoveredCategoryDetail
|
||||
{
|
||||
public string Category { get; set; } = string.Empty;
|
||||
public int TransactionCount { get; set; }
|
||||
public decimal TotalAmount { get; set; }
|
||||
}
|
||||
1295
Service/Budget/BudgetStatsService.cs
Normal file
1295
Service/Budget/BudgetStatsService.cs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,728 +0,0 @@
|
||||
namespace Service;
|
||||
|
||||
public interface IBudgetService
|
||||
{
|
||||
Task<List<BudgetResult>> GetListAsync(DateTime? referenceDate = null);
|
||||
|
||||
Task<BudgetResult?> GetStatisticsAsync(long id, DateTime referenceDate);
|
||||
|
||||
Task<string> ArchiveBudgetsAsync(int year, int month);
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定分类的统计信息(月度和年度)
|
||||
/// </summary>
|
||||
Task<BudgetCategoryStats> GetCategoryStatsAsync(BudgetCategory category, DateTime? referenceDate = null);
|
||||
|
||||
/// <summary>
|
||||
/// 获取未被预算覆盖的分类统计信息
|
||||
/// </summary>
|
||||
Task<List<UncoveredCategoryDetail>> GetUncoveredCategoriesAsync(BudgetCategory category, DateTime? referenceDate = null);
|
||||
}
|
||||
|
||||
public class BudgetService(
|
||||
IBudgetRepository budgetRepository,
|
||||
IBudgetArchiveRepository budgetArchiveRepository,
|
||||
ITransactionRecordRepository transactionRecordRepository,
|
||||
IOpenAiService openAiService,
|
||||
IConfigService configService,
|
||||
IMessageService messageService,
|
||||
ILogger<BudgetService> logger
|
||||
) : IBudgetService
|
||||
{
|
||||
public async Task<List<BudgetResult>> GetListAsync(DateTime? referenceDate = null)
|
||||
{
|
||||
var budgets = await budgetRepository.GetAllAsync();
|
||||
var dtos = new List<BudgetResult?>();
|
||||
|
||||
foreach (var budget in budgets)
|
||||
{
|
||||
var currentAmount = await CalculateCurrentAmountAsync(budget, referenceDate);
|
||||
dtos.Add(BudgetResult.FromEntity(budget, currentAmount, referenceDate));
|
||||
}
|
||||
|
||||
// 创造虚拟的存款预算
|
||||
dtos.Add(await GetVirtualSavingsDtoAsync(
|
||||
BudgetPeriodType.Month,
|
||||
referenceDate,
|
||||
budgets));
|
||||
dtos.Add(await GetVirtualSavingsDtoAsync(
|
||||
BudgetPeriodType.Year,
|
||||
referenceDate,
|
||||
budgets));
|
||||
|
||||
return dtos.Where(dto => dto != null).Cast<BudgetResult>().ToList();
|
||||
}
|
||||
|
||||
public async Task<BudgetResult?> GetStatisticsAsync(long id, DateTime referenceDate)
|
||||
{
|
||||
bool isArchive = false;
|
||||
BudgetRecord? budget = null;
|
||||
if (id == -1)
|
||||
{
|
||||
if (isAcrhiveFunc(BudgetPeriodType.Year))
|
||||
{
|
||||
isArchive = true;
|
||||
budget = await BuildVirtualSavingsBudgetRecordAsync(-1, referenceDate, 0);
|
||||
}
|
||||
|
||||
}
|
||||
else if (id == -2)
|
||||
{
|
||||
if (isAcrhiveFunc(BudgetPeriodType.Month))
|
||||
{
|
||||
isArchive = true;
|
||||
budget = await BuildVirtualSavingsBudgetRecordAsync(-2, referenceDate, 0);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
budget = await budgetRepository.GetByIdAsync(id);
|
||||
|
||||
if (budget == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
isArchive = isAcrhiveFunc(budget.Type);
|
||||
}
|
||||
|
||||
if (isArchive && budget != null)
|
||||
{
|
||||
var archive = await budgetArchiveRepository.GetArchiveAsync(
|
||||
id,
|
||||
referenceDate.Year,
|
||||
referenceDate.Month);
|
||||
|
||||
if (archive != null) // 存在归档 直接读取归档数据
|
||||
{
|
||||
budget.Limit = archive.BudgetedAmount;
|
||||
return BudgetResult.FromEntity(
|
||||
budget,
|
||||
archive.RealizedAmount,
|
||||
referenceDate,
|
||||
archive.Description ?? string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (id == -1)
|
||||
{
|
||||
return await GetVirtualSavingsDtoAsync(BudgetPeriodType.Year, referenceDate);
|
||||
}
|
||||
if (id == -2)
|
||||
{
|
||||
return await GetVirtualSavingsDtoAsync(BudgetPeriodType.Month, referenceDate);
|
||||
}
|
||||
|
||||
budget = await budgetRepository.GetByIdAsync(id);
|
||||
if (budget == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var currentAmount = await CalculateCurrentAmountAsync(budget, referenceDate);
|
||||
return BudgetResult.FromEntity(budget, currentAmount, referenceDate);
|
||||
|
||||
bool isAcrhiveFunc(BudgetPeriodType periodType)
|
||||
{
|
||||
if (periodType == BudgetPeriodType.Year)
|
||||
{
|
||||
return DateTime.Now.Year > referenceDate.Year;
|
||||
}
|
||||
else if (periodType == BudgetPeriodType.Month)
|
||||
{
|
||||
return DateTime.Now.Year > referenceDate.Year
|
||||
|| (DateTime.Now.Year == referenceDate.Year
|
||||
&& DateTime.Now.Month > referenceDate.Month);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<BudgetCategoryStats> GetCategoryStatsAsync(BudgetCategory category, DateTime? referenceDate = null)
|
||||
{
|
||||
var budgets = (await budgetRepository.GetAllAsync()).ToList();
|
||||
var refDate = referenceDate ?? DateTime.Now;
|
||||
|
||||
var result = new BudgetCategoryStats();
|
||||
|
||||
// 获取月度统计
|
||||
result.Month = await CalculateCategoryStatsAsync(budgets, category, BudgetPeriodType.Month, refDate);
|
||||
|
||||
// 获取年度统计
|
||||
result.Year = await CalculateCategoryStatsAsync(budgets, category, BudgetPeriodType.Year, refDate);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<List<UncoveredCategoryDetail>> GetUncoveredCategoriesAsync(BudgetCategory category, DateTime? referenceDate = null)
|
||||
{
|
||||
var date = referenceDate ?? DateTime.Now;
|
||||
var transactionType = category switch
|
||||
{
|
||||
BudgetCategory.Expense => TransactionType.Expense,
|
||||
BudgetCategory.Income => TransactionType.Income,
|
||||
_ => TransactionType.None
|
||||
};
|
||||
|
||||
if (transactionType == TransactionType.None) return new List<UncoveredCategoryDetail>();
|
||||
|
||||
// 1. 获取所有预算
|
||||
var budgets = (await budgetRepository.GetAllAsync()).ToList();
|
||||
var coveredCategories = budgets
|
||||
.Where(b => b.Category == category)
|
||||
.SelectMany(b => b.SelectedCategories.Split(',', StringSplitOptions.RemoveEmptyEntries))
|
||||
.ToHashSet();
|
||||
|
||||
// 2. 获取分类统计
|
||||
var stats = await transactionRecordRepository.GetCategoryStatisticsAsync(date.Year, date.Month, transactionType);
|
||||
|
||||
// 3. 过滤未覆盖的
|
||||
return stats
|
||||
.Where(s => !coveredCategories.Contains(s.Classify))
|
||||
.Select(s => new UncoveredCategoryDetail
|
||||
{
|
||||
Category = s.Classify,
|
||||
TransactionCount = s.Count,
|
||||
TotalAmount = s.Amount
|
||||
})
|
||||
.OrderByDescending(x => x.TotalAmount)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private async Task<BudgetStatsDto> CalculateCategoryStatsAsync(
|
||||
List<BudgetRecord> budgets,
|
||||
BudgetCategory category,
|
||||
BudgetPeriodType statType,
|
||||
DateTime referenceDate)
|
||||
{
|
||||
var result = new BudgetStatsDto
|
||||
{
|
||||
PeriodType = statType,
|
||||
Rate = 0,
|
||||
Current = 0,
|
||||
Limit = 0,
|
||||
Count = 0
|
||||
};
|
||||
|
||||
// 获取当前分类下所有预算
|
||||
var relevant = budgets
|
||||
.Where(b => b.Category == category)
|
||||
.ToList();
|
||||
|
||||
if (relevant.Count == 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
result.Count = relevant.Count;
|
||||
decimal totalCurrent = 0;
|
||||
decimal totalLimit = 0;
|
||||
|
||||
foreach (var budget in relevant)
|
||||
{
|
||||
// 限额折算
|
||||
var itemLimit = budget.Limit;
|
||||
if (statType == BudgetPeriodType.Month && budget.Type == BudgetPeriodType.Year)
|
||||
{
|
||||
// 月度视图下,年度预算不参与限额计算
|
||||
itemLimit = 0;
|
||||
}
|
||||
else if (statType == BudgetPeriodType.Year && budget.Type == BudgetPeriodType.Month)
|
||||
{
|
||||
// 年度视图下,月度预算折算为年度
|
||||
itemLimit = budget.Limit * 12;
|
||||
}
|
||||
totalLimit += itemLimit;
|
||||
|
||||
// 当前值累加
|
||||
var currentAmount = await CalculateCurrentAmountAsync(budget, referenceDate);
|
||||
if (budget.Type == statType)
|
||||
{
|
||||
totalCurrent += currentAmount;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 如果周期不匹配
|
||||
if (statType == BudgetPeriodType.Year && budget.Type == BudgetPeriodType.Month)
|
||||
{
|
||||
// 在年度视图下,月度预算计入其当前值(作为对年度目前的贡献)
|
||||
totalCurrent += currentAmount;
|
||||
}
|
||||
// 月度视图下,年度预算的 current 不计入
|
||||
}
|
||||
}
|
||||
|
||||
result.Limit = totalLimit;
|
||||
result.Current = totalCurrent;
|
||||
result.Rate = totalLimit > 0 ? totalCurrent / totalLimit * 100 : 0;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<string> ArchiveBudgetsAsync(int year, int month)
|
||||
{
|
||||
var referenceDate = new DateTime(year, month, 1);
|
||||
var budgets = await GetListAsync(referenceDate);
|
||||
|
||||
var addArchives = new List<BudgetArchive>();
|
||||
var updateArchives = new List<BudgetArchive>();
|
||||
foreach (var budget in budgets)
|
||||
{
|
||||
var archive = await budgetArchiveRepository.GetArchiveAsync(budget.Id, year, month);
|
||||
|
||||
if (archive != null)
|
||||
{
|
||||
archive.RealizedAmount = budget.Current;
|
||||
archive.ArchiveDate = DateTime.Now;
|
||||
archive.Description = budget.Description;
|
||||
updateArchives.Add(archive);
|
||||
}
|
||||
else
|
||||
{
|
||||
archive = new BudgetArchive
|
||||
{
|
||||
BudgetId = budget.Id,
|
||||
BudgetType = budget.Type,
|
||||
Year = year,
|
||||
Month = month,
|
||||
BudgetedAmount = budget.Limit,
|
||||
RealizedAmount = budget.Current,
|
||||
Description = budget.Description,
|
||||
ArchiveDate = DateTime.Now
|
||||
};
|
||||
|
||||
addArchives.Add(archive);
|
||||
}
|
||||
}
|
||||
|
||||
if (addArchives.Count > 0)
|
||||
{
|
||||
if (!await budgetArchiveRepository.AddRangeAsync(addArchives))
|
||||
{
|
||||
return "保存预算归档失败";
|
||||
}
|
||||
}
|
||||
if (updateArchives.Count > 0)
|
||||
{
|
||||
if (!await budgetArchiveRepository.UpdateRangeAsync(updateArchives))
|
||||
{
|
||||
return "更新预算归档失败";
|
||||
}
|
||||
}
|
||||
|
||||
_ = NotifyAsync(year, month);
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private async Task NotifyAsync(int year, int month)
|
||||
{
|
||||
try
|
||||
{
|
||||
var archives = await budgetArchiveRepository.GetListAsync(year, month);
|
||||
var budgets = await budgetRepository.GetAllAsync();
|
||||
var budgetMap = budgets.ToDictionary(b => b.Id, b => b);
|
||||
|
||||
var archiveData = archives.Select(a =>
|
||||
{
|
||||
budgetMap.TryGetValue(a.BudgetId, out var br);
|
||||
var name = br?.Name ?? (a.BudgetId == -1 ? "年度存款" : a.BudgetId == -2 ? "月度存款" : "未知");
|
||||
return new
|
||||
{
|
||||
Name = name,
|
||||
Type = a.BudgetType.ToString(),
|
||||
Limit = a.BudgetedAmount,
|
||||
Actual = a.RealizedAmount,
|
||||
Category = br?.Category.ToString() ?? (a.BudgetId < 0 ? "Savings" : "Unknown")
|
||||
};
|
||||
}).ToList();
|
||||
|
||||
var yearTransactions = await transactionRecordRepository.ExecuteDynamicSqlAsync(
|
||||
$"""
|
||||
SELECT
|
||||
COUNT(*) AS TransactionCount,
|
||||
SUM(ABS(Amount)) AS TotalAmount,
|
||||
Type,
|
||||
Classify
|
||||
FROM TransactionRecord
|
||||
WHERE OccurredAt >= '{year}-01-01'
|
||||
AND OccurredAt < '{year + 1}-01-01'
|
||||
GROUP BY Type, Classify
|
||||
ORDER BY TotalAmount DESC
|
||||
"""
|
||||
);
|
||||
var monthYear = new DateTime(year, month, 1).AddMonths(1);
|
||||
var monthTransactions = await transactionRecordRepository.ExecuteDynamicSqlAsync(
|
||||
$"""
|
||||
SELECT
|
||||
COUNT(*) AS TransactionCount,
|
||||
SUM(ABS(Amount)) AS TotalAmount,
|
||||
Type,
|
||||
Classify
|
||||
FROM TransactionRecord
|
||||
WHERE OccurredAt >= '{year}-{month:00}-01'
|
||||
AND OccurredAt < '{monthYear:yyyy-MM-dd}'
|
||||
GROUP BY Type, Classify
|
||||
ORDER BY TotalAmount DESC
|
||||
"""
|
||||
);
|
||||
|
||||
// 分析未被预算覆盖的分类 (仅针对支出类型 Type=0)
|
||||
var budgetedCategories = budgets
|
||||
.Where(b => !string.IsNullOrEmpty(b.SelectedCategories))
|
||||
.SelectMany(b => b.SelectedCategories.Split(','))
|
||||
.Distinct()
|
||||
.ToHashSet();
|
||||
|
||||
var uncovered = monthTransactions
|
||||
.Where(t =>
|
||||
{
|
||||
var dict = (IDictionary<string, object>)t;
|
||||
var classify = dict["Classify"]?.ToString() ?? "";
|
||||
var type = Convert.ToInt32(dict["Type"]);
|
||||
return type == 0 && !budgetedCategories.Contains(classify);
|
||||
})
|
||||
.ToList();
|
||||
|
||||
logger.LogInformation("预算执行数据{JSON}", JsonSerializer.Serialize(archiveData));
|
||||
logger.LogInformation("本月消费明细{JSON}", JsonSerializer.Serialize(monthTransactions));
|
||||
logger.LogInformation("全年累计消费概况{JSON}", JsonSerializer.Serialize(yearTransactions));
|
||||
logger.LogInformation("未被预算覆盖的分类{JSON}", JsonSerializer.Serialize(uncovered));
|
||||
|
||||
var dataPrompt = $"""
|
||||
报告周期:{year}年{month}月
|
||||
账单数据说明:支出金额已取绝对值(TotalAmount 为正数表示支出/收入的总量)。
|
||||
|
||||
1. 预算执行数据(JSON):
|
||||
{JsonSerializer.Serialize(archiveData)}
|
||||
|
||||
2. 本月消费明细(按分类, JSON):
|
||||
{JsonSerializer.Serialize(monthTransactions)}
|
||||
|
||||
3. 全年累计消费概况(按分类, JSON):
|
||||
{JsonSerializer.Serialize(yearTransactions)}
|
||||
|
||||
4. 未被任何预算覆盖的支出分类(JSON):
|
||||
{JsonSerializer.Serialize(uncovered)}
|
||||
|
||||
请生成一份专业且美观的预算执行分析报告,严格遵守以下要求:
|
||||
|
||||
【内容要求】
|
||||
1. 概览:总结本月预算达成情况。
|
||||
2. 预算详情:使用 HTML 表格展示预算执行明细(预算项、预算额、实际额、使用/达成率、状态)。
|
||||
3. 超支/异常预警:重点分析超支项或支出异常的分类。
|
||||
4. 消费透视:针对“未被预算覆盖的支出”提供分析建议。分析这些账单产生的合理性,并评估是否需要为其中的大额或频发分类建立新预算。
|
||||
5. 改进建议:根据当前时间进度和预算完成进度,基于本月整体收入支出情况,给出下月预算调整或消费改进的专业化建议。
|
||||
6. 语言风格:专业、清晰、简洁,适合财务报告阅读。
|
||||
7.
|
||||
|
||||
【格式要求】
|
||||
1. 使用HTML格式(移动端H5页面风格)
|
||||
2. 生成清晰的报告标题(基于用户问题)
|
||||
3. 使用表格展示统计数据(table > thead/tbody > tr > th/td)
|
||||
4. 使用合适的HTML标签:h2(标题)、h3(小节)、p(段落)、table(表格)、ul/li(列表)、strong(强调)
|
||||
5. 支出金额用 <span class='expense-value'>金额</span> 包裹
|
||||
6. 收入金额用 <span class='income-value'>金额</span> 包裹
|
||||
7. 重要结论用 <span class='highlight'>内容</span> 高亮
|
||||
|
||||
【样式限制(重要)】
|
||||
8. 不要包含 html、body、head 标签
|
||||
9. 不要使用任何 style 属性或 <style> 标签
|
||||
10. 不要设置 background、background-color、color 等样式属性
|
||||
11. 不要使用 div 包裹大段内容
|
||||
|
||||
【系统信息】
|
||||
当前时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}
|
||||
预算归档周期:{year}年{month}月
|
||||
|
||||
直接输出纯净 HTML 内容,不要带有 Markdown 代码块包裹。
|
||||
""";
|
||||
|
||||
var htmlReport = await openAiService.ChatAsync(dataPrompt);
|
||||
if (!string.IsNullOrEmpty(htmlReport))
|
||||
{
|
||||
await messageService.AddAsync(
|
||||
title: $"{year}年{month}月 - 预算归档报告",
|
||||
content: htmlReport,
|
||||
type: MessageType.Html,
|
||||
url: "/balance?tab=message");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "生成预算执行通知报告失败");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<decimal> CalculateCurrentAmountAsync(BudgetRecord budget, DateTime? now = null)
|
||||
{
|
||||
var referenceDate = now ?? DateTime.Now;
|
||||
var (startDate, endDate) = GetPeriodRange(budget.StartDate, budget.Type, referenceDate);
|
||||
|
||||
return await budgetRepository.GetCurrentAmountAsync(budget, startDate, endDate);
|
||||
}
|
||||
|
||||
internal static (DateTime start, DateTime end) GetPeriodRange(DateTime startDate, BudgetPeriodType type, DateTime referenceDate)
|
||||
{
|
||||
DateTime start;
|
||||
DateTime end;
|
||||
|
||||
if (type == BudgetPeriodType.Month)
|
||||
{
|
||||
start = new DateTime(referenceDate.Year, referenceDate.Month, 1);
|
||||
end = start.AddMonths(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);
|
||||
}
|
||||
else if (type == BudgetPeriodType.Year)
|
||||
{
|
||||
start = new DateTime(referenceDate.Year, 1, 1);
|
||||
end = new DateTime(referenceDate.Year, 12, 31).AddHours(23).AddMinutes(59).AddSeconds(59);
|
||||
}
|
||||
else
|
||||
{
|
||||
start = startDate;
|
||||
end = DateTime.MaxValue;
|
||||
}
|
||||
|
||||
return (start, end);
|
||||
}
|
||||
|
||||
private async Task<BudgetResult?> GetVirtualSavingsDtoAsync(
|
||||
BudgetPeriodType periodType,
|
||||
DateTime? referenceDate = null,
|
||||
IEnumerable<BudgetRecord>? existingBudgets = null)
|
||||
{
|
||||
var allBudgets = existingBudgets;
|
||||
|
||||
if (existingBudgets == null)
|
||||
{
|
||||
allBudgets = await budgetRepository.GetAllAsync();
|
||||
}
|
||||
|
||||
if (allBudgets == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var date = referenceDate ?? DateTime.Now;
|
||||
|
||||
decimal incomeLimitAtPeriod = 0;
|
||||
decimal expenseLimitAtPeriod = 0;
|
||||
|
||||
var incomeItems = new List<(string Name, decimal Limit, decimal Factor, decimal Total)>();
|
||||
var expenseItems = new List<(string Name, decimal Limit, decimal Factor, decimal Total)>();
|
||||
|
||||
foreach (var b in allBudgets)
|
||||
{
|
||||
if (b.Category == BudgetCategory.Savings) continue;
|
||||
|
||||
// 折算系数:根据当前请求的 periodType (Year 或 Month),将预算 b 的 Limit 折算过来
|
||||
decimal factor = 1.0m;
|
||||
|
||||
if (periodType == BudgetPeriodType.Year)
|
||||
{
|
||||
factor = b.Type switch
|
||||
{
|
||||
BudgetPeriodType.Month => 12,
|
||||
BudgetPeriodType.Year => 1,
|
||||
_ => 0
|
||||
};
|
||||
}
|
||||
else if (periodType == BudgetPeriodType.Month)
|
||||
{
|
||||
factor = b.Type switch
|
||||
{
|
||||
BudgetPeriodType.Month => 1,
|
||||
BudgetPeriodType.Year => 0,
|
||||
_ => 0
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
factor = 0; // 其他周期暂不计算虚拟存款
|
||||
}
|
||||
|
||||
if (factor <= 0) continue;
|
||||
|
||||
var subtotal = b.Limit * factor;
|
||||
if (b.Category == BudgetCategory.Income)
|
||||
{
|
||||
incomeLimitAtPeriod += subtotal;
|
||||
incomeItems.Add((b.Name, b.Limit, factor, subtotal));
|
||||
}
|
||||
else if (b.Category == BudgetCategory.Expense)
|
||||
{
|
||||
expenseLimitAtPeriod += subtotal;
|
||||
expenseItems.Add((b.Name, b.Limit, factor, subtotal));
|
||||
}
|
||||
}
|
||||
|
||||
var description = new StringBuilder();
|
||||
description.Append("<h3>预算收入明细</h3>");
|
||||
if (incomeItems.Count == 0) description.Append("<p>无收入预算</p>");
|
||||
else
|
||||
{
|
||||
description.Append("<table><thead><tr><th>名称</th><th>金额</th><th>折算</th><th>合计</th></tr></thead><tbody>");
|
||||
foreach (var item in incomeItems)
|
||||
{
|
||||
description.Append($"<tr><td>{item.Name}</td><td>{item.Limit:N0}</td><td>x{item.Factor:0.##}</td><td><span class='income-value'>{item.Total:N0}</span></td></tr>");
|
||||
}
|
||||
description.Append("</tbody></table>");
|
||||
}
|
||||
description.Append($"<p>收入合计: <span class='income-value'><strong>{incomeLimitAtPeriod:N0}</strong></span></p>");
|
||||
|
||||
description.Append("<h3>预算支出明细</h3>");
|
||||
if (expenseItems.Count == 0) description.Append("<p>无支出预算</p>");
|
||||
else
|
||||
{
|
||||
description.Append("<table><thead><tr><th>名称</th><th>金额</th><th>折算</th><th>合计</th></tr></thead><tbody>");
|
||||
foreach (var item in expenseItems)
|
||||
{
|
||||
description.Append($"<tr><td>{item.Name}</td><td>{item.Limit:N0}</td><td>x{item.Factor:0.##}</td><td><span class='expense-value'>{item.Total:N0}</span></td></tr>");
|
||||
}
|
||||
description.Append("</tbody></table>");
|
||||
}
|
||||
description.Append($"<p>支出合计: <span class='expense-value'><strong>{expenseLimitAtPeriod:N0}</strong></span></p>");
|
||||
|
||||
description.Append("<h3>存款计划结论</h3>");
|
||||
description.Append($"<p>计划存款 = 收入 <span class='income-value'>{incomeLimitAtPeriod:N0}</span> - 支出 <span class='expense-value'>{expenseLimitAtPeriod:N0}</span></p>");
|
||||
description.Append($"<p>最终目标:<span class='highlight'><strong>{incomeLimitAtPeriod - expenseLimitAtPeriod:N0}</strong></span></p>");
|
||||
|
||||
var virtualBudget = await BuildVirtualSavingsBudgetRecordAsync(
|
||||
periodType == BudgetPeriodType.Year ? -1 : -2,
|
||||
date,
|
||||
incomeLimitAtPeriod - expenseLimitAtPeriod);
|
||||
|
||||
// 计算实际发生的 收入 - 支出
|
||||
var current = await CalculateCurrentAmountAsync(new BudgetRecord
|
||||
{
|
||||
Category = virtualBudget.Category,
|
||||
Type = virtualBudget.Type,
|
||||
SelectedCategories = virtualBudget.SelectedCategories,
|
||||
StartDate = virtualBudget.StartDate,
|
||||
}, date);
|
||||
|
||||
return BudgetResult.FromEntity(virtualBudget, current, date, description.ToString());
|
||||
}
|
||||
|
||||
private async Task<BudgetRecord> BuildVirtualSavingsBudgetRecordAsync(
|
||||
long id,
|
||||
DateTime date,
|
||||
decimal limit)
|
||||
{
|
||||
var savingsCategories = await configService.GetConfigByKeyAsync<string>("SavingsCategories") ?? string.Empty;
|
||||
return new BudgetRecord
|
||||
{
|
||||
Id = id,
|
||||
Name = id == -1 ? "年度存款" : "月度存款",
|
||||
Category = BudgetCategory.Savings,
|
||||
Type = id == -1 ? BudgetPeriodType.Year : BudgetPeriodType.Month,
|
||||
Limit = limit,
|
||||
StartDate = id == -1
|
||||
? new DateTime(date.Year, 1, 1)
|
||||
: new DateTime(date.Year, date.Month, 1),
|
||||
SelectedCategories = savingsCategories
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public record BudgetResult
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public BudgetPeriodType Type { get; set; }
|
||||
public decimal Limit { get; set; }
|
||||
public decimal Current { get; set; }
|
||||
public BudgetCategory Category { get; set; }
|
||||
public string[] SelectedCategories { get; set; } = Array.Empty<string>();
|
||||
public string StartDate { get; set; } = string.Empty;
|
||||
public string Period { get; set; } = string.Empty;
|
||||
public DateTime? PeriodStart { get; set; }
|
||||
public DateTime? PeriodEnd { get; set; }
|
||||
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
public static BudgetResult FromEntity(
|
||||
BudgetRecord entity,
|
||||
decimal currentAmount = 0,
|
||||
DateTime? referenceDate = null,
|
||||
string description = "")
|
||||
{
|
||||
var date = referenceDate ?? DateTime.Now;
|
||||
var (start, end) = BudgetService.GetPeriodRange(entity.StartDate, entity.Type, date);
|
||||
|
||||
return new BudgetResult
|
||||
{
|
||||
Id = entity.Id,
|
||||
Name = entity.Name,
|
||||
Type = entity.Type,
|
||||
Limit = entity.Limit,
|
||||
Current = currentAmount,
|
||||
Category = entity.Category,
|
||||
SelectedCategories = string.IsNullOrEmpty(entity.SelectedCategories)
|
||||
? Array.Empty<string>()
|
||||
: entity.SelectedCategories.Split(','),
|
||||
StartDate = entity.StartDate.ToString("yyyy-MM-dd"),
|
||||
Period = entity.Type switch
|
||||
{
|
||||
BudgetPeriodType.Year => $"{start:yy}年",
|
||||
BudgetPeriodType.Month => $"{start:yy}年第{start.Month}月",
|
||||
_ => $"{start:yyyy-MM-dd} ~ {end:yyyy-MM-dd}"
|
||||
},
|
||||
PeriodStart = start,
|
||||
PeriodEnd = end,
|
||||
Description = description
|
||||
};
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 预算统计结果 DTO
|
||||
/// </summary>
|
||||
public class BudgetStatsDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 统计周期类型(Month/Year)
|
||||
/// </summary>
|
||||
public BudgetPeriodType PeriodType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 使用率百分比(0-100)
|
||||
/// </summary>
|
||||
public decimal Rate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 实际金额
|
||||
/// </summary>
|
||||
public decimal Current { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 目标/限额金额
|
||||
/// </summary>
|
||||
public decimal Limit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 预算项数量
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分类统计结果
|
||||
/// </summary>
|
||||
public class BudgetCategoryStats
|
||||
{
|
||||
/// <summary>
|
||||
/// 月度统计
|
||||
/// </summary>
|
||||
public BudgetStatsDto Month { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 年度统计
|
||||
/// </summary>
|
||||
public BudgetStatsDto Year { get; set; } = new();
|
||||
}
|
||||
public class UncoveredCategoryDetail
|
||||
{
|
||||
public string Category { get; set; } = string.Empty;
|
||||
public int TransactionCount { get; set; }
|
||||
public decimal TotalAmount { get; set; }
|
||||
}
|
||||
@@ -43,12 +43,12 @@ public class ConfigService(IConfigRepository configRepository) : IConfigService
|
||||
var config = await configRepository.GetByKeyAsync(key);
|
||||
var type = typeof(T) switch
|
||||
{
|
||||
Type t when t == typeof(bool) => ConfigType.Boolean,
|
||||
Type t when t == typeof(int)
|
||||
|| t == typeof(double)
|
||||
|| t == typeof(float)
|
||||
|| t == typeof(decimal) => ConfigType.Number,
|
||||
Type t when t == typeof(string) => ConfigType.String,
|
||||
{ } t when t == typeof(bool) => ConfigType.Boolean,
|
||||
{ } t when t == typeof(int)
|
||||
|| t == typeof(double)
|
||||
|| t == typeof(float)
|
||||
|| t == typeof(decimal) => ConfigType.Number,
|
||||
{ } t when t == typeof(string) => ConfigType.String,
|
||||
_ => ConfigType.Json
|
||||
};
|
||||
var valueStr = type switch
|
||||
|
||||
@@ -74,13 +74,13 @@ public class EmailFetchService(ILogger<EmailFetchService> logger) : IEmailFetchS
|
||||
_useSsl = useSsl;
|
||||
_email = email;
|
||||
_password = password;
|
||||
|
||||
|
||||
// 如果已连接,先断开
|
||||
if (_imapClient?.IsConnected == true)
|
||||
{
|
||||
await DisconnectAsync();
|
||||
}
|
||||
|
||||
|
||||
_imapClient = new ImapClient();
|
||||
|
||||
if (useSsl)
|
||||
@@ -206,7 +206,7 @@ public class EmailFetchService(ILogger<EmailFetchService> logger) : IEmailFetchS
|
||||
|
||||
// 标记邮件为已读(设置Seen标记)
|
||||
await inbox.AddFlagsAsync(uid, MessageFlags.Seen, silent: false);
|
||||
|
||||
|
||||
_logger.LogDebug("邮件 {Uid} 标记已读操作已提交", uid);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -240,13 +240,13 @@ public class EmailFetchService(ILogger<EmailFetchService> logger) : IEmailFetchS
|
||||
}
|
||||
return _imapClient?.IsConnected == true;
|
||||
}
|
||||
|
||||
|
||||
if (string.IsNullOrEmpty(_host) || string.IsNullOrEmpty(_email))
|
||||
{
|
||||
_logger.LogWarning("未初始化连接信息,无法自动重连");
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
_logger.LogInformation("检测到连接断开,尝试重新连接到 {Email}...", _email);
|
||||
return await ConnectAsync(_host, _port, _useSsl, _email, _password);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using Service.EmailParseServices;
|
||||
using Service.AI;
|
||||
using Service.EmailServices.EmailParse;
|
||||
using Service.Message;
|
||||
|
||||
namespace Service.EmailServices;
|
||||
|
||||
@@ -65,7 +67,7 @@ public class EmailHandleService(
|
||||
await messageService.AddAsync(
|
||||
"邮件解析失败",
|
||||
$"来自 {from} 发送给 {to} 的邮件(主题:{subject})未能成功解析内容,可能格式已变更或不受支持。",
|
||||
url: $"/balance?tab=email"
|
||||
url: "/balance?tab=email"
|
||||
);
|
||||
logger.LogWarning("未能成功解析邮件内容,跳过账单处理");
|
||||
return true;
|
||||
@@ -73,7 +75,7 @@ public class EmailHandleService(
|
||||
|
||||
logger.LogInformation("成功解析邮件,共 {Count} 条交易记录", parsed.Length);
|
||||
|
||||
bool allSuccess = true;
|
||||
var allSuccess = true;
|
||||
var records = new List<TransactionRecord>();
|
||||
foreach (var (card, reason, amount, balance, type, occurredAt) in parsed)
|
||||
{
|
||||
@@ -142,7 +144,7 @@ public class EmailHandleService(
|
||||
|
||||
logger.LogInformation("成功解析邮件,共 {Count} 条交易记录", parsed.Length);
|
||||
|
||||
bool allSuccess = true;
|
||||
var allSuccess = true;
|
||||
var records = new List<TransactionRecord>();
|
||||
foreach (var (card, reason, amount, balance, type, occurredAt) in parsed)
|
||||
{
|
||||
@@ -177,7 +179,7 @@ public class EmailHandleService(
|
||||
{
|
||||
var clone = records.ToArray().DeepClone();
|
||||
|
||||
if(clone?.Any() != true)
|
||||
if (clone?.Any() != true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace Service.EmailParseServices;
|
||||
using Service.AI;
|
||||
|
||||
namespace Service.EmailServices.EmailParse;
|
||||
|
||||
public class EmailParseForm95555(
|
||||
ILogger<EmailParseForm95555> logger,
|
||||
@@ -26,7 +28,7 @@ public class EmailParseForm95555(
|
||||
return true;
|
||||
}
|
||||
|
||||
public override async Task<(
|
||||
public override Task<(
|
||||
string card,
|
||||
string reason,
|
||||
decimal amount,
|
||||
@@ -51,7 +53,7 @@ public class EmailParseForm95555(
|
||||
if (matches.Count <= 0)
|
||||
{
|
||||
logger.LogWarning("未能从招商银行邮件内容中解析出交易信息");
|
||||
return [];
|
||||
return Task.FromResult<(string card, string reason, decimal amount, decimal balance, TransactionType type, DateTime? occurredAt)[]>([]);
|
||||
}
|
||||
|
||||
var results = new List<(
|
||||
@@ -70,7 +72,7 @@ public class EmailParseForm95555(
|
||||
var balanceStr = match.Groups["balance"].Value;
|
||||
var typeStr = match.Groups["type"].Value;
|
||||
var reason = match.Groups["reason"].Value;
|
||||
if(string.IsNullOrEmpty(reason))
|
||||
if (string.IsNullOrEmpty(reason))
|
||||
{
|
||||
reason = typeStr;
|
||||
}
|
||||
@@ -85,7 +87,7 @@ public class EmailParseForm95555(
|
||||
results.Add((card, reason, amount, balance, type, occurredAt));
|
||||
}
|
||||
}
|
||||
return results.ToArray();
|
||||
return Task.FromResult(results.ToArray());
|
||||
}
|
||||
|
||||
private DateTime? ParseOccurredAt(string value)
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
using HtmlAgilityPack;
|
||||
using Service.AI;
|
||||
// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
|
||||
// ReSharper disable ConditionalAccessQualifierIsNonNullableAccordingToAPIContract
|
||||
|
||||
namespace Service.EmailParseServices;
|
||||
namespace Service.EmailServices.EmailParse;
|
||||
|
||||
public class EmailParseFormCCSVC(
|
||||
ILogger<EmailParseFormCCSVC> logger,
|
||||
[UsedImplicitly]
|
||||
public partial class EmailParseFormCcsvc(
|
||||
ILogger<EmailParseFormCcsvc> logger,
|
||||
IOpenAiService openAiService
|
||||
) : EmailParseServicesBase(logger, openAiService)
|
||||
{
|
||||
[GeneratedRegex("<.*?>")]
|
||||
private static partial Regex HtmlRegex();
|
||||
|
||||
public override bool CanParse(string from, string subject, string body)
|
||||
{
|
||||
if (!from.Contains("ccsvc@message.cmbchina.com"))
|
||||
@@ -20,12 +27,7 @@ public class EmailParseFormCCSVC(
|
||||
}
|
||||
|
||||
// 必须包含HTML标签
|
||||
if (!Regex.IsMatch(body, "<.*?>"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
return HtmlRegex().IsMatch(body);
|
||||
}
|
||||
|
||||
public override async Task<(
|
||||
@@ -47,7 +49,7 @@ public class EmailParseFormCCSVC(
|
||||
if (dateNode == null)
|
||||
{
|
||||
logger.LogWarning("Date node not found");
|
||||
return Array.Empty<(string, string, decimal, decimal, TransactionType, DateTime?)>();
|
||||
return [];
|
||||
}
|
||||
|
||||
var dateText = dateNode.InnerText.Trim();
|
||||
@@ -56,7 +58,7 @@ public class EmailParseFormCCSVC(
|
||||
if (!dateMatch.Success || !DateTime.TryParse(dateMatch.Value, out var date))
|
||||
{
|
||||
logger.LogWarning("Failed to parse date from: {DateText}", dateText);
|
||||
return Array.Empty<(string, string, decimal, decimal, TransactionType, DateTime?)>();
|
||||
return [];
|
||||
}
|
||||
|
||||
// 2. Get Balance (Available Limit)
|
||||
@@ -90,6 +92,7 @@ public class EmailParseFormCCSVC(
|
||||
{
|
||||
foreach (var node in transactionNodes)
|
||||
{
|
||||
var card = "";
|
||||
try
|
||||
{
|
||||
// Time
|
||||
@@ -122,30 +125,23 @@ public class EmailParseFormCCSVC(
|
||||
descText = HtmlEntity.DeEntitize(descText).Replace((char)160, ' ').Trim();
|
||||
|
||||
// Parse Description: "尾号4390 消费 财付通-luckincoffee瑞幸咖啡"
|
||||
var parts = descText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
var parts = descText.Split([' '], StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
string card = "";
|
||||
string reason = descText;
|
||||
TransactionType type = TransactionType.Expense;
|
||||
var reason = descText;
|
||||
TransactionType type;
|
||||
|
||||
if (parts.Length > 0 && parts[0].StartsWith("尾号"))
|
||||
{
|
||||
card = parts[0].Replace("尾号", "");
|
||||
}
|
||||
|
||||
if (parts.Length > 1)
|
||||
{
|
||||
var typeStr = parts[1];
|
||||
type = DetermineTransactionType(typeStr, reason, amount);
|
||||
}
|
||||
|
||||
if (parts.Length > 2)
|
||||
{
|
||||
reason = string.Join(" ", parts.Skip(2));
|
||||
}
|
||||
|
||||
// 招商信用卡特殊,消费金额为正数,退款为负数
|
||||
if(amount > 0)
|
||||
if (amount > 0)
|
||||
{
|
||||
type = TransactionType.Expense;
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace Service.EmailParseServices;
|
||||
using Service.AI;
|
||||
|
||||
namespace Service.EmailServices.EmailParse;
|
||||
|
||||
public interface IEmailParseServices
|
||||
{
|
||||
@@ -45,7 +47,7 @@ public abstract class EmailParseServicesBase(
|
||||
// AI兜底
|
||||
result = await ParseByAiAsync(emailContent) ?? [];
|
||||
|
||||
if(result.Length == 0)
|
||||
if (result.Length == 0)
|
||||
{
|
||||
logger.LogWarning("AI解析邮件内容也未能提取到任何交易记录");
|
||||
}
|
||||
@@ -63,10 +65,10 @@ public abstract class EmailParseServicesBase(
|
||||
)[]> ParseEmailContentAsync(string emailContent);
|
||||
|
||||
private async Task<(
|
||||
string card,
|
||||
string reason,
|
||||
decimal amount,
|
||||
decimal balance,
|
||||
string card,
|
||||
string reason,
|
||||
decimal amount,
|
||||
decimal balance,
|
||||
TransactionType type,
|
||||
DateTime? occurredAt
|
||||
)[]?> ParseByAiAsync(string body)
|
||||
@@ -148,19 +150,19 @@ public abstract class EmailParseServicesBase(
|
||||
|
||||
private (string card, string reason, decimal amount, decimal balance, TransactionType type, DateTime? occurredAt)? ParseSingleRecord(JsonElement obj)
|
||||
{
|
||||
string card = obj.TryGetProperty("card", out var pCard) ? pCard.GetString() ?? string.Empty : string.Empty;
|
||||
string reason = obj.TryGetProperty("reason", out var pReason) ? pReason.GetString() ?? string.Empty : string.Empty;
|
||||
string typeStr = obj.TryGetProperty("type", out var pType) ? pType.GetString() ?? string.Empty : string.Empty;
|
||||
string occurredAtStr = obj.TryGetProperty("occurredAt", out var pOccurredAt) ? pOccurredAt.GetString() ?? string.Empty : string.Empty;
|
||||
var card = obj.TryGetProperty("card", out var pCard) ? pCard.GetString() ?? string.Empty : string.Empty;
|
||||
var reason = obj.TryGetProperty("reason", out var pReason) ? pReason.GetString() ?? string.Empty : string.Empty;
|
||||
var typeStr = obj.TryGetProperty("type", out var pType) ? pType.GetString() ?? string.Empty : string.Empty;
|
||||
var occurredAtStr = obj.TryGetProperty("occurredAt", out var pOccurredAt) ? pOccurredAt.GetString() ?? string.Empty : string.Empty;
|
||||
|
||||
decimal amount = 0m;
|
||||
var amount = 0m;
|
||||
if (obj.TryGetProperty("amount", out var pAmount))
|
||||
{
|
||||
if (pAmount.ValueKind == JsonValueKind.Number && pAmount.TryGetDecimal(out var d)) amount = d;
|
||||
else if (pAmount.ValueKind == JsonValueKind.String && decimal.TryParse(pAmount.GetString(), NumberStyles.Any, CultureInfo.InvariantCulture, out var ds)) amount = ds;
|
||||
}
|
||||
|
||||
decimal balance = 0m;
|
||||
var balance = 0m;
|
||||
if (obj.TryGetProperty("balance", out var pBalance))
|
||||
{
|
||||
if (pBalance.ValueKind == JsonValueKind.Number && pBalance.TryGetDecimal(out var d2)) balance = d2;
|
||||
@@ -173,7 +175,7 @@ public abstract class EmailParseServicesBase(
|
||||
}
|
||||
|
||||
var occurredAt = (DateTime?)null;
|
||||
if(DateTime.TryParse(occurredAtStr, out var occurredAtValue))
|
||||
if (DateTime.TryParse(occurredAtStr, out var occurredAtValue))
|
||||
{
|
||||
occurredAt = occurredAtValue;
|
||||
}
|
||||
@@ -201,7 +203,7 @@ public abstract class EmailParseServicesBase(
|
||||
|
||||
// 收入关键词
|
||||
string[] incomeKeywords =
|
||||
{
|
||||
[
|
||||
"工资", "奖金", "退款",
|
||||
"返现", "收入", "转入",
|
||||
"存入", "利息", "分红",
|
||||
@@ -233,13 +235,13 @@ public abstract class EmailParseServicesBase(
|
||||
// 存取类
|
||||
"现金存入", "柜台存入", "ATM存入",
|
||||
"他人转入", "他人汇入"
|
||||
};
|
||||
];
|
||||
if (incomeKeywords.Any(k => lowerReason.Contains(k)))
|
||||
return TransactionType.Income;
|
||||
|
||||
// 支出关键词
|
||||
string[] expenseKeywords =
|
||||
{
|
||||
[
|
||||
"消费", "支付", "购买",
|
||||
"转出", "取款", "支出",
|
||||
"扣款", "缴费", "付款",
|
||||
@@ -269,7 +271,7 @@ public abstract class EmailParseServicesBase(
|
||||
// 信用卡/花呗等场景
|
||||
"信用卡还款", "花呗还款", "白条还款",
|
||||
"分期还款", "账单还款", "自动还款"
|
||||
};
|
||||
];
|
||||
if (expenseKeywords.Any(k => lowerReason.Contains(k)))
|
||||
return TransactionType.Expense;
|
||||
|
||||
|
||||
@@ -182,6 +182,7 @@ public class EmailSyncService(
|
||||
var unreadMessages = await emailFetchService.FetchUnreadMessagesAsync();
|
||||
logger.LogInformation("邮箱 {Email} 获取到 {MessageCount} 封未读邮件", email, unreadMessages.Count);
|
||||
|
||||
// ReSharper disable once UnusedVariable
|
||||
foreach (var (message, uid) in unreadMessages)
|
||||
{
|
||||
try
|
||||
@@ -198,12 +199,12 @@ public class EmailSyncService(
|
||||
message.TextBody ?? message.HtmlBody ?? string.Empty
|
||||
) || (DateTime.Now - message.Date.DateTime > TimeSpan.FromDays(3)))
|
||||
{
|
||||
#if DEBUG
|
||||
#if DEBUG
|
||||
logger.LogDebug("DEBUG 模式下,跳过标记已读步骤");
|
||||
#else
|
||||
#else
|
||||
// 标记邮件为已读
|
||||
await emailFetchService.MarkAsReadAsync(uid);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -7,10 +7,12 @@ global using System.Globalization;
|
||||
global using System.Text;
|
||||
global using System.Text.Json;
|
||||
global using Entity;
|
||||
global using FreeSql;
|
||||
global using System.Linq;
|
||||
global using Service.AppSettingModel;
|
||||
global using System.Text.Json.Serialization;
|
||||
global using System.Text.Json.Nodes;
|
||||
global using Microsoft.Extensions.Configuration;
|
||||
global using Common;
|
||||
global using Common;
|
||||
global using System.Net;
|
||||
global using System.Text.Encodings.Web;
|
||||
global using JetBrains.Annotations;
|
||||
@@ -133,7 +133,7 @@ public class ImportService(
|
||||
return DateTime.MinValue;
|
||||
}
|
||||
|
||||
foreach (var format in DateTimeFormats)
|
||||
foreach (var format in _dateTimeFormats)
|
||||
{
|
||||
if (DateTime.TryParseExact(
|
||||
row[key],
|
||||
@@ -283,12 +283,12 @@ public class ImportService(
|
||||
|
||||
DateTime GetDateTimeValue(IDictionary<string, string> row, string key)
|
||||
{
|
||||
if(!row.ContainsKey(key))
|
||||
if (!row.ContainsKey(key))
|
||||
{
|
||||
return DateTime.MinValue;
|
||||
}
|
||||
|
||||
foreach (var format in DateTimeFormats)
|
||||
foreach (var format in _dateTimeFormats)
|
||||
{
|
||||
if (DateTime.TryParseExact(
|
||||
row[key],
|
||||
@@ -358,14 +358,13 @@ public class ImportService(
|
||||
{
|
||||
return await ParseCsvAsync(file);
|
||||
}
|
||||
else if (fileExtension == ".xlsx" || fileExtension == ".xls")
|
||||
|
||||
if (fileExtension == ".xlsx" || fileExtension == ".xls")
|
||||
{
|
||||
return await ParseExcelAsync(file);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException("不支持的文件格式");
|
||||
}
|
||||
|
||||
throw new NotSupportedException("不支持的文件格式");
|
||||
}
|
||||
|
||||
private async Task<IDictionary<string, string>[]> ParseCsvAsync(MemoryStream file)
|
||||
@@ -388,7 +387,7 @@ public class ImportService(
|
||||
|
||||
if (headers == null || headers.Length == 0)
|
||||
{
|
||||
return Array.Empty<IDictionary<string, string>>();
|
||||
return [];
|
||||
}
|
||||
|
||||
var result = new List<IDictionary<string, string>>();
|
||||
@@ -420,7 +419,7 @@ public class ImportService(
|
||||
|
||||
if (worksheet == null || worksheet.Dimension == null)
|
||||
{
|
||||
return Array.Empty<IDictionary<string, string>>();
|
||||
return [];
|
||||
}
|
||||
|
||||
var rowCount = worksheet.Dimension.End.Row;
|
||||
@@ -428,12 +427,12 @@ public class ImportService(
|
||||
|
||||
if (rowCount < 2)
|
||||
{
|
||||
return Array.Empty<IDictionary<string, string>>();
|
||||
return [];
|
||||
}
|
||||
|
||||
// 读取表头(第一行)
|
||||
var headers = new List<string>();
|
||||
for (int col = 1; col <= colCount; col++)
|
||||
for (var col = 1; col <= colCount; col++)
|
||||
{
|
||||
var header = worksheet.Cells[1, col].Text?.Trim() ?? string.Empty;
|
||||
headers.Add(header);
|
||||
@@ -442,10 +441,10 @@ public class ImportService(
|
||||
var result = new List<IDictionary<string, string>>();
|
||||
|
||||
// 读取数据行(从第二行开始)
|
||||
for (int row = 2; row <= rowCount; row++)
|
||||
for (var row = 2; row <= rowCount; row++)
|
||||
{
|
||||
var rowData = new Dictionary<string, string>();
|
||||
for (int col = 1; col <= colCount; col++)
|
||||
for (var col = 1; col <= colCount; col++)
|
||||
{
|
||||
var header = headers[col - 1];
|
||||
var value = worksheet.Cells[row, col].Text?.Trim() ?? string.Empty;
|
||||
@@ -458,7 +457,7 @@ public class ImportService(
|
||||
return await Task.FromResult(result.ToArray());
|
||||
}
|
||||
|
||||
private static string[] DateTimeFormats =
|
||||
private static string[] _dateTimeFormats =
|
||||
[
|
||||
"yyyy-MM-dd",
|
||||
"yyyy-MM-dd HH",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Quartz;
|
||||
using Service.Budget;
|
||||
|
||||
namespace Service.Jobs;
|
||||
|
||||
@@ -23,6 +24,8 @@ public class BudgetArchiveJob(
|
||||
|
||||
using var scope = serviceProvider.CreateScope();
|
||||
var budgetService = scope.ServiceProvider.GetRequiredService<IBudgetService>();
|
||||
|
||||
// 归档月度数据
|
||||
var result = await budgetService.ArchiveBudgetsAsync(year, month);
|
||||
|
||||
if (string.IsNullOrEmpty(result))
|
||||
|
||||
150
Service/Jobs/CategoryIconGenerationJob.cs
Normal file
150
Service/Jobs/CategoryIconGenerationJob.cs
Normal file
@@ -0,0 +1,150 @@
|
||||
using Quartz;
|
||||
using Service.AI;
|
||||
|
||||
namespace Service.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 分类图标生成定时任务
|
||||
/// 每10分钟扫描一次,为没有图标的分类生成 5 个 SVG 图标
|
||||
/// </summary>
|
||||
public class CategoryIconGenerationJob(
|
||||
ITransactionCategoryRepository categoryRepository,
|
||||
IOpenAiService openAiService,
|
||||
ILogger<CategoryIconGenerationJob> logger) : IJob
|
||||
{
|
||||
private static readonly SemaphoreSlim _semaphore = new(1, 1);
|
||||
|
||||
public async Task Execute(IJobExecutionContext context)
|
||||
{
|
||||
// 尝试获取锁,如果失败则跳过本次执行
|
||||
if (!await _semaphore.WaitAsync(0))
|
||||
{
|
||||
logger.LogInformation("上一个分类图标生成任务尚未完成,跳过本次执行");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
logger.LogInformation("开始执行分类图标生成任务");
|
||||
|
||||
// 查询所有分类,然后过滤出没有图标的
|
||||
var allCategories = await categoryRepository.GetAllAsync();
|
||||
var categoriesWithoutIcon = allCategories
|
||||
.Where(c => string.IsNullOrEmpty(c.Icon))
|
||||
.ToList();
|
||||
|
||||
if (categoriesWithoutIcon.Count == 0)
|
||||
{
|
||||
logger.LogInformation("所有分类都已有图标,跳过本次任务");
|
||||
return;
|
||||
}
|
||||
|
||||
logger.LogInformation("发现 {Count} 个分类没有图标,开始生成", categoriesWithoutIcon.Count);
|
||||
|
||||
// 为每个分类生成图标
|
||||
foreach (var category in categoriesWithoutIcon)
|
||||
{
|
||||
try
|
||||
{
|
||||
await GenerateIconsForCategoryAsync(category);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "为分类 {CategoryName}(ID:{CategoryId}) 生成图标失败",
|
||||
category.Name, category.Id);
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogInformation("分类图标生成任务执行完成");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "分类图标生成任务执行出错");
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为单个分类生成 5 个 SVG 图标
|
||||
/// </summary>
|
||||
private async Task GenerateIconsForCategoryAsync(TransactionCategory category)
|
||||
{
|
||||
logger.LogInformation("正在为分类 {CategoryName}(ID:{CategoryId}) 生成图标",
|
||||
category.Name, category.Id);
|
||||
|
||||
var typeText = category.Type == TransactionType.Expense ? "支出" : "收入";
|
||||
|
||||
var systemPrompt = """
|
||||
你是一个专业的 SVG 图标设计师,擅长创作精美、富有表现力的图标。
|
||||
请根据分类名称和类型,生成 5 个风格迥异、视觉效果突出的 SVG 图标。
|
||||
|
||||
设计要求:
|
||||
1. 尺寸:24x24,viewBox="0 0 24 24"
|
||||
2. 色彩:使用丰富的渐变色和多色搭配,让图标更有吸引力和辨识度
|
||||
- 可以使用 <linearGradient> 或 <radialGradient> 创建渐变效果
|
||||
- 不同元素使用不同颜色,增加层次感
|
||||
- 根据分类含义选择合适的配色方案(如餐饮用暖色系、交通用蓝色系等)
|
||||
3. 设计风格:5 个图标必须风格明显不同,避免雷同
|
||||
- 第1个:扁平化风格,色彩鲜明,使用渐变
|
||||
- 第2个:线性风格,多色描边,细节丰富
|
||||
- 第3个:3D立体风格,使用阴影和高光效果
|
||||
- 第4个:卡通可爱风格,圆润造型,活泼配色
|
||||
- 第5个:现代简约风格,几何与曲线结合,优雅配色
|
||||
4. 细节丰富:不要只用简单的几何图形,添加特征性的细节元素
|
||||
- 例如:餐饮可以加刀叉、蒸汽、食材纹理等
|
||||
- 交通可以加轮胎、车窗、尾气等
|
||||
- 每个图标要有独特的视觉记忆点
|
||||
5. 图标要直观表达分类含义,让人一眼就能识别
|
||||
6. 只返回 JSON 数组格式,包含 5 个完整的 SVG 字符串,不要有任何其他文字说明
|
||||
|
||||
重要:每个 SVG 必须是自包含的完整代码,包含所有必要的 gradient 定义。
|
||||
""";
|
||||
|
||||
var userPrompt = $"""
|
||||
分类名称:{category.Name}
|
||||
分类类型:{typeText}
|
||||
|
||||
请为这个分类生成 5 个精美的、风格各异的彩色 SVG 图标。
|
||||
确保每个图标都有独特的视觉特征,不会与其他图标混淆。
|
||||
|
||||
返回格式(纯 JSON 数组,无其他内容):
|
||||
["<svg>...</svg>", "<svg>...</svg>", "<svg>...</svg>", "<svg>...</svg>", "<svg>...</svg>"]
|
||||
""";
|
||||
|
||||
var response = await openAiService.ChatAsync(systemPrompt, userPrompt, timeoutSeconds: 60 * 10);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(response))
|
||||
{
|
||||
logger.LogWarning("AI 未返回有效的图标数据,分类: {CategoryName}", category.Name);
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证返回的是有效的 JSON 数组
|
||||
try
|
||||
{
|
||||
var icons = JsonSerializer.Deserialize<List<string>>(response);
|
||||
if (icons == null || icons.Count != 5)
|
||||
{
|
||||
logger.LogWarning("AI 返回的图标数量不正确(期望5个),分类: {CategoryName}", category.Name);
|
||||
return;
|
||||
}
|
||||
|
||||
// 保存图标到数据库
|
||||
category.Icon = response;
|
||||
await categoryRepository.UpdateAsync(category);
|
||||
|
||||
logger.LogInformation("成功为分类 {CategoryName}(ID:{CategoryId}) 生成并保存了 5 个图标",
|
||||
category.Name, category.Id);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
logger.LogError(ex, "解析 AI 返回的图标数据失败,分类: {CategoryName},响应内容: {Response}",
|
||||
category.Name, response);
|
||||
}
|
||||
}
|
||||
}
|
||||
70
Service/Jobs/DbBackupJob.cs
Normal file
70
Service/Jobs/DbBackupJob.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Quartz;
|
||||
|
||||
namespace Service.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 数据库备份任务
|
||||
/// </summary>
|
||||
public class DbBackupJob(
|
||||
IHostEnvironment env,
|
||||
ILogger<DbBackupJob> logger) : IJob
|
||||
{
|
||||
public Task Execute(IJobExecutionContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogInformation("开始执行数据库备份任务");
|
||||
|
||||
// 数据库文件路径 (基于 appsettings.json 中的配置: database/EmailBill.db)
|
||||
var dbPath = Path.Combine(env.ContentRootPath, "database", "EmailBill.db");
|
||||
var backupDir = Path.Combine(env.ContentRootPath, "database", "backups");
|
||||
|
||||
if (!File.Exists(dbPath))
|
||||
{
|
||||
logger.LogWarning("数据库文件不存在,跳过备份: {Path}", dbPath);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
if (!Directory.Exists(backupDir))
|
||||
{
|
||||
Directory.CreateDirectory(backupDir);
|
||||
}
|
||||
|
||||
// 创建备份
|
||||
var backupFileName = $"EmailBill_backup_{DateTime.Now:yyyyMMdd}.db";
|
||||
var backupPath = Path.Combine(backupDir, backupFileName);
|
||||
|
||||
File.Copy(dbPath, backupPath, true);
|
||||
logger.LogInformation("数据库备份成功: {Path}", backupPath);
|
||||
|
||||
// 清理旧备份 (保留最近20个)
|
||||
var files = new DirectoryInfo(backupDir).GetFiles("EmailBill_backup_*.db")
|
||||
.OrderByDescending(f => f.LastWriteTime) // 使用 LastWriteTime 排序
|
||||
.ToList();
|
||||
|
||||
if (files.Count > 20)
|
||||
{
|
||||
var filesToDelete = files.Skip(20);
|
||||
foreach (var file in filesToDelete)
|
||||
{
|
||||
try
|
||||
{
|
||||
file.Delete();
|
||||
logger.LogInformation("删除过期备份: {Name}", file.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "删除过期备份失败: {Name}", file.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "数据库备份任务执行失败");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,7 @@ public class EmailSyncJob(
|
||||
var unreadMessages = await emailFetchService.FetchUnreadMessagesAsync();
|
||||
logger.LogInformation("邮箱 {Email} 获取到 {MessageCount} 封未读邮件", email, unreadMessages.Count);
|
||||
|
||||
// ReSharper disable once UnusedVariable
|
||||
foreach (var (message, uid) in unreadMessages)
|
||||
{
|
||||
try
|
||||
@@ -143,12 +144,12 @@ public class EmailSyncJob(
|
||||
message.TextBody ?? message.HtmlBody ?? string.Empty
|
||||
) || (DateTime.Now - message.Date.DateTime > TimeSpan.FromDays(3)))
|
||||
{
|
||||
#if DEBUG
|
||||
#if DEBUG
|
||||
logger.LogDebug("DEBUG 模式下,跳过标记已读步骤");
|
||||
#else
|
||||
#else
|
||||
// 标记邮件为已读
|
||||
await emailFetchService.MarkAsReadAsync(uid);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
78
Service/Jobs/LogCleanupJob.cs
Normal file
78
Service/Jobs/LogCleanupJob.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using Quartz;
|
||||
|
||||
namespace Service.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 日志清理定时任务
|
||||
/// </summary>
|
||||
[DisallowConcurrentExecution]
|
||||
public class LogCleanupJob(ILogger<LogCleanupJob> logger) : IJob
|
||||
{
|
||||
private const int RetentionDays = 30; // 保留30天的日志
|
||||
|
||||
public Task Execute(IJobExecutionContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogInformation("开始执行日志清理任务");
|
||||
|
||||
var logDirectory = Path.Combine(Directory.GetCurrentDirectory(), "logs");
|
||||
if (!Directory.Exists(logDirectory))
|
||||
{
|
||||
logger.LogWarning("日志目录不存在: {LogDirectory}", logDirectory);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var cutoffDate = DateTime.Now.AddDays(-RetentionDays);
|
||||
var logFiles = Directory.GetFiles(logDirectory, "log-*.txt");
|
||||
var deletedCount = 0;
|
||||
|
||||
foreach (var logFile in logFiles)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fileName = Path.GetFileNameWithoutExtension(logFile);
|
||||
var dateStr = fileName.Replace("log-", "");
|
||||
|
||||
// 尝试解析日期 (格式: yyyyMMdd)
|
||||
if (DateTime.TryParseExact(dateStr, "yyyyMMdd",
|
||||
CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.None,
|
||||
out var logDate))
|
||||
{
|
||||
if (logDate < cutoffDate)
|
||||
{
|
||||
File.Delete(logFile);
|
||||
deletedCount++;
|
||||
logger.LogInformation("已删除过期日志文件: {LogFile} (日期: {LogDate})",
|
||||
Path.GetFileName(logFile), logDate.ToString("yyyy-MM-dd"));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "删除日志文件失败: {LogFile}", logFile);
|
||||
}
|
||||
}
|
||||
|
||||
if (deletedCount > 0)
|
||||
{
|
||||
logger.LogInformation("日志清理完成,共删除 {DeletedCount} 个过期日志文件(保留 {RetentionDays} 天)",
|
||||
deletedCount, RetentionDays);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogDebug("没有需要清理的过期日志文件");
|
||||
}
|
||||
|
||||
logger.LogInformation("日志清理任务执行完成");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "日志清理任务执行出错");
|
||||
throw; // 让 Quartz 知道任务失败
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Quartz;
|
||||
using Service.Transaction;
|
||||
|
||||
namespace Service.Jobs;
|
||||
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace Service;
|
||||
|
||||
/// <summary>
|
||||
/// 日志清理后台服务
|
||||
/// </summary>
|
||||
public class LogCleanupService(ILogger<LogCleanupService> logger) : BackgroundService
|
||||
{
|
||||
private readonly TimeSpan _checkInterval = TimeSpan.FromHours(24); // 每24小时检查一次
|
||||
private const int RetentionDays = 30; // 保留30天的日志
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
logger.LogInformation("日志清理服务已启动");
|
||||
|
||||
// 启动时立即执行一次清理
|
||||
await CleanupOldLogsAsync();
|
||||
|
||||
// 定期清理
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(_checkInterval, stoppingToken);
|
||||
await CleanupOldLogsAsync();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// 服务正在停止
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "清理日志时发生错误");
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogInformation("日志清理服务已停止");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清理过期的日志文件
|
||||
/// </summary>
|
||||
private async Task CleanupOldLogsAsync()
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var logDirectory = Path.Combine(Directory.GetCurrentDirectory(), "logs");
|
||||
if (!Directory.Exists(logDirectory))
|
||||
{
|
||||
logger.LogWarning("日志目录不存在: {LogDirectory}", logDirectory);
|
||||
return;
|
||||
}
|
||||
|
||||
var cutoffDate = DateTime.Now.AddDays(-RetentionDays);
|
||||
var logFiles = Directory.GetFiles(logDirectory, "log-*.txt");
|
||||
var deletedCount = 0;
|
||||
|
||||
foreach (var logFile in logFiles)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fileName = Path.GetFileNameWithoutExtension(logFile);
|
||||
var dateStr = fileName.Replace("log-", "");
|
||||
|
||||
// 尝试解析日期 (格式: yyyyMMdd)
|
||||
if (DateTime.TryParseExact(dateStr, "yyyyMMdd",
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
System.Globalization.DateTimeStyles.None,
|
||||
out var logDate))
|
||||
{
|
||||
if (logDate < cutoffDate)
|
||||
{
|
||||
File.Delete(logFile);
|
||||
deletedCount++;
|
||||
logger.LogInformation("已删除过期日志文件: {LogFile} (日期: {LogDate})",
|
||||
Path.GetFileName(logFile), logDate.ToString("yyyy-MM-dd"));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "删除日志文件失败: {LogFile}", logFile);
|
||||
}
|
||||
}
|
||||
|
||||
if (deletedCount > 0)
|
||||
{
|
||||
logger.LogInformation("日志清理完成,共删除 {DeletedCount} 个过期日志文件(保留 {RetentionDays} 天)",
|
||||
deletedCount, RetentionDays);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogDebug("没有需要清理的过期日志文件");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "清理日志过程中发生错误");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Service;
|
||||
namespace Service.Message;
|
||||
|
||||
public interface IMessageService
|
||||
{
|
||||
@@ -30,9 +30,9 @@ public class MessageService(IMessageRecordRepository messageRepo, INotificationS
|
||||
}
|
||||
|
||||
public async Task<bool> AddAsync(
|
||||
string title,
|
||||
string content,
|
||||
MessageType type = MessageType.Text,
|
||||
string title,
|
||||
string content,
|
||||
MessageType type = MessageType.Text,
|
||||
string? url = null
|
||||
)
|
||||
{
|
||||
@@ -56,7 +56,7 @@ public class MessageService(IMessageRecordRepository messageRepo, INotificationS
|
||||
{
|
||||
var message = await messageRepo.GetByIdAsync(id);
|
||||
if (message == null) return false;
|
||||
|
||||
|
||||
message.IsRead = true;
|
||||
message.UpdateTime = DateTime.Now;
|
||||
return await messageRepo.UpdateAsync(message);
|
||||
@@ -1,11 +1,12 @@
|
||||
using WebPush;
|
||||
using PushSubscription = Entity.PushSubscription;
|
||||
|
||||
namespace Service;
|
||||
namespace Service.Message;
|
||||
|
||||
public interface INotificationService
|
||||
{
|
||||
Task<string> GetVapidPublicKeyAsync();
|
||||
Task SubscribeAsync(Entity.PushSubscription subscription);
|
||||
Task SubscribeAsync(PushSubscription subscription);
|
||||
Task SendNotificationAsync(string message, string? url = null);
|
||||
}
|
||||
|
||||
@@ -32,7 +33,7 @@ public class NotificationService(
|
||||
return Task.FromResult(GetSettings().PublicKey);
|
||||
}
|
||||
|
||||
public async Task SubscribeAsync(Entity.PushSubscription subscription)
|
||||
public async Task SubscribeAsync(PushSubscription subscription)
|
||||
{
|
||||
var existing = await subscriptionRepo.GetByEndpointAsync(subscription.Endpoint);
|
||||
if (existing != null)
|
||||
@@ -61,7 +62,7 @@ public class NotificationService(
|
||||
var webPushClient = new WebPushClient();
|
||||
|
||||
var subscriptions = await subscriptionRepo.GetAllAsync();
|
||||
var payload = System.Text.Json.JsonSerializer.Serialize(new
|
||||
var payload = JsonSerializer.Serialize(new
|
||||
{
|
||||
title = "System Notification",
|
||||
body = message,
|
||||
@@ -78,7 +79,7 @@ public class NotificationService(
|
||||
}
|
||||
catch (WebPushException ex)
|
||||
{
|
||||
if (ex.StatusCode == System.Net.HttpStatusCode.Gone || ex.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
if (ex.StatusCode == HttpStatusCode.Gone || ex.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
await subscriptionRepo.DeleteAsync(sub.Id);
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace Service;
|
||||
|
||||
/// <summary>
|
||||
/// 周期性账单后台服务
|
||||
/// </summary>
|
||||
public class PeriodicBillBackgroundService(
|
||||
IServiceProvider serviceProvider,
|
||||
ILogger<PeriodicBillBackgroundService> logger
|
||||
) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
logger.LogInformation("周期性账单后台服务已启动");
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
|
||||
// 计算下次执行时间(每天早上6点)
|
||||
var nextRun = now.Date.AddHours(6);
|
||||
if (now >= nextRun)
|
||||
{
|
||||
nextRun = nextRun.AddDays(1);
|
||||
}
|
||||
|
||||
var delay = nextRun - now;
|
||||
logger.LogInformation("下次执行周期性账单检查时间: {NextRun}, 延迟: {Delay}",
|
||||
nextRun.ToString("yyyy-MM-dd HH:mm:ss"), delay);
|
||||
|
||||
await Task.Delay(delay, stoppingToken);
|
||||
|
||||
if (stoppingToken.IsCancellationRequested)
|
||||
break;
|
||||
|
||||
// 执行周期性账单检查
|
||||
using (var scope = serviceProvider.CreateScope())
|
||||
{
|
||||
var periodicService = scope.ServiceProvider.GetRequiredService<ITransactionPeriodicService>();
|
||||
await periodicService.ExecutePeriodicBillsAsync();
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
logger.LogInformation("周期性账单后台服务已取消");
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "周期性账单后台服务执行出错");
|
||||
// 出错后等待1小时再重试
|
||||
await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogInformation("周期性账单后台服务已停止");
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="JetBrains.Annotations" />
|
||||
<PackageReference Include="MailKit" />
|
||||
<PackageReference Include="MimeKit" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Service;
|
||||
namespace Service.Transaction;
|
||||
|
||||
/// <summary>
|
||||
/// 周期性账单服务接口
|
||||
@@ -31,10 +31,10 @@ public class TransactionPeriodicService(
|
||||
try
|
||||
{
|
||||
logger.LogInformation("开始执行周期性账单检查...");
|
||||
|
||||
|
||||
var pendingBills = await periodicRepository.GetPendingPeriodicBillsAsync();
|
||||
var billsList = pendingBills.ToList();
|
||||
|
||||
|
||||
logger.LogInformation("找到 {Count} 条需要执行的周期性账单", billsList.Count);
|
||||
|
||||
foreach (var bill in billsList)
|
||||
@@ -61,10 +61,10 @@ public class TransactionPeriodicService(
|
||||
};
|
||||
|
||||
var success = await transactionRepository.AddAsync(transaction);
|
||||
|
||||
|
||||
if (success)
|
||||
{
|
||||
logger.LogInformation("成功创建周期性账单交易记录: {Reason}, 金额: {Amount}",
|
||||
logger.LogInformation("成功创建周期性账单交易记录: {Reason}, 金额: {Amount}",
|
||||
bill.Reason, bill.Amount);
|
||||
|
||||
// 创建未读消息
|
||||
@@ -80,8 +80,8 @@ public class TransactionPeriodicService(
|
||||
var now = DateTime.Now;
|
||||
var nextTime = CalculateNextExecuteTime(bill, now);
|
||||
await periodicRepository.UpdateExecuteTimeAsync(bill.Id, now, nextTime);
|
||||
|
||||
logger.LogInformation("周期性账单 {Id} 下次执行时间: {NextTime}",
|
||||
|
||||
logger.LogInformation("周期性账单 {Id} 下次执行时间: {NextTime}",
|
||||
bill.Id, nextTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "无");
|
||||
}
|
||||
else
|
||||
@@ -108,8 +108,13 @@ public class TransactionPeriodicService(
|
||||
/// </summary>
|
||||
private bool ShouldExecuteToday(TransactionPeriodic bill)
|
||||
{
|
||||
if (!bill.IsEnabled)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var today = DateTime.Today;
|
||||
|
||||
|
||||
// 如果从未执行过,需要执行
|
||||
if (bill.LastExecuteTime == null)
|
||||
{
|
||||
@@ -144,7 +149,7 @@ public class TransactionPeriodicService(
|
||||
var dayOfWeek = (int)today.DayOfWeek; // 0=Sunday, 1=Monday, ..., 6=Saturday
|
||||
var executeDays = config.Split(',', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(d => int.TryParse(d.Trim(), out var day) ? day : -1)
|
||||
.Where(d => d >= 0 && d <= 6)
|
||||
.Where(d => d is >= 0 and <= 6)
|
||||
.ToList();
|
||||
|
||||
return executeDays.Contains(dayOfWeek);
|
||||
@@ -160,7 +165,7 @@ public class TransactionPeriodicService(
|
||||
|
||||
var executeDays = config.Split(',', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(d => int.TryParse(d.Trim(), out var day) ? day : -1)
|
||||
.Where(d => d >= 1 && d <= 31)
|
||||
.Where(d => d is >= 1 and <= 31)
|
||||
.ToList();
|
||||
|
||||
// 如果当前为月末,且配置中有大于当月天数的日期,则也执行
|
||||
@@ -223,7 +228,7 @@ public class TransactionPeriodicService(
|
||||
|
||||
var executeDays = config.Split(',', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(d => int.TryParse(d.Trim(), out var day) ? day : -1)
|
||||
.Where(d => d >= 0 && d <= 6)
|
||||
.Where(d => d is >= 0 and <= 6)
|
||||
.OrderBy(d => d)
|
||||
.ToList();
|
||||
|
||||
@@ -231,7 +236,7 @@ public class TransactionPeriodicService(
|
||||
return null;
|
||||
|
||||
var currentDayOfWeek = (int)baseTime.DayOfWeek;
|
||||
|
||||
|
||||
// 找下一个执行日
|
||||
var nextDay = executeDays.FirstOrDefault(d => d > currentDayOfWeek);
|
||||
if (nextDay > 0)
|
||||
@@ -239,7 +244,7 @@ public class TransactionPeriodicService(
|
||||
var daysToAdd = nextDay - currentDayOfWeek;
|
||||
return baseTime.Date.AddDays(daysToAdd);
|
||||
}
|
||||
|
||||
|
||||
// 下周的第一个执行日
|
||||
var firstDay = executeDays.First();
|
||||
var daysUntilNextWeek = 7 - currentDayOfWeek + firstDay;
|
||||
@@ -253,7 +258,7 @@ public class TransactionPeriodicService(
|
||||
|
||||
var executeDays = config.Split(',', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(d => int.TryParse(d.Trim(), out var day) ? day : -1)
|
||||
.Where(d => d >= 1 && d <= 31)
|
||||
.Where(d => d is >= 1 and <= 31)
|
||||
.OrderBy(d => d)
|
||||
.ToList();
|
||||
|
||||
@@ -288,7 +293,7 @@ public class TransactionPeriodicService(
|
||||
var currentQuarterStartMonth = ((baseTime.Month - 1) / 3) * 3 + 1;
|
||||
var nextQuarterStartMonth = currentQuarterStartMonth + 3;
|
||||
var nextQuarterYear = baseTime.Year;
|
||||
|
||||
|
||||
if (nextQuarterStartMonth > 12)
|
||||
{
|
||||
nextQuarterStartMonth = 1;
|
||||
@@ -313,7 +318,7 @@ public class TransactionPeriodicService(
|
||||
// 处理闰年情况
|
||||
var daysInYear = DateTime.IsLeapYear(nextYear) ? 366 : 365;
|
||||
var actualDay = Math.Min(dayOfYear, daysInYear);
|
||||
|
||||
|
||||
return new DateTime(nextYear, 1, 1).AddDays(actualDay - 1);
|
||||
}
|
||||
}
|
||||
350
Service/Transaction/TransactionStatisticsService.cs
Normal file
350
Service/Transaction/TransactionStatisticsService.cs
Normal file
@@ -0,0 +1,350 @@
|
||||
namespace Service.Transaction;
|
||||
|
||||
public interface ITransactionStatisticsService
|
||||
{
|
||||
Task<Dictionary<string, (int count, decimal expense, decimal income, decimal saving)>> GetDailyStatisticsAsync(int year, int month, string? savingClassify = null);
|
||||
|
||||
Task<Dictionary<string, (int count, decimal expense, decimal income, decimal saving)>> GetDailyStatisticsByRangeAsync(DateTime startDate, DateTime endDate, string? savingClassify = null);
|
||||
|
||||
Task<MonthlyStatistics> GetMonthlyStatisticsAsync(int year, int month);
|
||||
|
||||
Task<List<CategoryStatistics>> GetCategoryStatisticsAsync(int year, int month, TransactionType type);
|
||||
|
||||
Task<List<TrendStatistics>> GetTrendStatisticsAsync(int startYear, int startMonth, int monthCount);
|
||||
|
||||
Task<(List<ReasonGroupDto> list, int total)> GetReasonGroupsAsync(int pageIndex = 1, int pageSize = 20);
|
||||
|
||||
Task<List<(TransactionRecord record, double relevanceScore)>> GetClassifiedByKeywordsWithScoreAsync(List<string> keywords, double minMatchRate = 0.3, int limit = 10);
|
||||
|
||||
Task<Dictionary<DateTime, decimal>> GetFilteredTrendStatisticsAsync(
|
||||
DateTime startDate,
|
||||
DateTime endDate,
|
||||
TransactionType type,
|
||||
IEnumerable<string> classifies,
|
||||
bool groupByMonth = false);
|
||||
|
||||
Task<Dictionary<(string, TransactionType), decimal>> GetAmountGroupByClassifyAsync(DateTime startTime, DateTime endTime);
|
||||
}
|
||||
|
||||
public class TransactionStatisticsService(
|
||||
ITransactionRecordRepository transactionRepository
|
||||
) : ITransactionStatisticsService
|
||||
{
|
||||
public async Task<Dictionary<string, (int count, decimal expense, decimal income, decimal saving)>> GetDailyStatisticsAsync(int year, int month, string? savingClassify = null)
|
||||
{
|
||||
// 当 month=0 时,表示查询整年数据
|
||||
DateTime startDate;
|
||||
DateTime endDate;
|
||||
|
||||
if (month == 0)
|
||||
{
|
||||
// 查询整年:1月1日至12月31日
|
||||
startDate = new DateTime(year, 1, 1);
|
||||
endDate = new DateTime(year, 12, 31).AddDays(1); // 包含12月31日
|
||||
}
|
||||
else
|
||||
{
|
||||
// 查询指定月份
|
||||
startDate = new DateTime(year, month, 1);
|
||||
endDate = startDate.AddMonths(1);
|
||||
}
|
||||
|
||||
return await GetDailyStatisticsByRangeAsync(startDate, endDate, savingClassify);
|
||||
}
|
||||
|
||||
public async Task<Dictionary<string, (int count, decimal expense, decimal income, decimal saving)>> GetDailyStatisticsByRangeAsync(DateTime startDate, DateTime endDate, string? savingClassify = null)
|
||||
{
|
||||
var records = await transactionRepository.QueryAsync(
|
||||
startDate: startDate,
|
||||
endDate: endDate,
|
||||
pageSize: int.MaxValue);
|
||||
|
||||
return records
|
||||
.GroupBy(t => t.OccurredAt.ToString("yyyy-MM-dd"))
|
||||
.ToDictionary(
|
||||
g => g.Key,
|
||||
g =>
|
||||
{
|
||||
var income = g.Where(t => t.Type == TransactionType.Income).Sum(t => Math.Abs(t.Amount));
|
||||
var expense = g.Where(t => t.Type == TransactionType.Expense).Sum(t => Math.Abs(t.Amount));
|
||||
|
||||
var saving = 0m;
|
||||
if (!string.IsNullOrEmpty(savingClassify))
|
||||
{
|
||||
saving = g.Where(t => savingClassify.Split(',').Contains(t.Classify)).Sum(t => Math.Abs(t.Amount));
|
||||
}
|
||||
|
||||
return (count: g.Count(), expense, income, saving);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public async Task<MonthlyStatistics> GetMonthlyStatisticsAsync(int year, int month)
|
||||
{
|
||||
var records = await transactionRepository.QueryAsync(
|
||||
year: year,
|
||||
month: month,
|
||||
pageSize: int.MaxValue);
|
||||
|
||||
var statistics = new MonthlyStatistics
|
||||
{
|
||||
Year = year,
|
||||
Month = month
|
||||
};
|
||||
|
||||
foreach (var record in records)
|
||||
{
|
||||
var amount = Math.Abs(record.Amount);
|
||||
|
||||
if (record.Type == TransactionType.Expense)
|
||||
{
|
||||
statistics.TotalExpense += amount;
|
||||
statistics.ExpenseCount++;
|
||||
}
|
||||
else if (record.Type == TransactionType.Income)
|
||||
{
|
||||
statistics.TotalIncome += amount;
|
||||
statistics.IncomeCount++;
|
||||
}
|
||||
}
|
||||
|
||||
statistics.Balance = statistics.TotalIncome - statistics.TotalExpense;
|
||||
statistics.TotalCount = records.Count;
|
||||
|
||||
return statistics;
|
||||
}
|
||||
|
||||
public async Task<List<CategoryStatistics>> GetCategoryStatisticsAsync(int year, int month, TransactionType type)
|
||||
{
|
||||
var records = await transactionRepository.QueryAsync(
|
||||
year: year,
|
||||
month: month,
|
||||
type: type,
|
||||
pageSize: int.MaxValue);
|
||||
|
||||
var categoryGroups = records
|
||||
.GroupBy(t => t.Classify)
|
||||
.Select(g => new CategoryStatistics
|
||||
{
|
||||
Classify = g.Key,
|
||||
Amount = g.Sum(t => Math.Abs(t.Amount)),
|
||||
Count = g.Count()
|
||||
})
|
||||
.OrderByDescending(c => c.Amount)
|
||||
.ToList();
|
||||
|
||||
var total = categoryGroups.Sum(c => c.Amount);
|
||||
if (total > 0)
|
||||
{
|
||||
foreach (var category in categoryGroups)
|
||||
{
|
||||
category.Percent = Math.Round((category.Amount / total) * 100, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return categoryGroups;
|
||||
}
|
||||
|
||||
public async Task<List<TrendStatistics>> GetTrendStatisticsAsync(int startYear, int startMonth, int monthCount)
|
||||
{
|
||||
var trends = new List<TrendStatistics>();
|
||||
|
||||
for (var i = 0; i < monthCount; i++)
|
||||
{
|
||||
var targetYear = startYear;
|
||||
var targetMonth = startMonth + i;
|
||||
|
||||
while (targetMonth > 12)
|
||||
{
|
||||
targetMonth -= 12;
|
||||
targetYear++;
|
||||
}
|
||||
|
||||
var records = await transactionRepository.QueryAsync(
|
||||
year: targetYear,
|
||||
month: targetMonth,
|
||||
pageSize: int.MaxValue);
|
||||
|
||||
var expense = records.Where(t => t.Type == TransactionType.Expense).Sum(t => Math.Abs(t.Amount));
|
||||
var income = records.Where(t => t.Type == TransactionType.Income).Sum(t => Math.Abs(t.Amount));
|
||||
|
||||
trends.Add(new TrendStatistics
|
||||
{
|
||||
Year = targetYear,
|
||||
Month = targetMonth,
|
||||
Expense = expense,
|
||||
Income = income,
|
||||
Balance = income - expense
|
||||
});
|
||||
}
|
||||
|
||||
return trends;
|
||||
}
|
||||
|
||||
public async Task<(List<ReasonGroupDto> list, int total)> GetReasonGroupsAsync(int pageIndex = 1, int pageSize = 20)
|
||||
{
|
||||
var records = await transactionRepository.QueryAsync(
|
||||
pageSize: int.MaxValue);
|
||||
|
||||
var unclassifiedRecords = records
|
||||
.Where(t => !string.IsNullOrEmpty(t.Reason) && string.IsNullOrEmpty(t.Classify))
|
||||
.GroupBy(t => t.Reason)
|
||||
.Select(g => new
|
||||
{
|
||||
Reason = g.Key,
|
||||
Count = g.Count(),
|
||||
TotalAmount = g.Sum(r => r.Amount),
|
||||
SampleType = g.First().Type,
|
||||
SampleClassify = g.First().Classify,
|
||||
TransactionIds = g.Select(r => r.Id).ToList()
|
||||
})
|
||||
.OrderByDescending(g => Math.Abs(g.TotalAmount))
|
||||
.ToList();
|
||||
|
||||
var total = unclassifiedRecords.Count;
|
||||
var pagedGroups = unclassifiedRecords
|
||||
.Skip((pageIndex - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.Select(g => new ReasonGroupDto
|
||||
{
|
||||
Reason = g.Reason,
|
||||
Count = g.Count,
|
||||
SampleType = g.SampleType,
|
||||
SampleClassify = g.SampleClassify,
|
||||
TransactionIds = g.TransactionIds,
|
||||
TotalAmount = Math.Abs(g.TotalAmount)
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return (pagedGroups, total);
|
||||
}
|
||||
|
||||
public async Task<List<(TransactionRecord record, double relevanceScore)>> GetClassifiedByKeywordsWithScoreAsync(List<string> keywords, double minMatchRate = 0.3, int limit = 10)
|
||||
{
|
||||
if (keywords.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var candidates = await transactionRepository.GetClassifiedByKeywordsAsync(keywords, limit: int.MaxValue);
|
||||
|
||||
var scoredResults = candidates
|
||||
.Select(record =>
|
||||
{
|
||||
var matchedCount = keywords.Count(keyword => record.Reason.Contains(keyword, StringComparison.OrdinalIgnoreCase));
|
||||
var matchRate = (double)matchedCount / keywords.Count;
|
||||
|
||||
var exactMatchBonus = keywords.Any(k => record.Reason.Equals(k, StringComparison.OrdinalIgnoreCase)) ? 0.2 : 0.0;
|
||||
|
||||
var avgKeywordLength = keywords.Average(k => k.Length);
|
||||
var lengthSimilarity = 1.0 - Math.Min(1.0, Math.Abs(record.Reason.Length - avgKeywordLength) / Math.Max(record.Reason.Length, avgKeywordLength));
|
||||
var lengthBonus = lengthSimilarity * 0.1;
|
||||
|
||||
var score = matchRate + exactMatchBonus + lengthBonus;
|
||||
return (record, score);
|
||||
})
|
||||
.Where(x => x.score >= minMatchRate)
|
||||
.OrderByDescending(x => x.score)
|
||||
.ThenByDescending(x => x.record.OccurredAt)
|
||||
.Take(limit)
|
||||
.ToList();
|
||||
|
||||
return scoredResults;
|
||||
}
|
||||
|
||||
public async Task<Dictionary<DateTime, decimal>> GetFilteredTrendStatisticsAsync(
|
||||
DateTime startDate,
|
||||
DateTime endDate,
|
||||
TransactionType type,
|
||||
IEnumerable<string> classifies,
|
||||
bool groupByMonth = false)
|
||||
{
|
||||
var records = await transactionRepository.QueryAsync(
|
||||
startDate: startDate,
|
||||
endDate: endDate,
|
||||
type: type,
|
||||
classifies: classifies.ToArray(),
|
||||
pageSize: int.MaxValue);
|
||||
|
||||
if (groupByMonth)
|
||||
{
|
||||
return records
|
||||
.GroupBy(t => new DateTime(t.OccurredAt.Year, t.OccurredAt.Month, 1))
|
||||
.ToDictionary(g => g.Key, g => g.Sum(x => Math.Abs(x.Amount)));
|
||||
}
|
||||
|
||||
return records
|
||||
.GroupBy(t => t.OccurredAt.Date)
|
||||
.ToDictionary(g => g.Key, g => g.Sum(x => Math.Abs(x.Amount)));
|
||||
}
|
||||
|
||||
public async Task<Dictionary<(string, TransactionType), decimal>> GetAmountGroupByClassifyAsync(DateTime startTime, DateTime endTime)
|
||||
{
|
||||
var records = await transactionRepository.QueryAsync(
|
||||
startDate: startTime,
|
||||
endDate: endTime,
|
||||
pageSize: int.MaxValue);
|
||||
|
||||
return records
|
||||
.GroupBy(t => new { t.Classify, t.Type })
|
||||
.ToDictionary(g => (g.Key.Classify, g.Key.Type), g => g.Sum(t => t.Amount));
|
||||
}
|
||||
}
|
||||
|
||||
public record ReasonGroupDto
|
||||
{
|
||||
public string Reason { get; set; } = string.Empty;
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public TransactionType SampleType { get; set; }
|
||||
|
||||
public string SampleClassify { get; set; } = string.Empty;
|
||||
|
||||
public List<long> TransactionIds { get; set; } = [];
|
||||
|
||||
public decimal TotalAmount { get; set; }
|
||||
}
|
||||
|
||||
public record MonthlyStatistics
|
||||
{
|
||||
public int Year { get; set; }
|
||||
|
||||
public int Month { get; set; }
|
||||
|
||||
public decimal TotalExpense { get; set; }
|
||||
|
||||
public decimal TotalIncome { get; set; }
|
||||
|
||||
public decimal Balance { get; set; }
|
||||
|
||||
public int ExpenseCount { get; set; }
|
||||
|
||||
public int IncomeCount { get; set; }
|
||||
|
||||
public int TotalCount { get; set; }
|
||||
}
|
||||
|
||||
public record CategoryStatistics
|
||||
{
|
||||
public string Classify { get; set; } = string.Empty;
|
||||
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public decimal Percent { get; set; }
|
||||
}
|
||||
|
||||
public record TrendStatistics
|
||||
{
|
||||
public int Year { get; set; }
|
||||
|
||||
public int Month { get; set; }
|
||||
|
||||
public decimal Expense { get; set; }
|
||||
|
||||
public decimal Income { get; set; }
|
||||
|
||||
public decimal Balance { get; set; }
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -2,5 +2,6 @@
|
||||
"$schema": "https://json.schemastore.org/prettierrc",
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"printWidth": 100
|
||||
"printWidth": 100,
|
||||
"trailingComma": "none"
|
||||
}
|
||||
|
||||
@@ -1,52 +1,82 @@
|
||||
import js from '@eslint/js'
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import pluginVue from 'eslint-plugin-vue'
|
||||
import skipFormatting from '@vue/eslint-config-prettier/skip-formatting'
|
||||
|
||||
export default [
|
||||
{
|
||||
ignores: ['**/dist/**', '**/dist-ssr/**', '**/coverage/**', '**/node_modules/**', '.nuxt/**'],
|
||||
ignores: ['**/dist/**', '**/dist-ssr/**', '**/coverage/**', '**/node_modules/**', '.nuxt/**']
|
||||
},
|
||||
// Load Vue recommended rules first (sets up parser etc.)
|
||||
...pluginVue.configs['flat/recommended'],
|
||||
|
||||
// General Configuration for all JS/Vue files
|
||||
{
|
||||
files: ['**/*.{js,mjs,jsx}'],
|
||||
files: ['**/*.{js,mjs,jsx,vue}'],
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
},
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
...globals.browser
|
||||
},
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module'
|
||||
},
|
||||
rules: {
|
||||
// Import standard JS recommended rules
|
||||
...js.configs.recommended.rules,
|
||||
'indent': ['error', 2],
|
||||
|
||||
// --- Logic & Best Practices ---
|
||||
'no-unused-vars': ['warn', {
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_'
|
||||
}],
|
||||
'no-undef': 'error',
|
||||
'no-console': ['warn', { allow: ['warn', 'error', 'info'] }],
|
||||
'no-debugger': 'warn',
|
||||
'eqeqeq': ['error', 'always', { null: 'ignore' }],
|
||||
'curly': ['error', 'all'],
|
||||
'prefer-const': 'warn',
|
||||
'no-var': 'error',
|
||||
|
||||
// --- Formatting & Style (User requested warnings) ---
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'quotes': ['error', 'single', { avoidEscape: true }],
|
||||
'semi': ['error', 'never'],
|
||||
'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
|
||||
'comma-dangle': ['error', 'never'],
|
||||
'no-trailing-spaces': 'error',
|
||||
'no-multiple-empty-lines': ['error', { max: 1 }],
|
||||
'space-before-function-paren': ['error', 'always'],
|
||||
},
|
||||
'object-curly-spacing': ['error', 'always'],
|
||||
'array-bracket-spacing': ['error', 'never']
|
||||
}
|
||||
},
|
||||
...pluginVue.configs['flat/recommended'],
|
||||
|
||||
// Vue Specific Overrides
|
||||
{
|
||||
files: ['**/*.vue'],
|
||||
rules: {
|
||||
'vue/multi-word-component-names': 'off',
|
||||
'vue/no-v-html': 'warn',
|
||||
|
||||
// Turn off standard indent for Vue files to avoid conflicts with vue/html-indent
|
||||
// or script indentation issues. Vue plugin handles this better.
|
||||
'indent': 'off',
|
||||
},
|
||||
// Ensure Vue's own indentation rules are active (they are in 'recommended' but let's be explicit if needed)
|
||||
'vue/html-indent': ['error', 2],
|
||||
'vue/script-indent': ['error', 2, {
|
||||
baseIndent: 0,
|
||||
switchCase: 1,
|
||||
ignores: []
|
||||
}]
|
||||
}
|
||||
},
|
||||
skipFormatting,
|
||||
|
||||
// Service Worker specific globals
|
||||
{
|
||||
files: ['**/service-worker.js', '**/src/registerServiceWorker.js'],
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.serviceworker,
|
||||
...globals.browser,
|
||||
},
|
||||
},
|
||||
},
|
||||
...globals.serviceworker
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -11,11 +11,12 @@
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint . --fix --cache",
|
||||
"format": "prettier --write --experimental-cli src/"
|
||||
"format": "prettier --write src/"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.13.2",
|
||||
"dayjs": "^1.11.19",
|
||||
"echarts": "^6.0.0",
|
||||
"pinia": "^3.0.4",
|
||||
"vant": "^4.9.22",
|
||||
"vue": "^3.5.25",
|
||||
|
||||
23
Web/pnpm-lock.yaml
generated
23
Web/pnpm-lock.yaml
generated
@@ -14,6 +14,9 @@ importers:
|
||||
dayjs:
|
||||
specifier: ^1.11.19
|
||||
version: 1.11.19
|
||||
echarts:
|
||||
specifier: ^6.0.0
|
||||
version: 6.0.0
|
||||
pinia:
|
||||
specifier: ^3.0.4
|
||||
version: 3.0.4(vue@3.5.26)
|
||||
@@ -787,6 +790,9 @@ packages:
|
||||
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
echarts@6.0.0:
|
||||
resolution: {integrity: sha512-Tte/grDQRiETQP4xz3iZWSvoHrkCQtwqd6hs+mifXcjrCuo2iKWbajFObuLJVBlDIJlOzgQPd1hsaKt/3+OMkQ==}
|
||||
|
||||
electron-to-chromium@1.5.267:
|
||||
resolution: {integrity: sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==}
|
||||
|
||||
@@ -1296,6 +1302,9 @@ packages:
|
||||
resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
tslib@2.3.0:
|
||||
resolution: {integrity: sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==}
|
||||
|
||||
type-check@0.4.0:
|
||||
resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==}
|
||||
engines: {node: '>= 0.8.0'}
|
||||
@@ -1435,6 +1444,9 @@ packages:
|
||||
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
zrender@6.0.0:
|
||||
resolution: {integrity: sha512-41dFXEEXuJpNecuUQq6JlbybmnHaqqpGlbH1yxnA5V9MMP4SbohSVZsJIwz+zdjQXSSlR1Vc34EgH1zxyTDvhg==}
|
||||
|
||||
snapshots:
|
||||
|
||||
'@babel/code-frame@7.27.1':
|
||||
@@ -2131,6 +2143,11 @@ snapshots:
|
||||
es-errors: 1.3.0
|
||||
gopd: 1.2.0
|
||||
|
||||
echarts@6.0.0:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
zrender: 6.0.0
|
||||
|
||||
electron-to-chromium@1.5.267: {}
|
||||
|
||||
entities@7.0.0: {}
|
||||
@@ -2611,6 +2628,8 @@ snapshots:
|
||||
|
||||
totalist@3.0.1: {}
|
||||
|
||||
tslib@2.3.0: {}
|
||||
|
||||
type-check@0.4.0:
|
||||
dependencies:
|
||||
prelude-ls: 1.2.1
|
||||
@@ -2744,3 +2763,7 @@ snapshots:
|
||||
yallist@3.1.1: {}
|
||||
|
||||
yocto-queue@0.1.0: {}
|
||||
|
||||
zrender@6.0.0:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
|
||||
@@ -1,56 +1,56 @@
|
||||
const VERSION = '1.0.0'; // Build Time: 2026-01-07 15:59:36
|
||||
const CACHE_NAME = `emailbill-${VERSION}`;
|
||||
const VERSION = '1.0.0' // Build Time: 2026-01-07 15:59:36
|
||||
const CACHE_NAME = `emailbill-${VERSION}`
|
||||
const urlsToCache = [
|
||||
'/',
|
||||
'/index.html',
|
||||
'/favicon.ico',
|
||||
'/manifest.json'
|
||||
];
|
||||
]
|
||||
|
||||
// 安装 Service Worker
|
||||
self.addEventListener('install', (event) => {
|
||||
console.log('[Service Worker] 安装中...');
|
||||
console.log('[Service Worker] 安装中...')
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME)
|
||||
.then((cache) => {
|
||||
console.log('[Service Worker] 缓存文件');
|
||||
return cache.addAll(urlsToCache);
|
||||
console.log('[Service Worker] 缓存文件')
|
||||
return cache.addAll(urlsToCache)
|
||||
})
|
||||
);
|
||||
});
|
||||
)
|
||||
})
|
||||
|
||||
// 监听跳过等待消息
|
||||
self.addEventListener('message', (event) => {
|
||||
if (event.data && event.data.type === 'SKIP_WAITING') {
|
||||
self.skipWaiting();
|
||||
self.skipWaiting()
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
// 激活 Service Worker
|
||||
self.addEventListener('activate', (event) => {
|
||||
console.log('[Service Worker] 激活中...');
|
||||
console.log('[Service Worker] 激活中...')
|
||||
event.waitUntil(
|
||||
caches.keys().then((cacheNames) => {
|
||||
return Promise.all(
|
||||
cacheNames.map((cacheName) => {
|
||||
if (cacheName !== CACHE_NAME) {
|
||||
console.log('[Service Worker] 删除旧缓存:', cacheName);
|
||||
return caches.delete(cacheName);
|
||||
console.log('[Service Worker] 删除旧缓存:', cacheName)
|
||||
return caches.delete(cacheName)
|
||||
}
|
||||
})
|
||||
);
|
||||
)
|
||||
}).then(() => self.clients.claim())
|
||||
);
|
||||
});
|
||||
)
|
||||
})
|
||||
|
||||
// 拦截请求
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const { request } = event;
|
||||
const url = new URL(request.url);
|
||||
const { request } = event
|
||||
const url = new URL(request.url)
|
||||
|
||||
// 跳过跨域请求
|
||||
if (url.origin !== location.origin) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
// API请求使用网络优先策略
|
||||
@@ -60,19 +60,19 @@ self.addEventListener('fetch', (event) => {
|
||||
.then((response) => {
|
||||
// 只针对成功的GET请求进行缓存
|
||||
if (request.method === 'GET' && response.status === 200) {
|
||||
const responseClone = response.clone();
|
||||
const responseClone = response.clone()
|
||||
caches.open(CACHE_NAME).then((cache) => {
|
||||
cache.put(request, responseClone);
|
||||
});
|
||||
cache.put(request, responseClone)
|
||||
})
|
||||
}
|
||||
return response;
|
||||
return response
|
||||
})
|
||||
.catch(() => {
|
||||
// 网络失败时尝试从缓存获取
|
||||
return caches.match(request);
|
||||
return caches.match(request)
|
||||
})
|
||||
);
|
||||
return;
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// 页面请求使用网络优先策略,确保能获取到最新的 index.html
|
||||
@@ -80,17 +80,17 @@ self.addEventListener('fetch', (event) => {
|
||||
event.respondWith(
|
||||
fetch(request)
|
||||
.then((response) => {
|
||||
const responseClone = response.clone();
|
||||
const responseClone = response.clone()
|
||||
caches.open(CACHE_NAME).then((cache) => {
|
||||
cache.put(request, responseClone);
|
||||
});
|
||||
return response;
|
||||
cache.put(request, responseClone)
|
||||
})
|
||||
return response
|
||||
})
|
||||
.catch(() => {
|
||||
return caches.match('/index.html') || caches.match(request);
|
||||
return caches.match('/index.html') || caches.match(request)
|
||||
})
|
||||
);
|
||||
return;
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// 其他静态资源使用缓存优先策略
|
||||
@@ -98,50 +98,50 @@ self.addEventListener('fetch', (event) => {
|
||||
caches.match(request)
|
||||
.then((response) => {
|
||||
if (response) {
|
||||
return response;
|
||||
return response
|
||||
}
|
||||
return fetch(request).then((response) => {
|
||||
// 检查是否是有效响应
|
||||
if (!response || response.status !== 200 || response.type !== 'basic') {
|
||||
return response;
|
||||
return response
|
||||
}
|
||||
|
||||
const responseClone = response.clone();
|
||||
const responseClone = response.clone()
|
||||
caches.open(CACHE_NAME).then((cache) => {
|
||||
cache.put(request, responseClone);
|
||||
});
|
||||
cache.put(request, responseClone)
|
||||
})
|
||||
|
||||
return response;
|
||||
});
|
||||
return response
|
||||
})
|
||||
})
|
||||
.catch(() => {
|
||||
// 返回离线页面或默认内容
|
||||
if (request.destination === 'document') {
|
||||
return caches.match('/index.html');
|
||||
return caches.match('/index.html')
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
)
|
||||
})
|
||||
|
||||
// 后台同步
|
||||
self.addEventListener('sync', (event) => {
|
||||
console.log('[Service Worker] 后台同步:', event.tag);
|
||||
console.log('[Service Worker] 后台同步:', event.tag)
|
||||
if (event.tag === 'sync-data') {
|
||||
event.waitUntil(syncData());
|
||||
event.waitUntil(syncData())
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
// 推送通知
|
||||
self.addEventListener('push', (event) => {
|
||||
console.log('[Service Worker] 收到推送消息');
|
||||
let data = { title: '账单管理', body: '您有新的消息', url: '/', icon: '/icons/icon-192x192.png' };
|
||||
|
||||
console.log('[Service Worker] 收到推送消息')
|
||||
let data = { title: '账单管理', body: '您有新的消息', url: '/', icon: '/icons/icon-192x192.png' }
|
||||
|
||||
if (event.data) {
|
||||
try {
|
||||
const json = event.data.json();
|
||||
data = { ...data, ...json };
|
||||
const json = event.data.json()
|
||||
data = { ...data, ...json }
|
||||
} catch {
|
||||
data.body = event.data.text();
|
||||
data.body = event.data.text()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,41 +153,41 @@ self.addEventListener('push', (event) => {
|
||||
tag: 'emailbill-notification',
|
||||
requireInteraction: false,
|
||||
data: { url: data.url }
|
||||
};
|
||||
}
|
||||
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(data.title, options)
|
||||
);
|
||||
});
|
||||
)
|
||||
})
|
||||
|
||||
// 通知点击
|
||||
self.addEventListener('notificationclick', (event) => {
|
||||
console.log('[Service Worker] 通知被点击');
|
||||
event.notification.close();
|
||||
const urlToOpen = event.notification.data?.url || '/';
|
||||
console.log('[Service Worker] 通知被点击')
|
||||
event.notification.close()
|
||||
const urlToOpen = event.notification.data?.url || '/'
|
||||
event.waitUntil(
|
||||
clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
|
||||
// 如果已经打开了该 URL,则聚焦
|
||||
for (let i = 0; i < windowClients.length; i++) {
|
||||
const client = windowClients[i];
|
||||
const client = windowClients[i]
|
||||
if (client.url === urlToOpen && 'focus' in client) {
|
||||
return client.focus();
|
||||
return client.focus()
|
||||
}
|
||||
}
|
||||
// 否则打开新窗口
|
||||
if (clients.openWindow) {
|
||||
return clients.openWindow(urlToOpen);
|
||||
return clients.openWindow(urlToOpen)
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
)
|
||||
})
|
||||
|
||||
// 数据同步函数
|
||||
async function syncData() {
|
||||
async function syncData () {
|
||||
try {
|
||||
// 这里添加需要同步的逻辑
|
||||
console.log('[Service Worker] 执行数据同步');
|
||||
console.log('[Service Worker] 执行数据同步')
|
||||
} catch (error) {
|
||||
console.error('[Service Worker] 同步失败:', error);
|
||||
console.error('[Service Worker] 同步失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,68 @@
|
||||
<template>
|
||||
<van-config-provider :theme="theme" class="app-provider">
|
||||
<van-config-provider
|
||||
:theme="theme"
|
||||
class="app-provider"
|
||||
>
|
||||
<div class="app-root">
|
||||
<RouterView />
|
||||
<van-tabbar v-show="showTabbar" v-model="active">
|
||||
<van-tabbar-item name="ccalendar" icon="notes" to="/calendar">
|
||||
<van-tabbar
|
||||
v-show="showTabbar"
|
||||
v-model="active"
|
||||
>
|
||||
<van-tabbar-item
|
||||
name="ccalendar"
|
||||
icon="notes"
|
||||
to="/calendar"
|
||||
>
|
||||
日历
|
||||
</van-tabbar-item>
|
||||
<van-tabbar-item name="statistics" icon="chart-trending-o" to="/" @click="handleTabClick('/statistics')">
|
||||
<van-tabbar-item
|
||||
name="statistics"
|
||||
icon="chart-trending-o"
|
||||
to="/"
|
||||
@click="handleTabClick('/statistics')"
|
||||
>
|
||||
统计
|
||||
</van-tabbar-item>
|
||||
<van-tabbar-item
|
||||
name="balance"
|
||||
icon="balance-list"
|
||||
:to="messageStore.unreadCount > 0 ? '/balance?tab=message' : '/balance'"
|
||||
:badge="messageStore.unreadCount || null"
|
||||
<van-tabbar-item
|
||||
name="balance"
|
||||
icon="balance-list"
|
||||
:to="messageStore.unreadCount > 0 ? '/balance?tab=message' : '/balance'"
|
||||
:badge="messageStore.unreadCount || null"
|
||||
@click="handleTabClick('/balance')"
|
||||
>
|
||||
账单
|
||||
</van-tabbar-item>
|
||||
<van-tabbar-item name="budget" icon="bill-o" to="/budget" @click="handleTabClick('/budget')">
|
||||
<van-tabbar-item
|
||||
name="budget"
|
||||
icon="bill-o"
|
||||
to="/budget"
|
||||
@click="handleTabClick('/budget')"
|
||||
>
|
||||
预算
|
||||
</van-tabbar-item>
|
||||
<van-tabbar-item name="setting" icon="setting" to="/setting">
|
||||
<van-tabbar-item
|
||||
name="setting"
|
||||
icon="setting"
|
||||
to="/setting"
|
||||
>
|
||||
设置
|
||||
</van-tabbar-item>
|
||||
</van-tabbar>
|
||||
<GlobalAddBill v-if="isShowAddBill" @success="handleAddTransactionSuccess"/>
|
||||
|
||||
<div v-if="needRefresh" class="update-toast" @click="updateServiceWorker">
|
||||
<van-icon name="upgrade" class="update-icon" />
|
||||
<GlobalAddBill
|
||||
v-if="isShowAddBill"
|
||||
@success="handleAddTransactionSuccess"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="needRefresh"
|
||||
class="update-toast"
|
||||
@click="updateServiceWorker"
|
||||
>
|
||||
<van-icon
|
||||
name="upgrade"
|
||||
class="update-icon"
|
||||
/>
|
||||
<span>新版本可用,点击刷新</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -85,12 +119,14 @@ onUnmounted(() => {
|
||||
const route = useRoute()
|
||||
// 根据路由判断是否显示Tabbar
|
||||
const showTabbar = computed(() => {
|
||||
return route.path === '/' ||
|
||||
return (
|
||||
route.path === '/' ||
|
||||
route.path === '/calendar' ||
|
||||
route.path === '/message' ||
|
||||
route.path === '/setting' ||
|
||||
route.path === '/balance' ||
|
||||
route.path === '/budget'
|
||||
)
|
||||
})
|
||||
|
||||
const active = ref('')
|
||||
@@ -116,11 +152,14 @@ setInterval(() => {
|
||||
}, 60 * 1000) // 每60秒更新一次未读消息数
|
||||
|
||||
// 监听路由变化调整
|
||||
watch(() => route.path, (newPath) => {
|
||||
setActive(newPath)
|
||||
watch(
|
||||
() => route.path,
|
||||
(newPath) => {
|
||||
setActive(newPath)
|
||||
|
||||
messageStore.updateUnreadCount()
|
||||
})
|
||||
messageStore.updateUnreadCount()
|
||||
}
|
||||
)
|
||||
|
||||
const setActive = (path) => {
|
||||
active.value = (() => {
|
||||
@@ -138,14 +177,10 @@ const setActive = (path) => {
|
||||
return 'statistics'
|
||||
}
|
||||
})()
|
||||
console.log(active.value, path)
|
||||
}
|
||||
|
||||
const isShowAddBill = computed(() => {
|
||||
return route.path === '/'
|
||||
|| route.path === '/calendar'
|
||||
|| route.path === '/balance'
|
||||
|| route.path === '/message'
|
||||
return route.path === '/' || route.path === '/balance' || route.path === '/message' || route.path === '/calendar'
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
@@ -166,7 +201,6 @@ const handleAddTransactionSuccess = () => {
|
||||
const event = new Event('transactions-changed')
|
||||
window.dispatchEvent(event)
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
59
Web/src/api/AGENTS.md
Normal file
59
Web/src/api/AGENTS.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# API CLIENTS KNOWLEDGE BASE
|
||||
|
||||
**Generated:** 2026-01-28
|
||||
**Parent:** EmailBill/AGENTS.md
|
||||
|
||||
## OVERVIEW
|
||||
Axios-based HTTP client modules for backend API integration with request/response interceptors.
|
||||
|
||||
## STRUCTURE
|
||||
```
|
||||
Web/src/api/
|
||||
├── request.js # Base HTTP client setup
|
||||
├── auth.js # Authentication API
|
||||
├── budget.js # Budget management API
|
||||
├── transactionRecord.js # Transaction CRUD API
|
||||
├── transactionCategory.js # Category management
|
||||
├── transactionPeriodic.js # Periodic transactions
|
||||
├── statistics.js # Analytics API
|
||||
├── message.js # Message API
|
||||
├── notification.js # Push notifications
|
||||
├── emailRecord.js # Email records
|
||||
├── config.js # Configuration API
|
||||
├── billImport.js # Bill import
|
||||
├── log.js # Application logs
|
||||
└── job.js # Background job management
|
||||
```
|
||||
|
||||
## WHERE TO LOOK
|
||||
| Task | Location | Notes |
|
||||
|------|----------|-------|
|
||||
| Base HTTP setup | request.js | Axios interceptors, error handling |
|
||||
| Authentication | auth.js | Login, token management |
|
||||
| Budget data | budget.js | Budget CRUD, statistics |
|
||||
| Transactions | transactionRecord.js | Transaction operations |
|
||||
| Categories | transactionCategory.js | Category management |
|
||||
| Statistics | statistics.js | Analytics, reports |
|
||||
| Notifications | notification.js | Push subscription handling |
|
||||
|
||||
## CONVENTIONS
|
||||
- All functions return Promises with async/await
|
||||
- Error handling via try/catch with user messages
|
||||
- HTTP methods: get, post, put, delete mapping to REST
|
||||
- Request/response data transformation
|
||||
- Token-based authentication via headers
|
||||
- Consistent error message format
|
||||
|
||||
## ANTI-PATTERNS (THIS LAYER)
|
||||
- Never fetch directly without going through these modules
|
||||
- Don't hardcode API endpoints (use environment variables)
|
||||
- Avoid synchronous operations
|
||||
- Don't duplicate request logic across components
|
||||
- No business logic in API clients
|
||||
|
||||
## UNIQUE STYLES
|
||||
- Chinese error messages for user feedback
|
||||
- Automatic token refresh handling
|
||||
- Request/response logging for debugging
|
||||
- Paged query patterns for list endpoints
|
||||
- File upload handling for imports
|
||||
@@ -26,45 +26,47 @@ export const uploadBillFile = (file, type) => {
|
||||
Authorization: `Bearer ${useAuthStore().token || ''}`
|
||||
},
|
||||
timeout: 60000 // 文件上传增加超时时间
|
||||
}).then(response => {
|
||||
const { data } = response
|
||||
|
||||
if (data.success === false) {
|
||||
showToast(data.message || '上传失败')
|
||||
return Promise.reject(new Error(data.message || '上传失败'))
|
||||
}
|
||||
|
||||
return data
|
||||
}).catch(error => {
|
||||
console.error('上传错误:', error)
|
||||
|
||||
if (error.response) {
|
||||
const { status, data } = error.response
|
||||
let message = '上传失败'
|
||||
|
||||
switch (status) {
|
||||
case 400:
|
||||
message = data?.message || '请求参数错误'
|
||||
break
|
||||
case 401:
|
||||
message = '未授权,请先登录'
|
||||
break
|
||||
case 403:
|
||||
message = '没有权限'
|
||||
break
|
||||
case 413:
|
||||
message = '文件过大'
|
||||
break
|
||||
case 500:
|
||||
message = '服务器错误'
|
||||
break
|
||||
}
|
||||
|
||||
showToast(message)
|
||||
return Promise.reject(new Error(message))
|
||||
}
|
||||
|
||||
showToast('网络错误,请检查网络连接')
|
||||
return Promise.reject(error)
|
||||
})
|
||||
.then((response) => {
|
||||
const { data } = response
|
||||
|
||||
if (data.success === false) {
|
||||
showToast(data.message || '上传失败')
|
||||
return Promise.reject(new Error(data.message || '上传失败'))
|
||||
}
|
||||
|
||||
return data
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('上传错误:', error)
|
||||
|
||||
if (error.response) {
|
||||
const { status, data } = error.response
|
||||
let message = '上传失败'
|
||||
|
||||
switch (status) {
|
||||
case 400:
|
||||
message = data?.message || '请求参数错误'
|
||||
break
|
||||
case 401:
|
||||
message = '未授权,请先登录'
|
||||
break
|
||||
case 403:
|
||||
message = '没有权限'
|
||||
break
|
||||
case 413:
|
||||
message = '文件过大'
|
||||
break
|
||||
case 500:
|
||||
message = '服务器错误'
|
||||
break
|
||||
}
|
||||
|
||||
showToast(message)
|
||||
return Promise.reject(new Error(message))
|
||||
}
|
||||
|
||||
showToast('网络错误,请检查网络连接')
|
||||
return Promise.reject(error)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 获取预算列表
|
||||
* @param {string} referenceDate 参考日期 (可选)
|
||||
*/
|
||||
export function getBudgetList(referenceDate) {
|
||||
export function getBudgetList (referenceDate) {
|
||||
return request({
|
||||
url: '/Budget/GetList',
|
||||
method: 'get',
|
||||
@@ -12,24 +12,11 @@ export function getBudgetList(referenceDate) {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个预算统计
|
||||
* @param {number} id 预算ID
|
||||
* @param {string} referenceDate 参考日期
|
||||
*/
|
||||
export function getBudgetStatistics(id, referenceDate) {
|
||||
return request({
|
||||
url: '/Budget/GetStatistics',
|
||||
method: 'get',
|
||||
params: { id, referenceDate }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建预算
|
||||
* @param {object} data 预算数据
|
||||
*/
|
||||
export function createBudget(data) {
|
||||
export function createBudget (data) {
|
||||
return request({
|
||||
url: '/Budget/Create',
|
||||
method: 'post',
|
||||
@@ -41,7 +28,7 @@ export function createBudget(data) {
|
||||
* 更新预算
|
||||
* @param {object} data 预算数据
|
||||
*/
|
||||
export function updateBudget(data) {
|
||||
export function updateBudget (data) {
|
||||
return request({
|
||||
url: '/Budget/Update',
|
||||
method: 'post',
|
||||
@@ -53,7 +40,7 @@ export function updateBudget(data) {
|
||||
* 删除预算
|
||||
* @param {number} id 预算ID
|
||||
*/
|
||||
export function deleteBudget(id) {
|
||||
export function deleteBudget (id) {
|
||||
return request({
|
||||
url: `/Budget/DeleteById/${id}`,
|
||||
method: 'delete'
|
||||
@@ -65,7 +52,7 @@ export function deleteBudget(id) {
|
||||
* @param {string} category 分类 (Expense/Income/Savings)
|
||||
* @param {string} referenceDate 参考日期 (可选)
|
||||
*/
|
||||
export function getCategoryStats(category, referenceDate) {
|
||||
export function getCategoryStats (category, referenceDate) {
|
||||
return request({
|
||||
url: '/Budget/GetCategoryStats',
|
||||
method: 'get',
|
||||
@@ -77,22 +64,48 @@ export function getCategoryStats(category, referenceDate) {
|
||||
* @param {number} category 预算分类
|
||||
* @param {string} referenceDate 参考日期
|
||||
*/
|
||||
export function getUncoveredCategories(category, referenceDate) {
|
||||
export function getUncoveredCategories (category, referenceDate) {
|
||||
return request({
|
||||
url: '/Budget/GetUncoveredCategories',
|
||||
method: 'get',
|
||||
params: { category, referenceDate }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 归档预算
|
||||
* @param {number} year 年份
|
||||
* @param {number} month 月份
|
||||
* 获取归档总结
|
||||
* @param {string} referenceDate 参考日期
|
||||
*/
|
||||
export function archiveBudgets(year, month) {
|
||||
export function getArchiveSummary (referenceDate) {
|
||||
return request({
|
||||
url: `/Budget/ArchiveBudgetsAsync/${year}/${month}`,
|
||||
method: 'post'
|
||||
url: '/Budget/GetArchiveSummary',
|
||||
method: 'get',
|
||||
params: { referenceDate }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新归档总结
|
||||
* @param {object} data 数据 { referenceDate, summary }
|
||||
*/
|
||||
export function updateArchiveSummary (data) {
|
||||
return request({
|
||||
url: '/Budget/UpdateArchiveSummary',
|
||||
method: 'post',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定周期的存款预算信息
|
||||
* @param {number} year 年份
|
||||
* @param {number} month 月份
|
||||
* @param {number} type 周期类型 (1:Month, 2:Year)
|
||||
*/
|
||||
export function getSavingsBudget (year, month, type) {
|
||||
return request({
|
||||
url: '/Budget/GetSavingsBudget',
|
||||
method: 'get',
|
||||
params: { year, month, type }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ export const getEmailDetail = (id) => {
|
||||
*/
|
||||
export const deleteEmail = (id) => {
|
||||
return request({
|
||||
url: `/EmailMessage/DeleteById`,
|
||||
url: '/EmailMessage/DeleteById',
|
||||
method: 'post',
|
||||
params: { id }
|
||||
})
|
||||
@@ -50,7 +50,7 @@ export const deleteEmail = (id) => {
|
||||
*/
|
||||
export const refreshTransactionRecords = (id) => {
|
||||
return request({
|
||||
url: `/EmailMessage/RefreshTransactionRecords`,
|
||||
url: '/EmailMessage/RefreshTransactionRecords',
|
||||
method: 'post',
|
||||
params: { id }
|
||||
})
|
||||
@@ -62,7 +62,7 @@ export const refreshTransactionRecords = (id) => {
|
||||
*/
|
||||
export const syncEmails = () => {
|
||||
return request({
|
||||
url: `/EmailMessage/SyncEmails`,
|
||||
url: '/EmailMessage/SyncEmails',
|
||||
method: 'post'
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import request from '@/api/request'
|
||||
|
||||
export function getJobs() {
|
||||
export function getJobs () {
|
||||
return request({
|
||||
url: '/Job/GetJobs',
|
||||
method: 'get'
|
||||
})
|
||||
}
|
||||
|
||||
export function executeJob(jobName) {
|
||||
export function executeJob (jobName) {
|
||||
return request({
|
||||
url: '/Job/Execute',
|
||||
method: 'post',
|
||||
@@ -15,7 +15,7 @@ export function executeJob(jobName) {
|
||||
})
|
||||
}
|
||||
|
||||
export function pauseJob(jobName) {
|
||||
export function pauseJob (jobName) {
|
||||
return request({
|
||||
url: '/Job/Pause',
|
||||
method: 'post',
|
||||
@@ -23,7 +23,7 @@ export function pauseJob(jobName) {
|
||||
})
|
||||
}
|
||||
|
||||
export function resumeJob(jobName) {
|
||||
export function resumeJob (jobName) {
|
||||
return request({
|
||||
url: '/Job/Resume',
|
||||
method: 'post',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import request from './request'
|
||||
import request from './request'
|
||||
|
||||
/**
|
||||
* 日志相关 API
|
||||
@@ -12,6 +12,7 @@
|
||||
* @param {string} [params.searchKeyword] - 搜索关键词
|
||||
* @param {string} [params.logLevel] - 日志级别
|
||||
* @param {string} [params.date] - 日期 (yyyyMMdd)
|
||||
* @param {string} [params.className] - 类名
|
||||
* @returns {Promise<{success: boolean, data: Array, total: number}>}
|
||||
*/
|
||||
export const getLogList = (params = {}) => {
|
||||
@@ -32,3 +33,34 @@ export const getAvailableDates = () => {
|
||||
method: 'get'
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取可用的类名列表
|
||||
* @param {Object} params - 查询参数
|
||||
* @param {string} [params.date] - 日期 (yyyyMMdd)
|
||||
* @returns {Promise<{success: boolean, data: Array}>}
|
||||
*/
|
||||
export const getAvailableClassNames = (params = {}) => {
|
||||
return request({
|
||||
url: '/Log/GetAvailableClassNames',
|
||||
method: 'get',
|
||||
params
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据请求ID查询关联日志
|
||||
* @param {Object} params - 查询参数
|
||||
* @param {string} params.requestId - 请求ID
|
||||
* @param {number} [params.pageIndex=1] - 页码
|
||||
* @param {number} [params.pageSize=50] - 每页条数
|
||||
* @param {string} [params.date] - 日期 (yyyyMMdd)
|
||||
* @returns {Promise<{success: boolean, data: Array, total: number}>}
|
||||
*/
|
||||
export const getLogsByRequestId = (params = {}) => {
|
||||
return request({
|
||||
url: '/Log/GetLogsByRequestId',
|
||||
method: 'get',
|
||||
params
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import request from './request'
|
||||
|
||||
export function getVapidPublicKey() {
|
||||
export function getVapidPublicKey () {
|
||||
return request({
|
||||
url: '/Notification/GetVapidPublicKey',
|
||||
method: 'get'
|
||||
})
|
||||
}
|
||||
|
||||
export function subscribe(data) {
|
||||
export function subscribe (data) {
|
||||
return request({
|
||||
url: '/Notification/Subscribe',
|
||||
method: 'post',
|
||||
@@ -15,7 +15,7 @@ export function subscribe(data) {
|
||||
})
|
||||
}
|
||||
|
||||
export function testNotification(message) {
|
||||
export function testNotification (message) {
|
||||
return request({
|
||||
url: '/Notification/TestNotification',
|
||||
method: 'post',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import axios from 'axios'
|
||||
import axios from 'axios'
|
||||
import { showToast } from 'vant'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import router from '@/router'
|
||||
@@ -12,17 +12,31 @@ const request = axios.create({
|
||||
}
|
||||
})
|
||||
|
||||
// 生成请求ID
|
||||
const generateRequestId = () => {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
||||
const r = Math.random() * 16 | 0
|
||||
const v = c === 'x' ? r : (r & 0x3 | 0x8)
|
||||
return v.toString(16)
|
||||
})
|
||||
}
|
||||
|
||||
// 请求拦截器
|
||||
request.interceptors.request.use(
|
||||
config => {
|
||||
(config) => {
|
||||
// 添加 token 认证信息
|
||||
const authStore = useAuthStore()
|
||||
if (authStore.token) {
|
||||
config.headers.Authorization = `Bearer ${authStore.token}`
|
||||
}
|
||||
|
||||
// 添加请求ID
|
||||
const requestId = generateRequestId()
|
||||
config.headers['X-Request-ID'] = requestId
|
||||
|
||||
return config
|
||||
},
|
||||
error => {
|
||||
(error) => {
|
||||
console.error('请求错误:', error)
|
||||
return Promise.reject(error)
|
||||
}
|
||||
@@ -30,25 +44,25 @@ request.interceptors.request.use(
|
||||
|
||||
// 响应拦截器
|
||||
request.interceptors.response.use(
|
||||
response => {
|
||||
(response) => {
|
||||
const { data } = response
|
||||
|
||||
|
||||
// 统一处理业务错误
|
||||
if (data.success === false) {
|
||||
showToast(data.message || '请求失败')
|
||||
return Promise.reject(new Error(data.message || '请求失败'))
|
||||
}
|
||||
|
||||
|
||||
return data
|
||||
},
|
||||
error => {
|
||||
(error) => {
|
||||
console.error('响应错误:', error)
|
||||
|
||||
|
||||
// 统一处理 HTTP 错误
|
||||
if (error.response) {
|
||||
const { status, data } = error.response
|
||||
let message = '请求失败'
|
||||
|
||||
|
||||
switch (status) {
|
||||
case 400:
|
||||
message = data?.message || '请求参数错误'
|
||||
@@ -58,7 +72,10 @@ request.interceptors.response.use(
|
||||
// 清除登录状态并跳转到登录页
|
||||
const authStore = useAuthStore()
|
||||
authStore.logout()
|
||||
router.push({ name: 'login', query: { redirect: router.currentRoute.value.fullPath } })
|
||||
router.push({
|
||||
name: 'login',
|
||||
query: { redirect: router.currentRoute.value.fullPath }
|
||||
})
|
||||
break
|
||||
}
|
||||
case 403:
|
||||
@@ -73,14 +90,14 @@ request.interceptors.response.use(
|
||||
default:
|
||||
message = data?.message || `请求失败 (${status})`
|
||||
}
|
||||
|
||||
|
||||
showToast(message)
|
||||
} else if (error.request) {
|
||||
showToast('网络连接失败,请检查网络')
|
||||
} else {
|
||||
showToast(error.message || '请求失败')
|
||||
}
|
||||
|
||||
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import request from './request'
|
||||
import request from './request'
|
||||
|
||||
/**
|
||||
* 统计相关 API
|
||||
@@ -17,8 +17,6 @@
|
||||
* @returns {Object} data.expenseCount - 支出笔数
|
||||
* @returns {Object} data.incomeCount - 收入笔数
|
||||
* @returns {Object} data.totalCount - 总笔数
|
||||
* @returns {Object} data.maxExpense - 最大单笔支出
|
||||
* @returns {Object} data.maxIncome - 最大单笔收入
|
||||
*/
|
||||
export const getMonthlyStatistics = (params) => {
|
||||
return request({
|
||||
@@ -88,3 +86,21 @@ export const getDailyStatistics = (params) => {
|
||||
params
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取累积余额统计数据(用于余额卡片)
|
||||
* @param {Object} params - 查询参数
|
||||
* @param {number} params.year - 年份
|
||||
* @param {number} params.month - 月份
|
||||
* @returns {Promise<{success: boolean, data: Array}>}
|
||||
* @returns {Array} data - 每日累积余额列表
|
||||
* @returns {string} data[].date - 日期
|
||||
* @returns {number} data[].cumulativeBalance - 累积余额
|
||||
*/
|
||||
export const getBalanceStatistics = (params) => {
|
||||
return request({
|
||||
url: '/TransactionRecord/GetBalanceStatistics',
|
||||
method: 'get',
|
||||
params
|
||||
})
|
||||
}
|
||||
|
||||
@@ -76,3 +76,30 @@ export const batchCreateCategories = (dataList) => {
|
||||
data: dataList
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 为指定分类生成新的SVG图标
|
||||
* @param {number} categoryId - 分类ID
|
||||
* @returns {Promise<{success: boolean, data: string}>} 返回生成的SVG内容
|
||||
*/
|
||||
export const generateIcon = (categoryId) => {
|
||||
return request({
|
||||
url: '/TransactionCategory/GenerateIcon',
|
||||
method: 'post',
|
||||
data: { categoryId }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新分类的选中图标索引
|
||||
* @param {number} categoryId - 分类ID
|
||||
* @param {number} selectedIndex - 选中的图标索引
|
||||
* @returns {Promise<{success: boolean}>}
|
||||
*/
|
||||
export const updateSelectedIcon = (categoryId, selectedIndex) => {
|
||||
return request({
|
||||
url: '/TransactionCategory/UpdateSelectedIcon',
|
||||
method: 'post',
|
||||
data: { categoryId, selectedIndex }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ export const updatePeriodic = (data) => {
|
||||
*/
|
||||
export const deletePeriodic = (id) => {
|
||||
return request({
|
||||
url: `/TransactionPeriodic/DeleteById`,
|
||||
url: '/TransactionPeriodic/DeleteById',
|
||||
method: 'post',
|
||||
params: { id }
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import request from './request'
|
||||
import request from './request'
|
||||
|
||||
/**
|
||||
* 交易记录相关 API
|
||||
@@ -82,6 +82,7 @@ export const createTransaction = (data) => {
|
||||
* @param {number} data.balance - 交易后余额
|
||||
* @param {number} data.type - 交易类型 (0:支出, 1:收入, 2:不计入收支)
|
||||
* @param {string} data.classify - 交易分类
|
||||
* @param {string} [data.occurredAt] - 交易时间
|
||||
* @returns {Promise<{success: boolean}>}
|
||||
*/
|
||||
export const updateTransaction = (data) => {
|
||||
@@ -99,7 +100,7 @@ export const updateTransaction = (data) => {
|
||||
*/
|
||||
export const deleteTransaction = (id) => {
|
||||
return request({
|
||||
url: `/TransactionRecord/DeleteById`,
|
||||
url: '/TransactionRecord/DeleteById',
|
||||
method: 'post',
|
||||
params: { id }
|
||||
})
|
||||
@@ -118,7 +119,6 @@ export const getTransactionsByDate = (date) => {
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// 注意:分类相关的API已迁移到 transactionCategory.js
|
||||
// 请使用 getCategoryList 等新接口
|
||||
|
||||
@@ -155,12 +155,12 @@ export const smartClassify = (transactionIds = []) => {
|
||||
const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5071/api'
|
||||
const token = localStorage.getItem('token')
|
||||
const url = `${baseURL}/TransactionRecord/SmartClassify`
|
||||
|
||||
|
||||
return fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ transactionIds })
|
||||
})
|
||||
@@ -224,32 +224,6 @@ export const nlpAnalysis = (userInput) => {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取抵账候选列表
|
||||
* @param {number} id - 当前交易ID
|
||||
* @returns {Promise<{success: boolean, data: Array}>}
|
||||
*/
|
||||
export const getCandidatesForOffset = (id) => {
|
||||
return request({
|
||||
url: `/TransactionRecord/GetCandidatesForOffset/${id}`,
|
||||
method: 'get'
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 抵账(删除两笔交易)
|
||||
* @param {number} id1 - 交易ID 1
|
||||
* @param {number} id2 - 交易ID 2
|
||||
* @returns {Promise<{success: boolean}>}
|
||||
*/
|
||||
export const offsetTransactions = (id1, id2) => {
|
||||
return request({
|
||||
url: '/TransactionRecord/OffsetTransactions',
|
||||
method: 'post',
|
||||
data: { id1, id2 }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 一句话录账解析
|
||||
* @param {string} text - 用户输入的自然语言文本
|
||||
@@ -261,4 +235,4 @@ export const parseOneLine = (text) => {
|
||||
method: 'post',
|
||||
data: { text }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,55 +1,75 @@
|
||||
/* color palette from <https://github.com/vuejs/theme> */
|
||||
/* color palette from <https://github.com/vuejs/theme> */
|
||||
/*
|
||||
Most variables are replaced by Vant CSS variables.
|
||||
Keeping only what's necessary or mapping to Vant.
|
||||
*/
|
||||
|
||||
:root {
|
||||
--vt-c-white: #ffffff;
|
||||
--vt-c-white-soft: #f8f8f8;
|
||||
--vt-c-white-mute: #f2f2f2;
|
||||
--van-danger-color: rgb(255, 107, 107) !important; /* 覆盖默认的深红色 #ee0a24 */
|
||||
--color-background: var(--van-background);
|
||||
--color-background-soft: var(--van-background-2);
|
||||
--color-background-mute: var(--van-gray-1);
|
||||
|
||||
--vt-c-black: #181818;
|
||||
--vt-c-black-soft: #222222;
|
||||
--vt-c-black-mute: #282828;
|
||||
--color-border: var(--van-border-color);
|
||||
--color-border-hover: var(--van-gray-5);
|
||||
|
||||
--vt-c-indigo: #2c3e50;
|
||||
|
||||
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
|
||||
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
|
||||
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
|
||||
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
|
||||
|
||||
--vt-c-text-light-1: var(--vt-c-indigo);
|
||||
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
|
||||
--vt-c-text-dark-1: var(--vt-c-white);
|
||||
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
|
||||
}
|
||||
|
||||
/* semantic color variables for this project */
|
||||
:root {
|
||||
--color-background: var(--vt-c-white);
|
||||
--color-background-soft: var(--vt-c-white-soft);
|
||||
--color-background-mute: var(--vt-c-white-mute);
|
||||
|
||||
--color-border: var(--vt-c-divider-light-2);
|
||||
--color-border-hover: var(--vt-c-divider-light-1);
|
||||
|
||||
--color-heading: var(--vt-c-text-light-1);
|
||||
--color-text: var(--vt-c-text-light-1);
|
||||
--color-heading: var(--van-text-color);
|
||||
--color-text: var(--van-text-color);
|
||||
|
||||
--section-gap: 160px;
|
||||
|
||||
/* Chart Colors */
|
||||
--chart-color-1: #ff6b6b;
|
||||
--chart-color-2: #4ecdc4;
|
||||
--chart-color-3: #45b7d1;
|
||||
--chart-color-4: #ffa07a;
|
||||
--chart-color-5: #98d8c8;
|
||||
--chart-color-6: #f7dc6f;
|
||||
--chart-color-7: #bb8fce;
|
||||
--chart-color-8: #85c1e2;
|
||||
--chart-color-9: #f8b88b;
|
||||
--chart-color-10: #aab7b8;
|
||||
--chart-color-11: #ff8ed4;
|
||||
--chart-color-12: #67e6dc;
|
||||
--chart-color-13: #5b8dee;
|
||||
--chart-color-14: #c9b1ff;
|
||||
--chart-color-15: #7bdff2;
|
||||
|
||||
/* Status Colors for Charts */
|
||||
--chart-success: #52c41a;
|
||||
--chart-warning: #faad14;
|
||||
--chart-danger: #f5222d;
|
||||
--chart-primary: #1890ff;
|
||||
--chart-shadow: rgba(0, 138, 255, 0.45);
|
||||
--chart-axis: #e6ebf8;
|
||||
--chart-split: #eee;
|
||||
--chart-text-muted: #999;
|
||||
|
||||
/* Heatmap Colors - Light Mode */
|
||||
--heatmap-level-0: var(--van-gray-2);
|
||||
--heatmap-level-1: #9be9a8;
|
||||
--heatmap-level-2: #40c463;
|
||||
--heatmap-level-3: #30a14e;
|
||||
--heatmap-level-4: #216e39;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--color-background: var(--vt-c-black);
|
||||
--color-background-soft: var(--vt-c-black-soft);
|
||||
--color-background-mute: var(--vt-c-black-mute);
|
||||
--chart-axis: #333;
|
||||
--chart-split: #333;
|
||||
--chart-text-muted: #666;
|
||||
|
||||
--color-border: var(--vt-c-divider-dark-2);
|
||||
--color-border-hover: var(--vt-c-divider-dark-1);
|
||||
|
||||
--color-heading: var(--vt-c-text-dark-1);
|
||||
--color-text: var(--vt-c-text-dark-2);
|
||||
/* Heatmap Colors - Dark Mode (GitHub Style) */
|
||||
--heatmap-level-0: var(--van-gray-2);
|
||||
--heatmap-level-1: #9be9a8;
|
||||
--heatmap-level-2: #40c463;
|
||||
--heatmap-level-3: #30a14e;
|
||||
--heatmap-level-4: #216e39;
|
||||
}
|
||||
}
|
||||
|
||||
/* Removed manual dark mode media query as Vant handles it */
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
@@ -60,14 +80,13 @@
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
color: var(--color-text);
|
||||
background: var(--color-background);
|
||||
color: var(--van-text-color);
|
||||
background: var(--van-background);
|
||||
transition:
|
||||
color 0.5s,
|
||||
background-color 0.5s;
|
||||
line-height: 1.6;
|
||||
font-family:
|
||||
Inter,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
'Segoe UI',
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
@import './base.css';
|
||||
|
||||
/* 禁用页面弹性缩放和橡皮筋效果 */
|
||||
html, body {
|
||||
html,
|
||||
body {
|
||||
overscroll-behavior: none;
|
||||
overscroll-behavior-y: none;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
@@ -57,8 +58,10 @@ a,
|
||||
}
|
||||
}
|
||||
|
||||
html, body, #app {
|
||||
html,
|
||||
body,
|
||||
#app {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
184
Web/src/assets/theme.css
Normal file
184
Web/src/assets/theme.css
Normal file
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* EmailBill 主题系统 - 根据 v2.pen 设计稿
|
||||
* 用于保持整个应用色彩和布局一致性
|
||||
*/
|
||||
|
||||
:root {
|
||||
/* ============ 颜色变量 - 浅色主题 ============ */
|
||||
|
||||
/* 背景色 */
|
||||
--bg-primary: #FFFFFF;
|
||||
--bg-secondary: #F6F7F8;
|
||||
--bg-tertiary: #F3F4F6;
|
||||
--bg-button: #F5F5F5;
|
||||
|
||||
/* 文字颜色 */
|
||||
--text-primary: #1A1A1A;
|
||||
--text-secondary: #6B7280;
|
||||
--text-tertiary: #9CA3AF;
|
||||
|
||||
/* 强调色 */
|
||||
--accent-primary: #FF6B6B;
|
||||
--accent-danger: #EF4444;
|
||||
--accent-warning: #D97706;
|
||||
--accent-warning-bg: #FFFBEB;
|
||||
--accent-success: #22C55E;
|
||||
--accent-success-bg: #F0FDF4;
|
||||
--accent-info: #6366F1;
|
||||
--accent-info-bg: #E0E7FF;
|
||||
|
||||
/* 图标色 */
|
||||
--icon-star: #FF6B6B;
|
||||
--icon-coffee: #FCD34D;
|
||||
|
||||
/* ============ 布局变量 ============ */
|
||||
|
||||
/* 间距 */
|
||||
--spacing-xs: 2px;
|
||||
--spacing-sm: 4px;
|
||||
--spacing-md: 8px
|
||||
--spacing-lg: 12px;
|
||||
--spacing-xl: 16px;
|
||||
--spacing-2xl: 20px;
|
||||
--spacing-3xl: 24px;
|
||||
|
||||
/* 圆角 */
|
||||
--radius-sm: 12px;
|
||||
--radius-md: 16px;
|
||||
--radius-lg: 20px;
|
||||
--radius-full: 22px;
|
||||
|
||||
/* 字体大小 */
|
||||
--font-xs: 9px;
|
||||
--font-sm: 11px;
|
||||
--font-base: 12px;
|
||||
--font-md: 13px;
|
||||
--font-lg: 15px;
|
||||
--font-xl: 18px;
|
||||
--font-2xl: 24px;
|
||||
--font-3xl: 32px;
|
||||
|
||||
/* 字体粗细 */
|
||||
--font-medium: 500;
|
||||
--font-semibold: 600;
|
||||
--font-bold: 700;
|
||||
--font-extrabold: 800;
|
||||
|
||||
/* 字体 */
|
||||
--font-primary: 'DM Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
--font-display: 'Bricolage Grotesque', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
|
||||
/* 阴影 (可选) */
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
--shadow-md: 0 4px 6px rgba(0, 0, 0, 0.05);
|
||||
--shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
/* ============ 深色主题 ============ */
|
||||
[data-theme="dark"] {
|
||||
/* 背景色 */
|
||||
--bg-primary: #09090B;
|
||||
--bg-secondary: #18181b;
|
||||
--bg-tertiary: #27272a;
|
||||
--bg-button: #27272a;
|
||||
|
||||
/* 文字颜色 */
|
||||
--text-primary: #f4f4f5;
|
||||
--text-secondary: #a1a1aa;
|
||||
--text-tertiary: #71717a;
|
||||
|
||||
/* 强调色 (深色主题调整) */
|
||||
--accent-primary: #FF6B6B;
|
||||
--accent-danger: #f87171;
|
||||
--accent-warning: #fbbf24;
|
||||
--accent-warning-bg: #451a03;
|
||||
--accent-success: #4ade80;
|
||||
--accent-success-bg: #064e3b;
|
||||
--accent-info: #818cf8;
|
||||
--accent-info-bg: #312e81;
|
||||
|
||||
/* 图标色 (深色主题) */
|
||||
--icon-star: #FF6B6B;
|
||||
--icon-coffee: #FCD34D;
|
||||
}
|
||||
|
||||
/* ============ 通用工具类 ============ */
|
||||
|
||||
/* 文字 */
|
||||
.text-primary {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.text-secondary {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.text-tertiary {
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.text-danger {
|
||||
color: var(--accent-danger);
|
||||
}
|
||||
|
||||
/* 背景 */
|
||||
.bg-primary {
|
||||
background-color: var(--bg-primary);
|
||||
}
|
||||
|
||||
.bg-secondary {
|
||||
background-color: var(--bg-secondary);
|
||||
}
|
||||
|
||||
.bg-tertiary {
|
||||
background-color: var(--bg-tertiary);
|
||||
}
|
||||
|
||||
/* 布局容器 */
|
||||
.container-fluid {
|
||||
width: 100%;
|
||||
max-width: 402px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* Flex 布局 */
|
||||
.flex {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.flex-col {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.items-center {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.justify-between {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.justify-center {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* 间距 */
|
||||
.gap-xs { gap: var(--spacing-xs); }
|
||||
.gap-sm { gap: var(--spacing-sm); }
|
||||
.gap-md { gap: var(--spacing-md); }
|
||||
.gap-lg { gap: var(--spacing-lg); }
|
||||
.gap-xl { gap: var(--spacing-xl); }
|
||||
.gap-2xl { gap: var(--spacing-2xl); }
|
||||
.gap-3xl { gap: var(--spacing-3xl); }
|
||||
|
||||
/* 内边距 */
|
||||
.p-sm { padding: var(--spacing-md); }
|
||||
.p-md { padding: var(--spacing-xl); }
|
||||
.p-lg { padding: var(--spacing-2xl); }
|
||||
.p-xl { padding: var(--spacing-3xl); }
|
||||
|
||||
/* 圆角 */
|
||||
.rounded-sm { border-radius: var(--radius-sm); }
|
||||
.rounded-md { border-radius: var(--radius-md); }
|
||||
.rounded-lg { border-radius: var(--radius-lg); }
|
||||
.rounded-full { border-radius: var(--radius-full); }
|
||||
@@ -1,11 +1,14 @@
|
||||
<template>
|
||||
<van-dialog
|
||||
v-model:show="show"
|
||||
title="新增交易分类"
|
||||
<van-dialog
|
||||
v-model:show="show"
|
||||
title="新增交易分类"
|
||||
show-cancel-button
|
||||
@confirm="handleConfirm"
|
||||
>
|
||||
<van-field v-model="classifyName" placeholder="请输入新的交易分类" />
|
||||
<van-field
|
||||
v-model="classifyName"
|
||||
placeholder="请输入新的交易分类"
|
||||
/>
|
||||
</van-dialog>
|
||||
</template>
|
||||
|
||||
@@ -30,7 +33,7 @@ const handleConfirm = () => {
|
||||
showToast('请输入分类名称')
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
emit('confirm', classifyName.value.trim())
|
||||
show.value = false
|
||||
classifyName.value = ''
|
||||
|
||||
@@ -6,8 +6,12 @@
|
||||
<van-field label="时间">
|
||||
<template #input>
|
||||
<div style="display: flex; gap: 16px">
|
||||
<div @click="showDatePicker = true">{{ form.date }}</div>
|
||||
<div @click="showTimePicker = true">{{ form.time }}</div>
|
||||
<div @click="showDatePicker = true">
|
||||
{{ form.date }}
|
||||
</div>
|
||||
<div @click="showTimePicker = true">
|
||||
{{ form.time }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</van-field>
|
||||
@@ -34,24 +38,43 @@
|
||||
/>
|
||||
|
||||
<!-- 交易类型 -->
|
||||
<van-field name="type" label="类型">
|
||||
<van-field
|
||||
name="type"
|
||||
label="类型"
|
||||
>
|
||||
<template #input>
|
||||
<van-radio-group v-model="form.type" direction="horizontal" @change="handleTypeChange">
|
||||
<van-radio :name="0">支出</van-radio>
|
||||
<van-radio :name="1">收入</van-radio>
|
||||
<van-radio :name="2">不计</van-radio>
|
||||
<van-radio-group
|
||||
v-model="form.type"
|
||||
direction="horizontal"
|
||||
@change="handleTypeChange"
|
||||
>
|
||||
<van-radio :name="0">
|
||||
支出
|
||||
</van-radio>
|
||||
<van-radio :name="1">
|
||||
收入
|
||||
</van-radio>
|
||||
<van-radio :name="2">
|
||||
不计
|
||||
</van-radio>
|
||||
</van-radio-group>
|
||||
</template>
|
||||
</van-field>
|
||||
|
||||
<!-- 分类 -->
|
||||
<van-field name="category" label="分类">
|
||||
<van-field
|
||||
name="category"
|
||||
label="分类"
|
||||
>
|
||||
<template #input>
|
||||
<span v-if="!categoryName" style="color: #c8c9cc;">请选择分类</span>
|
||||
<span
|
||||
v-if="!categoryName"
|
||||
style="color: var(--van-text-color-3)"
|
||||
>请选择分类</span>
|
||||
<span v-else>{{ categoryName }}</span>
|
||||
</template>
|
||||
</van-field>
|
||||
|
||||
|
||||
<!-- 分类选择组件 -->
|
||||
<ClassifySelector
|
||||
v-model="categoryName"
|
||||
@@ -60,15 +83,26 @@
|
||||
</van-cell-group>
|
||||
|
||||
<div class="actions">
|
||||
<van-button round block type="primary" native-type="submit" :loading="loading">
|
||||
<van-button
|
||||
round
|
||||
block
|
||||
type="primary"
|
||||
native-type="submit"
|
||||
:loading="loading"
|
||||
>
|
||||
{{ submitText }}
|
||||
</van-button>
|
||||
<slot name="actions"></slot>
|
||||
<slot name="actions" />
|
||||
</div>
|
||||
</van-form>
|
||||
|
||||
<!-- 日期选择弹窗 -->
|
||||
<van-popup v-model:show="showDatePicker" position="bottom" round teleport="body">
|
||||
<van-popup
|
||||
v-model:show="showDatePicker"
|
||||
position="bottom"
|
||||
round
|
||||
teleport="body"
|
||||
>
|
||||
<van-date-picker
|
||||
v-model="currentDate"
|
||||
title="选择日期"
|
||||
@@ -78,7 +112,12 @@
|
||||
</van-popup>
|
||||
|
||||
<!-- 时间选择弹窗 -->
|
||||
<van-popup v-model:show="showTimePicker" position="bottom" round teleport="body">
|
||||
<van-popup
|
||||
v-model:show="showTimePicker"
|
||||
position="bottom"
|
||||
round
|
||||
teleport="body"
|
||||
>
|
||||
<van-time-picker
|
||||
v-model="currentTime"
|
||||
title="选择时间"
|
||||
@@ -137,7 +176,7 @@ const initForm = async () => {
|
||||
if (props.initialData) {
|
||||
isSyncing.value = true
|
||||
const { occurredAt, amount, reason, type, classify } = props.initialData
|
||||
|
||||
|
||||
if (occurredAt) {
|
||||
const dt = dayjs(occurredAt)
|
||||
form.value.date = dt.format('YYYY-MM-DD')
|
||||
@@ -145,11 +184,17 @@ const initForm = async () => {
|
||||
currentDate.value = form.value.date.split('-')
|
||||
currentTime.value = form.value.time.split(':')
|
||||
}
|
||||
|
||||
if (amount !== undefined) form.value.amount = amount
|
||||
if (reason !== undefined) form.value.note = reason
|
||||
if (type !== undefined) form.value.type = type
|
||||
|
||||
|
||||
if (amount !== undefined) {
|
||||
form.value.amount = amount
|
||||
}
|
||||
if (reason !== undefined) {
|
||||
form.value.note = reason
|
||||
}
|
||||
if (type !== undefined) {
|
||||
form.value.type = type
|
||||
}
|
||||
|
||||
// 如果有传入分类名称,尝试设置
|
||||
if (classify) {
|
||||
categoryName.value = classify
|
||||
@@ -166,9 +211,13 @@ onMounted(() => {
|
||||
})
|
||||
|
||||
// 监听 initialData 变化 (例如重新解析后)
|
||||
watch(() => props.initialData, () => {
|
||||
initForm()
|
||||
}, { deep: true })
|
||||
watch(
|
||||
() => props.initialData,
|
||||
() => {
|
||||
initForm()
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
const handleTypeChange = (newType) => {
|
||||
if (!isSyncing.value) {
|
||||
@@ -197,7 +246,7 @@ const handleSubmit = () => {
|
||||
}
|
||||
|
||||
const fullDateTime = `${form.value.date}T${form.value.time}:00`
|
||||
|
||||
|
||||
const payload = {
|
||||
occurredAt: fullDateTime,
|
||||
classify: categoryName.value,
|
||||
@@ -205,7 +254,7 @@ const handleSubmit = () => {
|
||||
reason: form.value.note || '',
|
||||
type: form.value.type
|
||||
}
|
||||
|
||||
|
||||
emit('submit', payload)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="manual-bill-add">
|
||||
<BillForm
|
||||
<BillForm
|
||||
ref="billFormRef"
|
||||
:loading="saving"
|
||||
@submit="handleSave"
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
<template>
|
||||
<div>
|
||||
<div v-if="!parseResult" class="input-section" style="margin: 12px 12px 0 16px;">
|
||||
<div
|
||||
v-if="!parseResult"
|
||||
class="input-section"
|
||||
style="margin: 12px 12px 0 16px"
|
||||
>
|
||||
<van-field
|
||||
v-model="text"
|
||||
type="textarea"
|
||||
@@ -10,11 +14,11 @@
|
||||
:disabled="parsing || saving"
|
||||
/>
|
||||
<div class="actions">
|
||||
<van-button
|
||||
type="primary"
|
||||
round
|
||||
block
|
||||
:loading="parsing"
|
||||
<van-button
|
||||
type="primary"
|
||||
round
|
||||
block
|
||||
:loading="parsing"
|
||||
:disabled="!text.trim()"
|
||||
@click="handleParse"
|
||||
>
|
||||
@@ -23,7 +27,10 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="parseResult" class="result-section">
|
||||
<div
|
||||
v-if="parseResult"
|
||||
class="result-section"
|
||||
>
|
||||
<BillForm
|
||||
:initial-data="parseResult"
|
||||
:loading="saving"
|
||||
@@ -31,11 +38,11 @@
|
||||
@submit="handleSave"
|
||||
>
|
||||
<template #actions>
|
||||
<van-button
|
||||
plain
|
||||
round
|
||||
block
|
||||
class="mt-2"
|
||||
<van-button
|
||||
plain
|
||||
round
|
||||
block
|
||||
class="mt-2"
|
||||
@click="parseResult = null"
|
||||
>
|
||||
重新输入
|
||||
@@ -60,17 +67,19 @@ const saving = ref(false)
|
||||
const parseResult = ref(null)
|
||||
|
||||
const handleParse = async () => {
|
||||
if (!text.value.trim()) return
|
||||
|
||||
if (!text.value.trim()) {
|
||||
return
|
||||
}
|
||||
|
||||
parsing.value = true
|
||||
parseResult.value = null
|
||||
|
||||
|
||||
try {
|
||||
const res = await parseOneLine(text.value)
|
||||
if(!res.success){
|
||||
if (!res.success) {
|
||||
throw new Error(res.message || '解析失败')
|
||||
}
|
||||
|
||||
|
||||
parseResult.value = res.data
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
@@ -84,11 +93,11 @@ const handleSave = async (payload) => {
|
||||
saving.value = true
|
||||
try {
|
||||
const res = await createTransaction(payload)
|
||||
|
||||
|
||||
if (!res.success) {
|
||||
throw new Error(res.message || '保存失败')
|
||||
}
|
||||
|
||||
|
||||
showToast('保存成功')
|
||||
text.value = ''
|
||||
parseResult.value = null
|
||||
@@ -121,6 +130,6 @@ const handleSave = async (payload) => {
|
||||
margin-bottom: 16px;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
border: 1px solid #ebedf0;
|
||||
border: 1px solid var(--van-border-color);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,172 +1,399 @@
|
||||
<template>
|
||||
<div class="common-card budget-card" @click="toggleExpand">
|
||||
<!-- eslint-disable vue/no-v-html -->
|
||||
<template>
|
||||
<!-- 普通预算卡片 -->
|
||||
<div
|
||||
v-if="!budget.noLimit"
|
||||
class="common-card budget-card"
|
||||
:class="{ 'cursor-default': budget.category === 2 }"
|
||||
@click="toggleExpand"
|
||||
>
|
||||
<div class="budget-content-wrapper">
|
||||
<!-- 折叠状态 -->
|
||||
<div v-if="!isExpanded" class="budget-collapsed">
|
||||
<div
|
||||
v-if="!isExpanded"
|
||||
class="budget-collapsed"
|
||||
>
|
||||
<div class="collapsed-header">
|
||||
<div class="budget-info">
|
||||
<slot name="tag">
|
||||
<van-tag
|
||||
:type="budget.type === BudgetPeriodType.Year ? 'warning' : 'primary'"
|
||||
plain
|
||||
class="status-tag"
|
||||
>
|
||||
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
|
||||
</van-tag>
|
||||
</slot>
|
||||
<h3 class="card-title">{{ budget.name }}</h3>
|
||||
<span v-if="budget.selectedCategories?.length" class="card-subtitle">
|
||||
({{ budget.selectedCategories.join('、') }})
|
||||
</span>
|
||||
</div>
|
||||
<van-icon name="arrow-down" class="expand-icon" />
|
||||
<div class="budget-info">
|
||||
<slot name="tag">
|
||||
<van-tag
|
||||
:type="budget.type === BudgetPeriodType.Year ? 'warning' : 'primary'"
|
||||
plain
|
||||
class="status-tag"
|
||||
>
|
||||
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
|
||||
<span
|
||||
v-if="budget.isMandatoryExpense"
|
||||
class="mandatory-mark"
|
||||
>📌</span>
|
||||
</van-tag>
|
||||
</slot>
|
||||
<h3 class="card-title">
|
||||
{{ budget.name }}
|
||||
</h3>
|
||||
<span
|
||||
v-if="budget.selectedCategories?.length"
|
||||
class="card-subtitle"
|
||||
>
|
||||
({{ budget.selectedCategories.join('、') }})
|
||||
</span>
|
||||
</div>
|
||||
<van-icon
|
||||
name="arrow-down"
|
||||
class="expand-icon"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="collapsed-footer">
|
||||
<div class="collapsed-item">
|
||||
<span class="compact-label">实际/目标</span>
|
||||
<span class="compact-value">
|
||||
<slot name="collapsed-amount">
|
||||
{{ budget.current !== undefined && budget.limit !== undefined
|
||||
? `¥${budget.current?.toFixed(0) || 0} / ¥${budget.limit?.toFixed(0) || 0}`
|
||||
: '--' }}
|
||||
{{
|
||||
budget.current !== undefined && budget.limit !== undefined
|
||||
? `¥${budget.current?.toFixed(0) || 0} / ¥${budget.limit?.toFixed(0) || 0}`
|
||||
: '--'
|
||||
}}
|
||||
</slot>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="collapsed-item">
|
||||
<span class="compact-label">达成率</span>
|
||||
<span class="compact-value" :class="percentClass">{{ percentage }}%</span>
|
||||
<span
|
||||
class="compact-value"
|
||||
:class="percentClass"
|
||||
>{{ percentage }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 展开状态 -->
|
||||
<Transition v-else :name="transitionName">
|
||||
<div :key="budget.period" class="budget-inner-card">
|
||||
<div class="card-header" style="margin-bottom: 0;">
|
||||
<div class="budget-info">
|
||||
<slot name="tag">
|
||||
<van-tag
|
||||
:type="budget.type === BudgetPeriodType.Year ? 'warning' : 'primary'"
|
||||
plain
|
||||
class="status-tag"
|
||||
>
|
||||
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
|
||||
</van-tag>
|
||||
</slot>
|
||||
<h3 class="card-title" style="max-width: 120px;">{{ budget.name }}</h3>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<slot name="actions">
|
||||
<van-button
|
||||
v-if="budget.description"
|
||||
:icon="showDescription ? 'info' : 'info-o'"
|
||||
size="small"
|
||||
:type="showDescription ? 'primary' : 'default'"
|
||||
plain
|
||||
@click.stop="showDescription = !showDescription"
|
||||
/>
|
||||
<van-button
|
||||
icon="orders-o"
|
||||
size="small"
|
||||
plain
|
||||
title="查询关联账单"
|
||||
@click.stop="handleQueryBills"
|
||||
/>
|
||||
<template v-if="budget.category !== 2">
|
||||
<van-button
|
||||
icon="edit"
|
||||
size="small"
|
||||
plain
|
||||
@click.stop="$emit('click', budget)"
|
||||
/>
|
||||
</template>
|
||||
|
||||
</slot>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="budget-body">
|
||||
<div v-if="budget.selectedCategories?.length" class="category-tags">
|
||||
<van-tag
|
||||
v-for="cat in budget.selectedCategories"
|
||||
:key="cat"
|
||||
size="mini"
|
||||
class="category-tag"
|
||||
<div
|
||||
v-else
|
||||
class="budget-inner-card"
|
||||
>
|
||||
<div
|
||||
class="card-header"
|
||||
style="margin-bottom: 0"
|
||||
>
|
||||
<div class="budget-info">
|
||||
<slot name="tag">
|
||||
<van-tag
|
||||
:type="budget.type === BudgetPeriodType.Year ? 'warning' : 'primary'"
|
||||
plain
|
||||
round
|
||||
class="status-tag"
|
||||
>
|
||||
{{ cat }}
|
||||
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
|
||||
<span
|
||||
v-if="budget.isMandatoryExpense"
|
||||
class="mandatory-mark"
|
||||
>📌</span>
|
||||
</van-tag>
|
||||
</div>
|
||||
<div class="amount-info">
|
||||
<slot name="amount-info"></slot>
|
||||
</div>
|
||||
|
||||
<div class="progress-section">
|
||||
<slot name="progress-info">
|
||||
<span class="period-type">{{ periodLabel }}{{ budget.category === 0 ? '使用' : '达成' }}</span>
|
||||
<van-progress
|
||||
:percentage="Math.min(percentage, 100)"
|
||||
stroke-width="8"
|
||||
:color="progressColor"
|
||||
:show-pivot="false"
|
||||
/>
|
||||
<span class="percent" :class="percentClass">{{ percentage }}%</span>
|
||||
</slot>
|
||||
</div>
|
||||
<div class="progress-section time-progress">
|
||||
<span class="period-type">时间进度</span>
|
||||
<van-progress
|
||||
:percentage="timePercentage"
|
||||
stroke-width="4"
|
||||
color="#969799"
|
||||
:show-pivot="false"
|
||||
/>
|
||||
<span class="percent">{{ timePercentage }}%</span>
|
||||
</div>
|
||||
|
||||
<van-collapse-transition>
|
||||
<div v-if="budget.description && showDescription" class="budget-description">
|
||||
<div class="description-content rich-html-content" v-html="budget.description"></div>
|
||||
</div>
|
||||
</van-collapse-transition>
|
||||
</slot>
|
||||
<h3
|
||||
class="card-title"
|
||||
style="max-width: 120px"
|
||||
>
|
||||
{{ budget.name }}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div class="card-footer">
|
||||
<div class="period-navigation" @click.stop>
|
||||
<van-button
|
||||
icon="arrow-left"
|
||||
class="nav-icon"
|
||||
plain
|
||||
<div class="header-actions">
|
||||
<slot name="actions">
|
||||
<van-button
|
||||
v-if="budget.description"
|
||||
:icon="showDescription ? 'info' : 'info-o'"
|
||||
size="small"
|
||||
style="width: 50px;"
|
||||
@click="handleSwitch(-1)"
|
||||
:type="showDescription ? 'primary' : 'default'"
|
||||
plain
|
||||
@click.stop="showDescription = !showDescription"
|
||||
/>
|
||||
<span class="period-text">{{ budget.period }}</span>
|
||||
<van-button
|
||||
icon="arrow"
|
||||
class="nav-icon"
|
||||
plain
|
||||
<van-button
|
||||
icon="orders-o"
|
||||
size="small"
|
||||
style="width: 50px;"
|
||||
:disabled="isNextDisabled"
|
||||
@click="handleSwitch(1)"
|
||||
plain
|
||||
title="查询关联账单"
|
||||
@click.stop="handleQueryBills"
|
||||
/>
|
||||
</div>
|
||||
<template v-if="budget.category !== 2">
|
||||
<van-button
|
||||
icon="edit"
|
||||
size="small"
|
||||
plain
|
||||
@click.stop="$emit('click', budget)"
|
||||
/>
|
||||
</template>
|
||||
</slot>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
|
||||
<div class="budget-body">
|
||||
<div
|
||||
v-if="budget.selectedCategories?.length"
|
||||
class="category-tags"
|
||||
>
|
||||
<van-tag
|
||||
v-for="cat in budget.selectedCategories"
|
||||
:key="cat"
|
||||
size="mini"
|
||||
class="category-tag"
|
||||
plain
|
||||
round
|
||||
>
|
||||
{{ cat }}
|
||||
</van-tag>
|
||||
</div>
|
||||
<div class="amount-info">
|
||||
<slot name="amount-info" />
|
||||
</div>
|
||||
|
||||
<div class="progress-section">
|
||||
<slot name="progress-info">
|
||||
<span class="period-type">{{ periodLabel }}{{ budget.category === 0 ? '使用' : '达成' }}</span>
|
||||
<van-progress
|
||||
:percentage="Math.min(percentage, 100)"
|
||||
stroke-width="8"
|
||||
:color="progressColor"
|
||||
:show-pivot="false"
|
||||
/>
|
||||
<span
|
||||
class="percent"
|
||||
:class="percentClass"
|
||||
>{{ percentage }}%</span>
|
||||
</slot>
|
||||
</div>
|
||||
<div class="progress-section time-progress">
|
||||
<span class="period-type">时间进度</span>
|
||||
<van-progress
|
||||
:percentage="timePercentage"
|
||||
stroke-width="4"
|
||||
color="var(--van-gray-6)"
|
||||
:show-pivot="false"
|
||||
/>
|
||||
<span class="percent">{{ timePercentage }}%</span>
|
||||
</div>
|
||||
|
||||
<transition
|
||||
name="collapse"
|
||||
@enter="onEnter"
|
||||
@after-enter="onAfterEnter"
|
||||
@leave="onLeave"
|
||||
@after-leave="onAfterLeave"
|
||||
>
|
||||
<div
|
||||
v-if="budget.description && showDescription"
|
||||
class="budget-collapse-wrapper"
|
||||
>
|
||||
<div class="budget-description">
|
||||
<div
|
||||
class="description-content rich-html-content"
|
||||
v-html="budget.description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
|
||||
<div class="card-footer">
|
||||
<slot name="footer" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 关联账单列表弹窗 -->
|
||||
<PopupContainer
|
||||
<PopupContainer
|
||||
v-model="showBillListModal"
|
||||
title="关联账单列表"
|
||||
height="75%"
|
||||
>
|
||||
<TransactionList
|
||||
<TransactionList
|
||||
:transactions="billList"
|
||||
:loading="billLoading"
|
||||
:finished="true"
|
||||
:show-delete="false"
|
||||
:show-checkbox="false"
|
||||
@click="handleBillClick"
|
||||
@delete="handleBillDelete"
|
||||
/>
|
||||
</PopupContainer>
|
||||
</div>
|
||||
|
||||
<!-- 不记额预算卡片 -->
|
||||
<div
|
||||
v-else
|
||||
class="common-card budget-card no-limit-card"
|
||||
:class="{ 'cursor-default': budget.category === 2 }"
|
||||
@click="toggleExpand"
|
||||
>
|
||||
<div class="budget-content-wrapper">
|
||||
<!-- 折叠状态 -->
|
||||
<div
|
||||
v-if="!isExpanded"
|
||||
class="budget-collapsed"
|
||||
>
|
||||
<div class="collapsed-header">
|
||||
<div class="budget-info">
|
||||
<slot name="tag">
|
||||
<van-tag
|
||||
type="success"
|
||||
plain
|
||||
class="status-tag"
|
||||
>
|
||||
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
|
||||
</van-tag>
|
||||
</slot>
|
||||
<h3 class="card-title">
|
||||
{{ budget.name }}
|
||||
</h3>
|
||||
<span
|
||||
v-if="budget.selectedCategories?.length"
|
||||
class="card-subtitle"
|
||||
>
|
||||
({{ budget.selectedCategories.join('、') }})
|
||||
</span>
|
||||
</div>
|
||||
<van-icon
|
||||
name="arrow-down"
|
||||
class="expand-icon"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="collapsed-footer no-limit-footer">
|
||||
<div class="collapsed-item">
|
||||
<span class="compact-label">实际</span>
|
||||
<span class="compact-value">
|
||||
<slot name="collapsed-amount">
|
||||
{{ budget.current !== undefined ? `¥${budget.current?.toFixed(0) || 0}` : '--' }}
|
||||
</slot>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 展开状态 -->
|
||||
<div
|
||||
v-else
|
||||
class="budget-inner-card"
|
||||
>
|
||||
<div
|
||||
class="card-header"
|
||||
style="margin-bottom: 0"
|
||||
>
|
||||
<div class="budget-info">
|
||||
<slot name="tag">
|
||||
<van-tag
|
||||
type="success"
|
||||
plain
|
||||
class="status-tag"
|
||||
>
|
||||
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
|
||||
</van-tag>
|
||||
</slot>
|
||||
<h3
|
||||
class="card-title"
|
||||
style="max-width: 120px"
|
||||
>
|
||||
{{ budget.name }}
|
||||
</h3>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<slot name="actions">
|
||||
<van-button
|
||||
v-if="budget.description"
|
||||
:icon="showDescription ? 'info' : 'info-o'"
|
||||
size="small"
|
||||
:type="showDescription ? 'primary' : 'default'"
|
||||
plain
|
||||
@click.stop="showDescription = !showDescription"
|
||||
/>
|
||||
<van-button
|
||||
icon="orders-o"
|
||||
size="small"
|
||||
plain
|
||||
title="查询关联账单"
|
||||
@click.stop="handleQueryBills"
|
||||
/>
|
||||
<template v-if="budget.category !== 2">
|
||||
<van-button
|
||||
icon="edit"
|
||||
size="small"
|
||||
plain
|
||||
@click.stop="$emit('click', budget)"
|
||||
/>
|
||||
</template>
|
||||
</slot>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="budget-body">
|
||||
<div
|
||||
v-if="budget.selectedCategories?.length"
|
||||
class="category-tags"
|
||||
>
|
||||
<van-tag
|
||||
v-for="cat in budget.selectedCategories"
|
||||
:key="cat"
|
||||
size="mini"
|
||||
class="category-tag"
|
||||
plain
|
||||
round
|
||||
>
|
||||
{{ cat }}
|
||||
</van-tag>
|
||||
</div>
|
||||
|
||||
<div class="no-limit-amount-info">
|
||||
<div class="amount-item">
|
||||
<span>
|
||||
<span class="label">实际</span>
|
||||
<span
|
||||
class="value"
|
||||
style="margin-left: 12px"
|
||||
>¥{{ budget.current?.toFixed(0) || 0 }}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="no-limit-notice">
|
||||
<span>
|
||||
<van-icon
|
||||
name="info-o"
|
||||
style="margin-right: 4px"
|
||||
/>
|
||||
不记额预算 - 直接计入存款明细
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<transition
|
||||
name="collapse"
|
||||
@enter="onEnter"
|
||||
@after-enter="onAfterEnter"
|
||||
@leave="onLeave"
|
||||
@after-leave="onAfterLeave"
|
||||
>
|
||||
<div
|
||||
v-if="budget.description && showDescription"
|
||||
class="budget-collapse-wrapper"
|
||||
>
|
||||
<div class="budget-description">
|
||||
<div
|
||||
class="description-content rich-html-content"
|
||||
v-html="budget.description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 关联账单列表弹窗 -->
|
||||
<PopupContainer
|
||||
v-model="showBillListModal"
|
||||
title="关联账单列表"
|
||||
height="75%"
|
||||
>
|
||||
<TransactionList
|
||||
:transactions="billList"
|
||||
:loading="billLoading"
|
||||
:finished="true"
|
||||
@@ -193,7 +420,7 @@ const props = defineProps({
|
||||
},
|
||||
progressColor: {
|
||||
type: String,
|
||||
default: '#1989fa'
|
||||
default: 'var(--van-primary-color)'
|
||||
},
|
||||
percentClass: {
|
||||
type: [String, Object],
|
||||
@@ -205,36 +432,29 @@ const props = defineProps({
|
||||
}
|
||||
})
|
||||
|
||||
const emit = defineEmits(['switch-period', 'click'])
|
||||
const emit = defineEmits(['click'])
|
||||
|
||||
const isExpanded = ref(props.budget.category === 2)
|
||||
const transitionName = ref('slide-left')
|
||||
const showDescription = ref(false)
|
||||
const showBillListModal = ref(false)
|
||||
const billList = ref([])
|
||||
const billLoading = ref(false)
|
||||
|
||||
const toggleExpand = () => {
|
||||
// 存款类型(category === 2)强制保持展开状态,不可折叠
|
||||
if (props.budget.category === 2) {
|
||||
return
|
||||
}
|
||||
isExpanded.value = !isExpanded.value
|
||||
}
|
||||
|
||||
const isNextDisabled = computed(() => {
|
||||
if (!props.budget.periodEnd) return false
|
||||
return new Date(props.budget.periodEnd) > new Date()
|
||||
})
|
||||
|
||||
const handleSwitch = (direction) => {
|
||||
transitionName.value = direction > 0 ? 'slide-left' : 'slide-right'
|
||||
emit('switch-period', direction)
|
||||
}
|
||||
|
||||
const handleQueryBills = async () => {
|
||||
showBillListModal.value = true
|
||||
billLoading.value = true
|
||||
|
||||
|
||||
try {
|
||||
const classify = props.budget.selectedCategories
|
||||
? props.budget.selectedCategories.join(',')
|
||||
const classify = props.budget.selectedCategories
|
||||
? props.budget.selectedCategories.join(',')
|
||||
: ''
|
||||
|
||||
if (classify === '') {
|
||||
@@ -254,12 +474,11 @@ const handleQueryBills = async () => {
|
||||
sortByAmount: true
|
||||
})
|
||||
|
||||
if(response.success) {
|
||||
if (response.success) {
|
||||
billList.value = response.data || []
|
||||
} else {
|
||||
billList.value = []
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('查询账单列表失败:', error)
|
||||
billList.value = []
|
||||
@@ -269,21 +488,59 @@ const handleQueryBills = async () => {
|
||||
}
|
||||
|
||||
const percentage = computed(() => {
|
||||
if (!props.budget.limit) return 0
|
||||
if (!props.budget.limit) {
|
||||
return 0
|
||||
}
|
||||
return Math.round((props.budget.current / props.budget.limit) * 100)
|
||||
})
|
||||
|
||||
const timePercentage = computed(() => {
|
||||
if (!props.budget.periodStart || !props.budget.periodEnd) return 0
|
||||
if (!props.budget.periodStart || !props.budget.periodEnd) {
|
||||
return 0
|
||||
}
|
||||
const start = new Date(props.budget.periodStart).getTime()
|
||||
const end = new Date(props.budget.periodEnd).getTime()
|
||||
const now = new Date().getTime()
|
||||
|
||||
if (now <= start) return 0
|
||||
if (now >= end) return 100
|
||||
|
||||
|
||||
if (now <= start) {
|
||||
return 0
|
||||
}
|
||||
if (now >= end) {
|
||||
return 100
|
||||
}
|
||||
|
||||
return Math.round(((now - start) / (end - start)) * 100)
|
||||
})
|
||||
|
||||
const onEnter = (el) => {
|
||||
el.style.height = '0'
|
||||
el.style.overflow = 'hidden'
|
||||
// Force reflow
|
||||
el.offsetHeight
|
||||
el.style.transition = 'height 0.3s ease-in-out'
|
||||
el.style.height = `${el.scrollHeight}px`
|
||||
}
|
||||
|
||||
const onAfterEnter = (el) => {
|
||||
el.style.height = ''
|
||||
el.style.overflow = ''
|
||||
el.style.transition = ''
|
||||
}
|
||||
|
||||
const onLeave = (el) => {
|
||||
el.style.height = `${el.scrollHeight}px`
|
||||
el.style.overflow = 'hidden'
|
||||
// Force reflow
|
||||
el.offsetHeight
|
||||
el.style.transition = 'height 0.3s ease-in-out'
|
||||
el.style.height = '0'
|
||||
}
|
||||
|
||||
const onAfterLeave = (el) => {
|
||||
el.style.height = ''
|
||||
el.style.overflow = ''
|
||||
el.style.transition = ''
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -297,6 +554,18 @@ const timePercentage = computed(() => {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.budget-card.cursor-default {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.no-limit-card {
|
||||
border-left: 3px solid var(--van-success-color);
|
||||
}
|
||||
|
||||
.collapsed-footer.no-limit-footer {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.budget-content-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
@@ -368,7 +637,7 @@ const timePercentage = computed(() => {
|
||||
|
||||
.compact-label {
|
||||
font-size: 12px;
|
||||
color: #969799;
|
||||
color: var(--van-text-color-2);
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
@@ -382,60 +651,26 @@ const timePercentage = computed(() => {
|
||||
}
|
||||
|
||||
.compact-value.warning {
|
||||
color: #ff976a;
|
||||
color: var(--van-warning-color);
|
||||
}
|
||||
|
||||
.compact-value.income {
|
||||
color: #07c160;
|
||||
color: var(--van-success-color);
|
||||
}
|
||||
|
||||
.expand-icon {
|
||||
color: #1989fa;
|
||||
color: var(--van-primary-color);
|
||||
font-size: 14px;
|
||||
transition: transform 0.3s ease;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.collapse-icon {
|
||||
color: #1989fa;
|
||||
color: var(--van-primary-color);
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* 切换动画 */
|
||||
.slide-left-enter-active,
|
||||
.slide-left-leave-active,
|
||||
.slide-right-enter-active,
|
||||
.slide-right-leave-active {
|
||||
transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.slide-left-enter-from {
|
||||
transform: translateX(100%);
|
||||
opacity: 0;
|
||||
}
|
||||
.slide-left-leave-to {
|
||||
transform: translateX(-100%);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.slide-right-enter-from {
|
||||
transform: translateX(-100%);
|
||||
opacity: 0;
|
||||
}
|
||||
.slide-right-leave-to {
|
||||
transform: translateX(100%);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.slide-left-leave-active,
|
||||
.slide-right-leave-active {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.budget-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -456,7 +691,7 @@ const timePercentage = computed(() => {
|
||||
|
||||
.card-subtitle {
|
||||
font-size: 12px;
|
||||
color: #969799;
|
||||
color: var(--van-text-color-2);
|
||||
font-weight: normal;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
@@ -490,7 +725,7 @@ const timePercentage = computed(() => {
|
||||
|
||||
:deep(.info-item) .label {
|
||||
font-size: 12px;
|
||||
color: #969799;
|
||||
color: var(--van-text-color-2);
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
@@ -500,11 +735,11 @@ const timePercentage = computed(() => {
|
||||
}
|
||||
|
||||
:deep(.value.expense) {
|
||||
color: #ee0a24;
|
||||
color: var(--van-danger-color);
|
||||
}
|
||||
|
||||
:deep(.value.income) {
|
||||
color: #07c160;
|
||||
color: var(--van-success-color);
|
||||
}
|
||||
|
||||
.progress-section {
|
||||
@@ -513,7 +748,7 @@ const timePercentage = computed(() => {
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
font-size: 13px;
|
||||
color: #646566;
|
||||
color: var(--van-gray-6);
|
||||
}
|
||||
|
||||
.progress-section :deep(.van-progress) {
|
||||
@@ -532,12 +767,12 @@ const timePercentage = computed(() => {
|
||||
}
|
||||
|
||||
.percent.warning {
|
||||
color: #ff976a;
|
||||
color: var(--van-warning-color);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.percent.income {
|
||||
color: #07c160;
|
||||
color: var(--van-success-color);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@@ -551,63 +786,58 @@ const timePercentage = computed(() => {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.budget-description {
|
||||
margin-top: 8px;
|
||||
background-color: #f7f8fa;
|
||||
.no-limit-notice {
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: var(--van-text-color-2);
|
||||
background-color: var(--van-light-gray);
|
||||
border-radius: 4px;
|
||||
padding: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.no-limit-amount-info {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin: 0px 0;
|
||||
}
|
||||
|
||||
.amount-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.amount-item .label {
|
||||
font-size: 12px;
|
||||
color: var(--van-text-color-2);
|
||||
}
|
||||
|
||||
.amount-item .value {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: var(--van-success-color);
|
||||
}
|
||||
|
||||
.budget-collapse-wrapper {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.budget-description {
|
||||
border-top: 1px solid var(--van-border-color);
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.description-content {
|
||||
font-size: 11px;
|
||||
color: #646566;
|
||||
color: var(--van-gray-6);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.card-footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
color: #969799;
|
||||
padding: 12px 12px 0;
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid #ebedf0;
|
||||
}
|
||||
|
||||
.period-navigation {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.period-text {
|
||||
.mandatory-mark {
|
||||
margin-left: 4px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #323233;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.nav-icon {
|
||||
padding: 4px;
|
||||
font-size: 12px;
|
||||
color: #1989fa;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.card-footer {
|
||||
border-top-color: #2c2c2c;
|
||||
}
|
||||
.period-text {
|
||||
color: #f5f5f5;
|
||||
}
|
||||
.budget-description {
|
||||
background-color: #2c2c2c;
|
||||
}
|
||||
.description-content {
|
||||
color: #969799;
|
||||
}
|
||||
.collapsed-row .value {
|
||||
color: #f5f5f5;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
1116
Web/src/components/Budget/BudgetChartAnalysis.vue
Normal file
1116
Web/src/components/Budget/BudgetChartAnalysis.vue
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,11 @@
|
||||
<template>
|
||||
<PopupContainer
|
||||
v-model="visible"
|
||||
:title="isEdit ? `编辑${getCategoryName(form.category)}预算` : `新增${getCategoryName(form.category)}预算`"
|
||||
<PopupContainer
|
||||
v-model="visible"
|
||||
:title="
|
||||
isEdit
|
||||
? `编辑${getCategoryName(form.category)}预算`
|
||||
: `新增${getCategoryName(form.category)}预算`
|
||||
"
|
||||
height="75%"
|
||||
>
|
||||
<div class="add-budget-form">
|
||||
@@ -14,19 +18,55 @@
|
||||
placeholder="例如:每月餐饮、年度奖金"
|
||||
:rules="[{ required: true, message: '请填写预算名称' }]"
|
||||
/>
|
||||
<van-field name="type" label="统计周期">
|
||||
<!-- 新增:不记额预算复选框 -->
|
||||
<van-field label="不记额预算">
|
||||
<template #input>
|
||||
<van-radio-group
|
||||
v-model="form.type"
|
||||
direction="horizontal"
|
||||
:disabled="isEdit"
|
||||
<van-checkbox
|
||||
v-model="form.noLimit"
|
||||
@update:model-value="onNoLimitChange"
|
||||
>
|
||||
<van-radio :name="BudgetPeriodType.Month">月</van-radio>
|
||||
<van-radio :name="BudgetPeriodType.Year">年</van-radio>
|
||||
</van-radio-group>
|
||||
不记额预算
|
||||
</van-checkbox>
|
||||
</template>
|
||||
</van-field>
|
||||
<!-- 新增:硬性消费复选框 -->
|
||||
<van-field :label="form.category === BudgetCategory.Expense ? '硬性消费' : '硬性收入'">
|
||||
<template #input>
|
||||
<div class="mandatory-wrapper">
|
||||
<van-checkbox
|
||||
v-model="form.isMandatoryExpense"
|
||||
:disabled="form.noLimit"
|
||||
>
|
||||
{{ form.category === BudgetCategory.Expense ? '硬性消费' : '硬性收入' }}
|
||||
<span class="mandatory-tip">
|
||||
当前周期 月/年 按天数自动累加(无记录时)
|
||||
</span>
|
||||
</van-checkbox>
|
||||
</div>
|
||||
</template>
|
||||
</van-field>
|
||||
<van-field
|
||||
name="type"
|
||||
label="统计周期"
|
||||
>
|
||||
<template #input>
|
||||
<van-radio-group
|
||||
v-model="form.type"
|
||||
direction="horizontal"
|
||||
:disabled="isEdit || form.noLimit"
|
||||
>
|
||||
<van-radio :name="BudgetPeriodType.Month">
|
||||
月
|
||||
</van-radio>
|
||||
<van-radio :name="BudgetPeriodType.Year">
|
||||
年
|
||||
</van-radio>
|
||||
</van-radio-group>
|
||||
</template>
|
||||
</van-field>
|
||||
<!-- 仅当未选中"不记额预算"时显示预算金额 -->
|
||||
<van-field
|
||||
v-if="!form.noLimit"
|
||||
v-model="form.limit"
|
||||
type="number"
|
||||
name="limit"
|
||||
@@ -40,8 +80,16 @@
|
||||
</van-field>
|
||||
<van-field label="相关分类">
|
||||
<template #input>
|
||||
<div v-if="form.selectedCategories.length === 0" style="color: #c8c9cc;">可多选分类</div>
|
||||
<div v-else class="selected-categories">
|
||||
<div
|
||||
v-if="form.selectedCategories.length === 0"
|
||||
style="color: var(--van-text-color-3)"
|
||||
>
|
||||
可多选分类
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="selected-categories"
|
||||
>
|
||||
<span class="ellipsis-text">
|
||||
{{ form.selectedCategories.join('、') }}
|
||||
</span>
|
||||
@@ -59,7 +107,14 @@
|
||||
</van-form>
|
||||
</div>
|
||||
<template #footer>
|
||||
<van-button block round type="primary" @click="onSubmit">保存预算</van-button>
|
||||
<van-button
|
||||
block
|
||||
round
|
||||
type="primary"
|
||||
@click="onSubmit"
|
||||
>
|
||||
保存预算
|
||||
</van-button>
|
||||
</template>
|
||||
</PopupContainer>
|
||||
</template>
|
||||
@@ -83,15 +138,13 @@ const form = reactive({
|
||||
type: BudgetPeriodType.Month,
|
||||
category: BudgetCategory.Expense,
|
||||
limit: '',
|
||||
selectedCategories: []
|
||||
selectedCategories: [],
|
||||
noLimit: false, // 新增字段
|
||||
isMandatoryExpense: false // 新增:硬性消费
|
||||
})
|
||||
|
||||
const open = ({
|
||||
data,
|
||||
isEditFlag,
|
||||
category
|
||||
}) => {
|
||||
if(category === undefined) {
|
||||
const open = ({ data, isEditFlag, category }) => {
|
||||
if (category === undefined) {
|
||||
showToast('缺少必要参数:category')
|
||||
return
|
||||
}
|
||||
@@ -104,7 +157,9 @@ const open = ({
|
||||
type: data.type,
|
||||
category: category,
|
||||
limit: data.limit,
|
||||
selectedCategories: data.selectedCategories ? [...data.selectedCategories] : []
|
||||
selectedCategories: data.selectedCategories ? [...data.selectedCategories] : [],
|
||||
noLimit: data.noLimit || false, // 新增
|
||||
isMandatoryExpense: data.isMandatoryExpense || false // 新增:硬性消费
|
||||
})
|
||||
} else {
|
||||
Object.assign(form, {
|
||||
@@ -113,7 +168,9 @@ const open = ({
|
||||
type: BudgetPeriodType.Month,
|
||||
category: category,
|
||||
limit: '',
|
||||
selectedCategories: []
|
||||
selectedCategories: [],
|
||||
noLimit: false, // 新增
|
||||
isMandatoryExpense: false // 新增:硬性消费
|
||||
})
|
||||
}
|
||||
visible.value = true
|
||||
@@ -124,17 +181,23 @@ defineExpose({
|
||||
})
|
||||
|
||||
const budgetType = computed(() => {
|
||||
return form.category === BudgetCategory.Expense ? 0 : (form.category === BudgetCategory.Income ? 1 : 2)
|
||||
return form.category === BudgetCategory.Expense
|
||||
? 0
|
||||
: form.category === BudgetCategory.Income
|
||||
? 1
|
||||
: 2
|
||||
})
|
||||
|
||||
const onSubmit = async () => {
|
||||
try {
|
||||
const data = {
|
||||
...form,
|
||||
limit: parseFloat(form.limit),
|
||||
selectedCategories: form.selectedCategories
|
||||
limit: form.noLimit ? 0 : parseFloat(form.limit), // 不记额时金额为0
|
||||
selectedCategories: form.selectedCategories,
|
||||
noLimit: form.noLimit, // 新增
|
||||
isMandatoryExpense: form.isMandatoryExpense // 新增:硬性消费
|
||||
}
|
||||
|
||||
|
||||
const res = form.id ? await updateBudget(data) : await createBudget(data)
|
||||
if (res.success) {
|
||||
showToast('保存成功')
|
||||
@@ -148,7 +211,7 @@ const onSubmit = async () => {
|
||||
}
|
||||
|
||||
const getCategoryName = (category) => {
|
||||
switch(category) {
|
||||
switch (category) {
|
||||
case BudgetCategory.Expense:
|
||||
return '支出'
|
||||
case BudgetCategory.Income:
|
||||
@@ -159,6 +222,15 @@ const getCategoryName = (category) => {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
const onNoLimitChange = (value) => {
|
||||
if (value) {
|
||||
// 选中不记额时,自动设为年度预算
|
||||
form.type = BudgetPeriodType.Year
|
||||
// 选中不记额时,清除硬性消费选择
|
||||
form.isMandatoryExpense = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -176,7 +248,7 @@ const getCategoryName = (category) => {
|
||||
|
||||
.ellipsis-text {
|
||||
font-size: 14px;
|
||||
color: #323233;
|
||||
color: var(--van-text-color);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -185,7 +257,19 @@ const getCategoryName = (category) => {
|
||||
|
||||
.no-data {
|
||||
font-size: 13px;
|
||||
color: #969799;
|
||||
color: var(--van-text-color-2);
|
||||
padding: 8px 16px;
|
||||
}
|
||||
|
||||
.mandatory-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.mandatory-tip {
|
||||
font-size: 11px;
|
||||
color: var(--van-text-color-3);
|
||||
margin-left: 6px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,17 +1,35 @@
|
||||
<template>
|
||||
<div class="summary-container">
|
||||
<transition :name="transitionName" mode="out-in">
|
||||
<div v-if="stats && (stats.month || stats.year)" :key="dateKey" class="summary-card common-card">
|
||||
<transition
|
||||
:name="transitionName"
|
||||
mode="out-in"
|
||||
>
|
||||
<div
|
||||
v-if="stats && (stats.month || stats.year)"
|
||||
:key="dateKey"
|
||||
class="summary-card common-card"
|
||||
>
|
||||
<!-- 左切换按钮 -->
|
||||
<div class="nav-arrow left" @click.stop="changeMonth(-1)">
|
||||
<div
|
||||
class="nav-arrow left"
|
||||
@click.stop="changeMonth(-1)"
|
||||
>
|
||||
<van-icon name="arrow-left" />
|
||||
</div>
|
||||
|
||||
<div class="summary-content">
|
||||
<template v-for="(config, key) in periodConfigs" :key="key">
|
||||
<template
|
||||
v-for="(config, key) in periodConfigs"
|
||||
:key="key"
|
||||
>
|
||||
<div class="summary-item">
|
||||
<div class="label">{{ config.label }}{{ title }}率</div>
|
||||
<div class="value" :class="getValueClass(stats[key]?.rate || '0.0')">
|
||||
<div class="label">
|
||||
{{ config.label }}{{ title }}率
|
||||
</div>
|
||||
<div
|
||||
class="value"
|
||||
:class="getValueClass(stats[key]?.rate || '0.0')"
|
||||
>
|
||||
{{ stats[key]?.rate || '0.0' }}<span class="unit">%</span>
|
||||
</div>
|
||||
<div class="sub-info">
|
||||
@@ -20,13 +38,16 @@
|
||||
<span class="amount">¥{{ formatMoney(stats[key]?.limit || 0) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="config.showDivider" class="divider"></div>
|
||||
<div
|
||||
v-if="config.showDivider"
|
||||
class="divider"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 右切换按钮 -->
|
||||
<div
|
||||
class="nav-arrow right"
|
||||
<div
|
||||
class="nav-arrow right"
|
||||
:class="{ disabled: isCurrentMonth }"
|
||||
@click.stop="!isCurrentMonth && changeMonth(1)"
|
||||
>
|
||||
@@ -34,7 +55,10 @@
|
||||
</div>
|
||||
|
||||
<!-- 非本月时显示的日期标识 -->
|
||||
<div v-if="!isCurrentMonth" class="date-tag">
|
||||
<div
|
||||
v-if="!isCurrentMonth"
|
||||
class="date-tag"
|
||||
>
|
||||
{{ props.date.getFullYear() }}年{{ props.date.getMonth() + 1 }}月
|
||||
</div>
|
||||
</div>
|
||||
@@ -71,18 +95,17 @@ const dateKey = computed(() => props.date.getFullYear() + '-' + props.date.getMo
|
||||
|
||||
const isCurrentMonth = computed(() => {
|
||||
const now = new Date()
|
||||
return props.date.getFullYear() === now.getFullYear() &&
|
||||
props.date.getMonth() === now.getMonth()
|
||||
return props.date.getFullYear() === now.getFullYear() && props.date.getMonth() === now.getMonth()
|
||||
})
|
||||
|
||||
const periodConfigs = computed(() => ({
|
||||
month: {
|
||||
label: isCurrentMonth.value ? '本月' : `${props.date.getMonth() + 1}月`,
|
||||
showDivider: true
|
||||
month: {
|
||||
label: isCurrentMonth.value ? '本月' : `${props.date.getMonth() + 1}月`,
|
||||
showDivider: true
|
||||
},
|
||||
year: {
|
||||
label: isCurrentMonth.value ? '年度' : `${props.date.getFullYear()}年`,
|
||||
showDivider: false
|
||||
year: {
|
||||
label: isCurrentMonth.value ? '年度' : `${props.date.getFullYear()}年`,
|
||||
showDivider: false
|
||||
}
|
||||
}))
|
||||
|
||||
@@ -94,7 +117,10 @@ const changeMonth = (delta) => {
|
||||
}
|
||||
|
||||
const formatMoney = (val) => {
|
||||
return parseFloat(val || 0).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })
|
||||
return parseFloat(val || 0).toLocaleString(undefined, {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 0
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -130,7 +156,7 @@ const formatMoney = (val) => {
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
font-size: 18px;
|
||||
color: #c8c9cc;
|
||||
color: var(--van-gray-5);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
z-index: 1;
|
||||
@@ -141,6 +167,17 @@ const formatMoney = (val) => {
|
||||
background-color: rgba(0, 0, 0, 0.02);
|
||||
}
|
||||
|
||||
.nav-arrow.disabled {
|
||||
color: #c8c9cc;
|
||||
cursor: not-allowed;
|
||||
opacity: 0.35;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.nav-arrow.disabled:active {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.nav-arrow.left {
|
||||
left: 0;
|
||||
}
|
||||
@@ -150,7 +187,7 @@ const formatMoney = (val) => {
|
||||
}
|
||||
|
||||
.nav-arrow.disabled {
|
||||
color: #f2f3f5;
|
||||
color: var(--van-gray-3);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@@ -200,26 +237,26 @@ const formatMoney = (val) => {
|
||||
|
||||
.summary-item .label {
|
||||
font-size: 12px;
|
||||
color: #969799;
|
||||
color: var(--van-text-color-2);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.summary-item .value {
|
||||
font-size: 20px;
|
||||
font-weight: bold;
|
||||
color: #323233;
|
||||
color: var(--van-text-color);
|
||||
}
|
||||
|
||||
.summary-item :deep(.value.expense) {
|
||||
color: #ee0a24;
|
||||
color: var(--van-danger-color);
|
||||
}
|
||||
|
||||
.summary-item :deep(.value.income) {
|
||||
color: #07c160;
|
||||
color: var(--van-success-color);
|
||||
}
|
||||
|
||||
.summary-item :deep(.value.warning) {
|
||||
color: #ff976a;
|
||||
color: var(--van-warning-color);
|
||||
}
|
||||
|
||||
.summary-item .unit {
|
||||
@@ -230,7 +267,7 @@ const formatMoney = (val) => {
|
||||
|
||||
.summary-item .sub-info {
|
||||
font-size: 12px;
|
||||
color: #c8c9cc;
|
||||
color: var(--van-text-color-3);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
@@ -238,35 +275,35 @@ const formatMoney = (val) => {
|
||||
}
|
||||
|
||||
.summary-item .amount {
|
||||
color: #646566;
|
||||
color: var(--van-text-color-2);
|
||||
}
|
||||
|
||||
.summary-item .separator {
|
||||
color: #c8c9cc;
|
||||
color: var(--van-text-color-3);
|
||||
}
|
||||
|
||||
.divider {
|
||||
width: 1px;
|
||||
height: 24px;
|
||||
background-color: #ebedf0;
|
||||
background-color: var(--van-border-color);
|
||||
margin: 0 4px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
/* @media (prefers-color-scheme: dark) {
|
||||
.nav-arrow:active {
|
||||
background-color: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
.nav-arrow.disabled {
|
||||
color: #323233;
|
||||
color: var(--van-text-color);
|
||||
}
|
||||
.summary-item .value {
|
||||
color: #f5f5f5;
|
||||
color: var(--van-text-color);
|
||||
}
|
||||
.summary-item .amount {
|
||||
color: #c8c9cc;
|
||||
color: var(--van-text-color-3);
|
||||
}
|
||||
.divider {
|
||||
background-color: #2c2c2c;
|
||||
background-color: var(--van-border-color);
|
||||
}
|
||||
}
|
||||
} */
|
||||
</style>
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
<template>
|
||||
<PopupContainer
|
||||
v-model="visible"
|
||||
title="设置存款分类"
|
||||
<PopupContainer
|
||||
v-model="visible"
|
||||
title="设置存款分类"
|
||||
height="60%"
|
||||
>
|
||||
<div class="savings-config-content">
|
||||
<div class="config-header">
|
||||
<p class="subtitle">这些分类的统计值将计入“存款”中</p>
|
||||
<p class="subtitle">
|
||||
这些分类的统计值将计入“存款”中
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="category-section">
|
||||
<div class="section-title">可多选分类</div>
|
||||
<div class="section-title">
|
||||
可多选分类
|
||||
</div>
|
||||
<ClassifySelector
|
||||
v-model="selectedCategories"
|
||||
:type="2"
|
||||
@@ -20,9 +24,16 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<template #footer>
|
||||
<van-button block round type="primary" @click="onSubmit">保存配置</van-button>
|
||||
<van-button
|
||||
block
|
||||
round
|
||||
type="primary"
|
||||
@click="onSubmit"
|
||||
>
|
||||
保存配置
|
||||
</van-button>
|
||||
</template>
|
||||
</PopupContainer>
|
||||
</template>
|
||||
@@ -52,7 +63,7 @@ const fetchConfig = async () => {
|
||||
try {
|
||||
const res = await getConfig('SavingsCategories')
|
||||
if (res.success && res.data) {
|
||||
selectedCategories.value = res.data.split(',').filter(x => x)
|
||||
selectedCategories.value = res.data.split(',').filter((x) => x)
|
||||
} else {
|
||||
selectedCategories.value = []
|
||||
}
|
||||
@@ -91,7 +102,7 @@ const onSubmit = async () => {
|
||||
|
||||
.subtitle {
|
||||
font-size: 14px;
|
||||
color: #969799;
|
||||
color: var(--van-text-color-2);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@@ -103,7 +114,7 @@ const onSubmit = async () => {
|
||||
|
||||
.no-data {
|
||||
text-align: center;
|
||||
color: #969799;
|
||||
color: var(--van-text-color-2);
|
||||
width: 100%;
|
||||
padding: 20px 0;
|
||||
}
|
||||
|
||||
@@ -98,17 +98,21 @@ const innerOptions = ref([])
|
||||
const addClassifyDialogRef = ref()
|
||||
|
||||
const displayOptions = computed(() => {
|
||||
if (props.options) return props.options
|
||||
if (props.options) {
|
||||
return props.options
|
||||
}
|
||||
return innerOptions.value
|
||||
})
|
||||
|
||||
const fetchOptions = async () => {
|
||||
if (props.options) return
|
||||
|
||||
if (props.options) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await getCategoryList(props.type)
|
||||
if (response.success) {
|
||||
innerOptions.value = (response.data || []).map(item => ({
|
||||
innerOptions.value = (response.data || []).map((item) => ({
|
||||
text: item.name,
|
||||
value: item.name,
|
||||
id: item.id
|
||||
@@ -132,12 +136,12 @@ const handleAddConfirm = async (categoryName) => {
|
||||
name: categoryName,
|
||||
type: props.type
|
||||
})
|
||||
|
||||
|
||||
if (response.success) {
|
||||
showToast('分类创建成功')
|
||||
// 刷新列表
|
||||
await fetchOptions()
|
||||
|
||||
|
||||
// 如果是单选模式,且当前没有选值或就是为了新增,则自动选中
|
||||
if (!props.multiple) {
|
||||
emit('update:modelValue', categoryName)
|
||||
@@ -152,9 +156,12 @@ const handleAddConfirm = async (categoryName) => {
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.type, () => {
|
||||
fetchOptions()
|
||||
})
|
||||
watch(
|
||||
() => props.type,
|
||||
() => {
|
||||
fetchOptions()
|
||||
}
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
fetchOptions()
|
||||
@@ -175,8 +182,10 @@ const isSelected = (item) => {
|
||||
|
||||
// 是否全部选中
|
||||
const isAllSelected = computed(() => {
|
||||
if (!props.multiple || displayOptions.value.length === 0) return false
|
||||
return displayOptions.value.every(item => props.modelValue.includes(item.text))
|
||||
if (!props.multiple || displayOptions.value.length === 0) {
|
||||
return false
|
||||
}
|
||||
return displayOptions.value.every((item) => props.modelValue.includes(item.text))
|
||||
})
|
||||
|
||||
// 是否有任何选中
|
||||
@@ -208,13 +217,15 @@ const toggleItem = (item) => {
|
||||
|
||||
// 切换全选
|
||||
const toggleAll = () => {
|
||||
if (!props.multiple) return
|
||||
|
||||
if (!props.multiple) {
|
||||
return
|
||||
}
|
||||
|
||||
if (isAllSelected.value) {
|
||||
emit('update:modelValue', [])
|
||||
emit('change', [])
|
||||
} else {
|
||||
const allValues = displayOptions.value.map(item => item.text)
|
||||
const allValues = displayOptions.value.map((item) => item.text)
|
||||
emit('update:modelValue', allValues)
|
||||
emit('change', allValues)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
<template>
|
||||
<div class="global-add-bill">
|
||||
<!-- Floating Add Bill Button -->
|
||||
<div class="floating-add" @click="openAddBill">
|
||||
<div
|
||||
class="floating-add"
|
||||
@click="openAddBill"
|
||||
>
|
||||
<van-icon name="plus" />
|
||||
</div>
|
||||
|
||||
@@ -11,12 +14,27 @@
|
||||
title="记一笔"
|
||||
height="75%"
|
||||
>
|
||||
<van-tabs v-model:active="activeTab" shrink>
|
||||
<van-tab title="一句话录账" name="one">
|
||||
<OneLineBillAdd :key="componentKey" @success="handleSuccess" />
|
||||
<van-tabs
|
||||
v-model:active="activeTab"
|
||||
shrink
|
||||
>
|
||||
<van-tab
|
||||
title="一句话录账"
|
||||
name="one"
|
||||
>
|
||||
<OneLineBillAdd
|
||||
:key="componentKey"
|
||||
@success="handleSuccess"
|
||||
/>
|
||||
</van-tab>
|
||||
<van-tab title="手动录账" name="manual">
|
||||
<ManualBillAdd :key="componentKey" @success="handleSuccess" />
|
||||
<van-tab
|
||||
title="手动录账"
|
||||
name="manual"
|
||||
>
|
||||
<ManualBillAdd
|
||||
:key="componentKey"
|
||||
@success="handleSuccess"
|
||||
/>
|
||||
</van-tab>
|
||||
</van-tabs>
|
||||
</PopupContainer>
|
||||
@@ -79,6 +97,6 @@ const handleSuccess = () => {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
background-color: #fff;
|
||||
background-color: var(--van-background-2);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -12,30 +12,50 @@
|
||||
<!-- 头部区域 -->
|
||||
<div class="popup-header-fixed">
|
||||
<!-- 标题行 (无子标题且有操作时使用 Grid 布局) -->
|
||||
<div class="header-title-row" :class="{ 'has-actions': !subtitle && hasActions }">
|
||||
<h3 class="popup-title">{{ title }}</h3>
|
||||
<div
|
||||
class="header-title-row"
|
||||
:class="{ 'has-actions': !subtitle && hasActions }"
|
||||
>
|
||||
<h3 class="popup-title">
|
||||
{{ title }}
|
||||
</h3>
|
||||
<!-- 无子标题时,操作按钮与标题同行 -->
|
||||
<div v-if="!subtitle && hasActions" class="header-actions-inline">
|
||||
<slot name="header-actions"></slot>
|
||||
<div
|
||||
v-if="!subtitle && hasActions"
|
||||
class="header-actions-inline"
|
||||
>
|
||||
<slot name="header-actions" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 子标题/统计信息 -->
|
||||
<div v-if="subtitle" class="header-stats">
|
||||
<span class="stats-text" v-html="subtitle" />
|
||||
<div
|
||||
v-if="subtitle"
|
||||
class="header-stats"
|
||||
>
|
||||
<span
|
||||
class="stats-text"
|
||||
v-html="subtitle"
|
||||
/>
|
||||
<!-- 额外操作插槽 -->
|
||||
<slot v-if="hasActions" name="header-actions"></slot>
|
||||
<slot
|
||||
v-if="hasActions"
|
||||
name="header-actions"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 内容区域(可滚动) -->
|
||||
<div class="popup-scroll-content">
|
||||
<slot></slot>
|
||||
<slot />
|
||||
</div>
|
||||
|
||||
<!-- 底部页脚,固定不可滚动 -->
|
||||
<div v-if="slots.footer" class="popup-footer-fixed">
|
||||
<slot name="footer"></slot>
|
||||
<div
|
||||
v-if="slots.footer"
|
||||
class="popup-footer-fixed"
|
||||
>
|
||||
<slot name="footer" />
|
||||
</div>
|
||||
</div>
|
||||
</van-popup>
|
||||
@@ -47,24 +67,24 @@ import { computed, useSlots } from 'vue'
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean,
|
||||
required: true,
|
||||
required: true
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
default: '',
|
||||
default: ''
|
||||
},
|
||||
subtitle: {
|
||||
type: String,
|
||||
default: '',
|
||||
default: ''
|
||||
},
|
||||
height: {
|
||||
type: String,
|
||||
default: '80%',
|
||||
default: '80%'
|
||||
},
|
||||
closeable: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
default: true
|
||||
}
|
||||
})
|
||||
|
||||
const emit = defineEmits(['update:modelValue'])
|
||||
@@ -74,7 +94,7 @@ const slots = useSlots()
|
||||
// 双向绑定
|
||||
const visible = computed({
|
||||
get: () => props.modelValue,
|
||||
set: (value) => emit('update:modelValue', value),
|
||||
set: (value) => emit('update:modelValue', value)
|
||||
})
|
||||
|
||||
// 判断是否有操作按钮
|
||||
@@ -91,8 +111,8 @@ const hasActions = computed(() => !!slots['header-actions'])
|
||||
.popup-header-fixed {
|
||||
flex-shrink: 0;
|
||||
padding: 16px;
|
||||
background-color: var(--van-background-2, #f7f8fa);
|
||||
border-bottom: 1px solid var(--van-border-color, #ebedf0);
|
||||
background-color: var(--van-background-2);
|
||||
border-bottom: 1px solid var(--van-border-color);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
@@ -121,7 +141,7 @@ const hasActions = computed(() => !!slots['header-actions'])
|
||||
font-weight: 500;
|
||||
margin: 0;
|
||||
text-align: center;
|
||||
color: var(--van-text-color, #323233);
|
||||
color: var(--van-text-color);
|
||||
/*超出长度*/
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -139,7 +159,7 @@ const hasActions = computed(() => !!slots['header-actions'])
|
||||
.stats-text {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
color: var(--van-text-color-2, #646566);
|
||||
color: var(--van-text-color-2);
|
||||
grid-column: 2;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -159,8 +179,8 @@ const hasActions = computed(() => !!slots['header-actions'])
|
||||
|
||||
.popup-footer-fixed {
|
||||
flex-shrink: 0;
|
||||
border-top: 1px solid var(--van-border-color, #ebedf0);
|
||||
background-color: var(--van-background-2, #f7f8fa);
|
||||
border-top: 1px solid var(--van-border-color);
|
||||
background-color: var(--van-background-2);
|
||||
padding: 12px 16px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
<template>
|
||||
<div class="reason-group-list-v2">
|
||||
<van-empty v-if="groups.length === 0 && !loading" description="暂无数据" />
|
||||
|
||||
<van-cell-group v-else inset>
|
||||
<van-cell
|
||||
v-for="group in groups"
|
||||
<van-empty
|
||||
v-if="groups.length === 0 && !loading"
|
||||
description="暂无数据"
|
||||
/>
|
||||
|
||||
<van-cell-group
|
||||
v-else
|
||||
inset
|
||||
>
|
||||
<van-cell
|
||||
v-for="group in groups"
|
||||
:key="group.reason"
|
||||
clickable
|
||||
@click="handleGroupClick(group)"
|
||||
@@ -12,7 +18,7 @@
|
||||
>
|
||||
<template #title>
|
||||
<div class="group-header">
|
||||
<van-checkbox
|
||||
<van-checkbox
|
||||
v-if="selectable"
|
||||
:model-value="isSelected(group.reason)"
|
||||
@click.stop="handleToggleSelection(group.reason)"
|
||||
@@ -24,23 +30,26 @@
|
||||
</template>
|
||||
<template #label>
|
||||
<div class="group-info">
|
||||
<van-tag
|
||||
:type="getTypeColor(group.sampleType)"
|
||||
<van-tag
|
||||
:type="getTypeColor(group.sampleType)"
|
||||
size="medium"
|
||||
style="margin-right: 8px;"
|
||||
style="margin-right: 8px"
|
||||
>
|
||||
{{ getTypeName(group.sampleType) }}
|
||||
</van-tag>
|
||||
<van-tag
|
||||
v-if="group.sampleClassify"
|
||||
type="primary"
|
||||
<van-tag
|
||||
v-if="group.sampleClassify"
|
||||
type="primary"
|
||||
size="medium"
|
||||
style="margin-right: 8px;"
|
||||
style="margin-right: 8px"
|
||||
>
|
||||
{{ group.sampleClassify }}
|
||||
</van-tag>
|
||||
<span class="count-text">{{ group.count }} 条</span>
|
||||
<span v-if="group.totalAmount" class="amount-text">
|
||||
<span
|
||||
v-if="group.totalAmount"
|
||||
class="amount-text"
|
||||
>
|
||||
¥{{ Math.abs(group.totalAmount).toFixed(2) }}
|
||||
</span>
|
||||
</div>
|
||||
@@ -59,8 +68,8 @@
|
||||
height="75%"
|
||||
>
|
||||
<template #header-actions>
|
||||
<van-button
|
||||
type="primary"
|
||||
<van-button
|
||||
type="primary"
|
||||
size="small"
|
||||
class="batch-classify-btn"
|
||||
@click.stop="handleBatchClassify(selectedGroup)"
|
||||
@@ -68,7 +77,7 @@
|
||||
批量分类
|
||||
</van-button>
|
||||
</template>
|
||||
|
||||
|
||||
<TransactionList
|
||||
:transactions="groupTransactions"
|
||||
:loading="transactionLoading"
|
||||
@@ -92,7 +101,10 @@
|
||||
title="批量设置分类"
|
||||
height="60%"
|
||||
>
|
||||
<van-form ref="batchFormRef" class="setting-form">
|
||||
<van-form
|
||||
ref="batchFormRef"
|
||||
class="setting-form"
|
||||
>
|
||||
<van-cell-group inset>
|
||||
<!-- 显示选中的摘要 -->
|
||||
<van-field
|
||||
@@ -101,7 +113,7 @@
|
||||
readonly
|
||||
input-align="left"
|
||||
/>
|
||||
|
||||
|
||||
<!-- 显示记录数量 -->
|
||||
<van-field
|
||||
:model-value="`${batchGroup?.count || 0} 条`"
|
||||
@@ -111,24 +123,42 @@
|
||||
/>
|
||||
|
||||
<!-- 交易类型 -->
|
||||
<van-field name="type" label="交易类型">
|
||||
<van-field
|
||||
name="type"
|
||||
label="交易类型"
|
||||
>
|
||||
<template #input>
|
||||
<van-radio-group v-model="batchForm.type" direction="horizontal">
|
||||
<van-radio :name="0">支出</van-radio>
|
||||
<van-radio :name="1">收入</van-radio>
|
||||
<van-radio :name="2">不计</van-radio>
|
||||
<van-radio-group
|
||||
v-model="batchForm.type"
|
||||
direction="horizontal"
|
||||
>
|
||||
<van-radio :name="0">
|
||||
支出
|
||||
</van-radio>
|
||||
<van-radio :name="1">
|
||||
收入
|
||||
</van-radio>
|
||||
<van-radio :name="2">
|
||||
不计
|
||||
</van-radio>
|
||||
</van-radio-group>
|
||||
</template>
|
||||
</van-field>
|
||||
|
||||
<!-- 分类选择 -->
|
||||
<van-field name="classify" label="分类">
|
||||
<van-field
|
||||
name="classify"
|
||||
label="分类"
|
||||
>
|
||||
<template #input>
|
||||
<span v-if="!batchForm.classify" style="opacity: 0.4;">请选择分类</span>
|
||||
<span
|
||||
v-if="!batchForm.classify"
|
||||
style="opacity: 0.4"
|
||||
>请选择分类</span>
|
||||
<span v-else>{{ batchForm.classify }}</span>
|
||||
</template>
|
||||
</van-field>
|
||||
|
||||
|
||||
<!-- 分类选择组件 -->
|
||||
<ClassifySelector
|
||||
v-model="batchForm.classify"
|
||||
@@ -138,9 +168,9 @@
|
||||
</van-form>
|
||||
<template #footer>
|
||||
<van-button
|
||||
round
|
||||
block
|
||||
type="primary"
|
||||
round
|
||||
block
|
||||
type="primary"
|
||||
@click="handleConfirmBatchUpdate"
|
||||
>
|
||||
确定
|
||||
@@ -152,13 +182,7 @@
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, watch, onBeforeUnmount } from 'vue'
|
||||
import {
|
||||
showToast,
|
||||
showSuccessToast,
|
||||
showLoadingToast,
|
||||
closeToast,
|
||||
showConfirmDialog
|
||||
} from 'vant'
|
||||
import { showToast, showSuccessToast, showLoadingToast, closeToast, showConfirmDialog } from 'vant'
|
||||
import { getReasonGroups, batchUpdateByReason, getTransactionList } from '@/api/transactionRecord'
|
||||
import ClassifySelector from './ClassifySelector.vue'
|
||||
import TransactionList from './TransactionList.vue'
|
||||
@@ -212,9 +236,12 @@ const batchForm = ref({
|
||||
})
|
||||
|
||||
// 监听交易类型变化,重新加载分类
|
||||
watch(() => batchForm.value.type, (newVal) => {
|
||||
batchForm.value.classify = ''
|
||||
})
|
||||
watch(
|
||||
() => batchForm.value.type,
|
||||
(newVal) => {
|
||||
batchForm.value.classify = ''
|
||||
}
|
||||
)
|
||||
|
||||
// 获取类型名称
|
||||
const getTypeName = (type) => {
|
||||
@@ -256,8 +283,10 @@ const handleGroupClick = async (group) => {
|
||||
|
||||
// 加载分组的交易记录
|
||||
const loadGroupTransactions = async () => {
|
||||
if (transactionFinished.value || !selectedGroup.value) return
|
||||
|
||||
if (transactionFinished.value || !selectedGroup.value) {
|
||||
return
|
||||
}
|
||||
|
||||
transactionLoading.value = true
|
||||
try {
|
||||
const res = await getTransactionList({
|
||||
@@ -265,17 +294,17 @@ const loadGroupTransactions = async () => {
|
||||
pageIndex: transactionPageIndex.value,
|
||||
pageSize: transactionPageSize.value
|
||||
})
|
||||
|
||||
|
||||
if (res.success) {
|
||||
const newData = res.data || []
|
||||
groupTransactions.value = [...groupTransactions.value, ...newData]
|
||||
groupTransactionsTotal.value = res.total || 0
|
||||
|
||||
|
||||
// 判断是否还有更多数据
|
||||
if (newData.length < transactionPageSize.value) {
|
||||
transactionFinished.value = true
|
||||
}
|
||||
|
||||
|
||||
transactionPageIndex.value++
|
||||
} else {
|
||||
showToast(res.message || '获取交易记录失败')
|
||||
@@ -323,7 +352,7 @@ const handleConfirmBatchUpdate = async () => {
|
||||
try {
|
||||
// 表单验证
|
||||
await batchFormRef.value?.validate()
|
||||
|
||||
|
||||
// 二次确认
|
||||
await showConfirmDialog({
|
||||
title: '确认批量设置',
|
||||
@@ -352,21 +381,19 @@ const handleConfirmBatchUpdate = async () => {
|
||||
await refresh()
|
||||
// 通知父组件数据已更改
|
||||
emit('data-changed')
|
||||
try {
|
||||
try {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(
|
||||
'transactions-changed',
|
||||
{
|
||||
detail: {
|
||||
reason: batchGroup.value.reason
|
||||
}
|
||||
})
|
||||
)
|
||||
} catch(e) {
|
||||
new CustomEvent('transactions-changed', {
|
||||
detail: {
|
||||
reason: batchGroup.value.reason
|
||||
}
|
||||
})
|
||||
)
|
||||
} catch (e) {
|
||||
console.error('触发全局 transactions-changed 事件失败:', e)
|
||||
}
|
||||
// 关闭弹窗
|
||||
showTransactionList.value = false
|
||||
}
|
||||
// 关闭弹窗
|
||||
showTransactionList.value = false
|
||||
} else {
|
||||
showToast(res.message || '批量更新失败')
|
||||
}
|
||||
@@ -398,18 +425,18 @@ const handleTransactionClick = (transaction) => {
|
||||
|
||||
// 处理分组中的删除事件
|
||||
const handleGroupTransactionDelete = async (transactionId) => {
|
||||
groupTransactions.value = groupTransactions.value.filter(t => t.id !== transactionId)
|
||||
groupTransactions.value = groupTransactions.value.filter((t) => t.id !== transactionId)
|
||||
groupTransactionsTotal.value = Math.max(0, (groupTransactionsTotal.value || 0) - 1)
|
||||
|
||||
if(groupTransactions.value.length === 0 && !transactionFinished.value) {
|
||||
if (groupTransactions.value.length === 0 && !transactionFinished.value) {
|
||||
// 如果当前页数据为空且未加载完,则尝试加载下一页
|
||||
await loadGroupTransactions()
|
||||
}
|
||||
|
||||
if(groupTransactions.value.length === 0){
|
||||
if (groupTransactions.value.length === 0) {
|
||||
// 如果删除后当前分组没有交易了,关闭弹窗
|
||||
showTransactionList.value = false
|
||||
groups.value = groups.value.filter(g => g.reason !== selectedGroup.value.reason)
|
||||
groups.value = groups.value.filter((g) => g.reason !== selectedGroup.value.reason)
|
||||
selectedGroup.value = null
|
||||
total.value--
|
||||
}
|
||||
@@ -433,10 +460,12 @@ const onGlobalTransactionDeleted = () => {
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener && window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
|
||||
window.addEventListener &&
|
||||
window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener && window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
|
||||
window.removeEventListener &&
|
||||
window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
|
||||
})
|
||||
|
||||
// 当有交易新增/修改/批量更新时的刷新监听
|
||||
@@ -451,10 +480,12 @@ const onGlobalTransactionsChanged = () => {
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener && window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
|
||||
window.addEventListener &&
|
||||
window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener && window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
|
||||
window.removeEventListener &&
|
||||
window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
|
||||
})
|
||||
|
||||
// 处理账单保存后的回调
|
||||
@@ -471,8 +502,10 @@ const handleTransactionSaved = async () => {
|
||||
* 加载数据(支持分页)
|
||||
*/
|
||||
const loadData = async () => {
|
||||
if (finished.value) return
|
||||
|
||||
if (finished.value) {
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await getReasonGroups(pageIndex.value, props.pageSize)
|
||||
@@ -480,14 +513,14 @@ const loadData = async () => {
|
||||
const newData = res.data || []
|
||||
groups.value = [...groups.value, ...newData]
|
||||
total.value = res.total || 0
|
||||
|
||||
|
||||
// 判断是否还有更多数据
|
||||
if (groups.value.length >= total.value) {
|
||||
finished.value = true
|
||||
}
|
||||
|
||||
|
||||
pageIndex.value++
|
||||
|
||||
|
||||
emit('data-loaded', {
|
||||
groups: groups.value,
|
||||
total: total.value,
|
||||
@@ -522,7 +555,7 @@ const refresh = async () => {
|
||||
*/
|
||||
const getList = (onlySelected = false) => {
|
||||
if (onlySelected && props.selectable) {
|
||||
return groups.value.filter(g => selectedReasons.value.has(g.reason))
|
||||
return groups.value.filter((g) => selectedReasons.value.has(g.reason))
|
||||
}
|
||||
return [...groups.value]
|
||||
}
|
||||
@@ -564,7 +597,7 @@ const clearSelection = () => {
|
||||
* 全选
|
||||
*/
|
||||
const selectAll = () => {
|
||||
selectedReasons.value = new Set(groups.value.map(g => g.reason))
|
||||
selectedReasons.value = new Set(groups.value.map((g) => g.reason))
|
||||
}
|
||||
|
||||
// 暴露方法给父组件
|
||||
@@ -627,13 +660,13 @@ defineExpose({
|
||||
|
||||
.count-text {
|
||||
font-size: 13px;
|
||||
color: #969799;
|
||||
color: var(--van-text-color-2);
|
||||
}
|
||||
|
||||
.amount-text {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #ff976a;
|
||||
color: var(--van-orange);
|
||||
}
|
||||
|
||||
:deep(.van-cell-group--inset) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user