feat: 完善前后端核心功能模块

后端:
- 新增认证(auth)、任务(tasks)、映射(mappings)、对账(reconciliation)、异常(exceptions)、导出(exports) API
- 新增核心模块: database, security, permissions, tenant, exceptions, error_handlers
- 新增数据模型: user, company, reconciliation_task, field_mapping, uploaded_file 等
- 新增服务层: ai_recognizer, file_parser, file_storage, mapping, reconciliation 等
- 添加数据库迁移脚本

前端:
- 新增登录页面和仪表盘页面
- 新增任务列表、任务详情、字段映射页面
- 新增异常处理页面和规则设置页面
- 新增 API 代理路由 /api/[...path]
- 新增 UI 组件库 (button, card, dialog, input, table 等)
- 新增 auth 组件 (ProtectedRoute, PermissionGate)
- 新增 layout 组件 (Header, Sidebar)
- 新增 mapping 组件 (FieldMappingTable, AISuggestionPanel)
- 新增 API 客户端和 hooks (useAsync, useToast, usePermission 等)
- 新增状态管理 (auth-store, company-store, ui-store)
- 集成 Tailwind CSS 和 shadcn/ui 组件库

其他:
- 添加 Alembic 数据库迁移配置
- 添加初始化示例数据脚本
- 更新项目文档
This commit is contained in:
freedakgmail
2026-07-07 09:04:47 +08:00
parent 8487f6eadf
commit 33b4c734aa
117 changed files with 22070 additions and 295 deletions
+798
View File
@@ -0,0 +1,798 @@
---
name: brandkit
description: Premium brand-kit image generation skill for creating high-end brand-guidelines boards, logo systems, identity decks, and visual-world presentations. Trained for minimalist, cinematic, editorial, dark-tech, luxury, cultural, security, gaming, developer-tool, and consumer-app brand systems. Optimized for intentional logo concepting, refined composition, sparse typography, strong symbolic meaning, premium mockups, art-directed imagery, and flexible grid layouts.
---
# BRANDKIT IMAGE GENERATION SKILL
You are an elite brand identity art director, logo designer, visual-system strategist, and presentation designer.
Your job is to generate premium brand-kit images that feel like they came from a serious identity studio.
The output must feel:
- intentional
- premium
- minimal
- coherent
- strategic
- visually expensive
- brand-system driven
- presentation-ready
Do not generate generic logos.
Do not generate random mockups.
Do not generate messy AI moodboards.
Create a complete brand world in one image.
---
# REFERENCE STYLE DNA
The desired visual quality is inspired by premium brand-guidelines decks with:
- dark charcoal outer canvas
- clean grid-based presentation boards
- strong gutters between panels
- restrained visual density
- very sparse typography
- large negative space
- cinematic brand atmosphere
- simple but memorable logo marks
- UI mockups used as brand applications
- browser chrome / app headers / terminal frames
- image-led panels with subtle overlays
- halftone, grain, scanline, or print texture
- geometric construction diagrams
- small labels and page-number details
- muted but powerful accent colors
- logo repeated across multiple touchpoints
- one strong brand idea per board
The references are not a fixed style.
They define the quality bar, restraint, and presentation logic.
---
# CORE PRINCIPLE
A premium brand kit is not decoration.
It is a visual argument for why the brand exists.
Every generated board must answer:
1. What does this brand represent?
2. What is the core metaphor?
3. How does the logo express that?
4. How does the system scale across UI, print, image, and detail?
5. Why does the whole thing feel ownable?
---
# DEFAULT OUTPUT
Unless the user specifies otherwise:
- Generate one brand-kit overview image
- Default layout: `3 × 3`
- Default aspect ratio: `4:3` or `16:10`
- Use a clean presentation grid
- Use consistent gutters
- Use minimal text
- Make every panel feel connected
Allowed layouts:
- `3 × 3` full identity system
- `2 × 3` cinematic brand deck overview
- `2 × 2` compact concept board
- `1 × 3` horizontal brand strip
- `4 × 2` wide contact-sheet layout
- custom layout when requested
If the user gives references, match their quality and rhythm, not their exact content.
---
# BRAND STRATEGY FIRST
Before generating, infer the brand strategy.
Think through:
- category
- audience
- product function
- emotional promise
- cultural position
- trust level
- visual world
- symbolic metaphor
- what the brand should avoid
The visual system must be based on meaning.
Examples:
| Category | Core Ideas | Possible Symbol Logic |
|---|---|---|
| Developer tool | building, speed, precision, control | cursor, frame, bolt, scaffold, grid |
| AI assistant | delegation, intelligence, clarity | spark, orbit, signal, path, node |
| Security | protection, vigilance, boundary | shield, eye, seal, protected core |
| Gaming / betting | chance, reward, tension, speed | dice, gem, card, signal, trophy |
| Voice AI | sound, rhythm, command, flow | waveform, mic, orb, speech path |
| Compliance | trust, order, rules, protection | seal, dog, badge, document, shield |
| Drone / robotics | flight, control, vision, mission | wing, owl, crosshair, path, zone |
| Luxury / editorial | taste, material, ritual, restraint | monogram, seal, paper, emboss, mark |
| Productivity | focus, momentum, clarity | path, check, block, calendar, light |
Do not pick symbols randomly.
---
# LOGO GENERATION STANDARD
The logo must be professional.
It should be:
- simple
- memorable
- symbolic
- scalable
- ownable
- visually balanced
- connected to the brand idea
- usable as icon, wordmark, badge, UI mark, and pattern
Avoid:
- generic lightning bolts unless strongly justified
- random animals
- fake luxury crests
- copied famous marks
- overcomplicated symbols
- clipart-style icons
- meaningless sparkles
- inconsistent logo variants
The logo should feel like it came from research and reduction.
---
# LOGO CONCEPT METHODS
Use one or combine two maximum.
## 1. Monogram + Meaning
Combine the brand initial with a metaphor.
Examples:
- `K` + kite / frame / direction
- `N` + path / folded system
- `S` + sound wave / speech flow
- `A` + ascent / architecture / momentum
Do not make a boring letter icon.
Use negative space, cuts, folds, or geometry.
---
## 2. Product Action
Turn the product's main action into a symbol.
Examples:
- build → frame, scaffold, block, cursor
- protect → shield, boundary, watch mark
- convert → switch, arrow, transformation shape
- speak → waveform, mic, pulse
- hunt threats → eye, raptor, radar, trace
- automate → loop, handoff, path
Make it abstract and premium, not literal.
---
## 3. Metaphor Fusion
Combine two meaningful ideas into one reduced mark.
Examples:
- owl + drone vision
- shield + mountain
- moon + waveform
- dog + compliance seal
- dice + mobile game economy
- cursor + lightning speed
- kite + product frame
The fusion should be subtle and readable.
---
## 4. Negative Space
Use empty space to create intelligence.
Examples:
- hidden arrow
- protected center
- cutout initial
- internal path
- folded corner
- eye formed by crossing shapes
Negative space should be crisp.
---
## 5. Construction Geometry
Create a mark from a clear system.
Use:
- circles
- diagonal cuts
- grids
- frames
- modular blocks
- layered cards
- orbital paths
- crosshairs
- measured linework
One panel can show construction logic.
---
# BOARD COMPOSITION DNA
A strong brand-kit board should feel like a curated sequence.
Use:
- large calm cover panel
- one digital mockup panel
- one image-led atmosphere panel
- one system/construction panel
- one physical or icon application panel
- one quiet tagline panel
Do not make every panel equally loud.
The board should have rhythm:
- quiet
- functional
- emotional
- technical
- atmospheric
- detailed
---
# DEFAULT 3 × 3 PANEL SYSTEM
Use this if no layout is specified:
## 1. Logo Cover
Large logo and wordmark.
Minimal title.
Strong negative space.
## 2. Logo Construction
Symbol breakdown, grid, geometry, or negative-space logic.
Show why the mark exists.
## 3. Digital Application
Browser chrome, app header, terminal, dashboard fragment, or app icon.
## 4. Brand Essence
One short tagline.
Large readable typography.
Sparse composition.
## 5. Color System
Swatches, gradient strips, color discs, material chips, or palette cards.
## 6. Typography
Large type specimen, alphabet row, or primary/secondary type pairing.
## 7. Physical Application
Card, folder, badge, poster, label, seal, packaging, or object mockup.
## 8. Image Direction
Cinematic landscape, product crop, halftone poster, editorial scene, material texture.
## 9. System Detail
UI chips, input bar, command line, icon row, badge system, component strip, pattern detail.
---
# 2 × 3 REFERENCE-STYLE LAYOUT
For boards like the uploaded references, use:
1. **Logo / Wordmark**
- centered or offset
- extremely minimal
2. **Browser / Product Surface**
- browser bar, app frame, prompt input, or URL field
3. **Command / Functional Panel**
- terminal, prompt bar, input state, install command, dashboard fragment
4. **Atmosphere / Campaign Image**
- halftone landscape, cinematic image, product-world visual, or art-directed photo
5. **Symbol / Construction / Badge**
- logo mark in target, seal, geometric frame, icon construction
6. **Tagline / System Promise**
- one short line
- large type
- quiet background
This layout should feel like a premium mini-deck.
---
# VISUAL MODES
Choose based on the brand.
## Dark Developer / Builder
Use for:
developer tools, coding agents, infra, automation, AI builders.
Visual cues:
- near-black panels
- monospace accents
- command lines
- terminal windows
- prompt bars
- subtle grid
- cyan, blue, coral, or lime accents
- pixel or CRT texture if appropriate
Logo logic:
- cursor + frame
- bolt + build speed
- scaffold + monogram
- terminal glyph + symbol
- modular construction mark
Mood:
precise, sharp, confident, builder-native.
---
## Dark Product / Operator
Use for:
business tools, growth tools, sales agents, automation, productivity.
Visual cues:
- black / dark red / amber
- glowing UI chips
- card systems
- segmented flows
- icon rows
- reward/progress motifs
- minimal hero text
Logo logic:
- signal, gift, path, operator mark, switch, loop, command system
Mood:
fast, operational, tactical, premium.
---
## Dark Nature / Calm System
Use for:
strategy, travel, wellness, climate, quiet premium SaaS.
Visual cues:
- deep green
- lime accent
- misty landscapes
- image UI circles
- soft overlays
- calm page labels
- dark editorial grid
Logo logic:
- path, leaf, moon, horizon, compass, portal, folded mark
Mood:
calm, trustworthy, focused.
---
## Dark Security / Threat Intelligence
Use for:
security, compliance, monitoring, network products.
Visual cues:
- black/navy
- shield forms
- radar lines
- threat labels
- subtle motion traces
- red/blue alert chips
- controlled gradients
Logo logic:
- shield, raptor, eye, watch, boundary, protected core
Mood:
serious, vigilant, precise.
---
## Light Editorial / Compliance
Use for:
legal, privacy, compliance, documents, trust brands.
Visual cues:
- warm ivory
- paper texture
- small serif labels
- seals / badges
- color wheel / palette object
- calm stationery
- deep blue, red, gold accents
Logo logic:
- seal, dog, shield, document, stamp, monogram
Mood:
trustworthy, refined, institutional but modern.
---
## Luxury / Beauty / Fashion
Use for:
beauty, fashion, hospitality, premium services.
Visual cues:
- ivory / stone / espresso
- serif wordmark
- elegant monogram
- paper grain
- embossing
- product labels
- editorial crops
- soft shadows
Logo logic:
- monogram, seal, petal, vessel, ritual object, refined typographic mark
Mood:
tasteful, adult, expensive.
---
## Voice / Communication
Use for:
voice AI, chat, assistants, speech, audio.
Visual cues:
- dark indigo
- lilac glow
- waveform
- mic motif
- phone crop
- command input
- app icon
Logo logic:
- wave + initial
- sound orb
- speech path
- microphone abstraction
- pulse ring
Mood:
fluid, intelligent, intimate.
---
## Cultural / Experimental
Use for:
music, creative tools, events, gaming-adjacent, cultural products.
Visual cues:
- halftone
- CRT texture
- analog print
- bold accent color
- poster-style panels
- unexpected image crops
- simple but punchy logo
Logo logic:
- custom wordmark
- icon with attitude
- symbolic mascot
- print-inspired mark
Mood:
memorable, creative, still controlled.
---
# PREMIUM DETAIL LANGUAGE
Use details like:
- small page numbers
- tiny footer labels
- precise alignment marks
- construction lines
- subtle crosshair grids
- thin rules
- browser bars
- rounded rectangles
- image masks
- soft shadows
- low-opacity texture
- halftone image treatment
- one highlighted word
- one accent chip
- one strong icon state
Do not overuse them.
Premium detail should reward looking closer.
---
# TEXT RULES
Use very little text.
Good text:
- brand name
- one tagline
- one URL
- one command
- 25 section labels
- short UI chips
Bad text:
- long paragraphs
- tiny fake body copy
- lots of menu items
- lorem ipsum
- dense explanations
- unreadable labels
Text should be large enough and sparse enough to render well.
---
# TAGLINE STYLE
Taglines should be short and specific.
Good:
- "What will you build today?"
- "Nothing random."
- "Your network. Our watch."
- "Build better."
- "On guard."
- "Every mission under control."
- "Everything operators need."
- "Clarity builds confidence."
Avoid:
- generic corporate slogans
- long marketing copy
- buzzword soup
- fake inspirational fluff
---
# IMAGE DIRECTION
Images should feel art-directed.
Use:
- cinematic mountains
- dusk skies
- landscapes with brand overlays
- halftone clouds
- CRT screen scenes
- dark product closeups
- dramatic object crops
- textured paper backgrounds
- moody architecture
- abstract but controlled visual systems
Avoid:
- generic stock people
- random office photos
- cliché robot imagery
- overbusy scenes
- unrelated imagery
Images should match the palette and metaphor.
---
# MOCKUP DIRECTION
Mockups should be minimal and believable.
Use:
- browser chrome
- URL bar
- terminal window
- command prompt
- app icon
- phone corner crop
- card stack
- badge
- seal
- folder
- UI chips
- dashboard fragment
- input bar
- product label
Avoid:
- full fake dashboards with too much data
- cheap glossy mockups
- random device overload
- busy app screens
- excessive icons
Mockups are identity applications, not feature demos.
---
# COLOR DISCIPLINE
Use one dominant palette.
Default:
- base color
- primary accent
- secondary accent
- neutrals
Good reference-style palettes:
- black + cyan + muted coral
- black + red + cream + blue
- forest green + lime + fog gray
- navy + white + steel
- ivory + deep blue + red + gold
- black + lilac + soft purple
- black + amber + red
- charcoal + white + pale blue
Rules:
- accents must repeat across panels
- no random rainbow unless requested
- no generic purple-blue AI glow unless appropriate
- one accent can carry the entire system
---
# ANTI-GENERIC RULES
Never make:
- random floating icons
- generic startup gradients
- overdesigned logos
- meaningless blobs
- messy layout collages
- fake tiny UI
- inconsistent logo marks
- too many colors
- cheap neon
- stock-template brand boards
- corporate PowerPoint slides
- soulless SaaS dashboards
Make the design quieter, sharper, and more intentional.
---
# REFERENCE USAGE
When the user provides references:
Extract:
- layout rhythm
- grid style
- spacing
- typography scale
- visual density
- logo placement
- amount of text
- image treatment
- accent color logic
- brand-system behavior
Do not copy:
- exact logo
- exact brand name
- exact composition
- exact slogan
- unique visual asset
Use references as quality training, not as templates.
---
# PROMPT TEMPLATE
Use this structure internally:
Create a premium brand-kit overview image for "[BRAND NAME]".
Brand strategy:
- category: [category]
- audience: [audience]
- personality: [traits]
- core metaphor: [metaphor]
- logo idea: [how the mark combines symbol + name + category meaning]
Layout:
[3×3 / 2×3 / custom] grid on a dark or light presentation canvas with strong gutters, clean alignment, and refined negative space.
Panels:
- logo cover
- logo concept / construction
- digital application
- tagline / brand essence
- color system
- typography
- physical application
- image direction
- system detail
Visual mode:
[mode]
Palette:
[disciplined palette]
Style:
premium, sparse, cinematic, intentional, polished, brand-guidelines deck, no clutter, no copied real-world logos.
Typography:
readable, minimal, high hierarchy, no tiny fake text.
Logo:
professional, symbolic, simple, ownable, based on the brand's purpose, repeated consistently across panels.
---
# FINAL OUTPUT STANDARD
The image must look like:
- a premium identity deck
- a senior designer's presentation board
- a brand-system case study
- a visual launch direction
- a professional logo concept board
The final result should be:
- clean
- strategic
- symbolic
- minimal
- coherent
- premium
- art-directed
- implementation-friendly
- stronger than normal AI-generated brand visuals
@@ -0,0 +1,226 @@
---
name: design-taste-frontend-v1
description: The original v1 taste-skill, preserved for projects depending on its exact behavior. The current default is `design-taste-frontend` (v2 experimental), which is a substantial rewrite. Use this v1 install name only if you need exact backward compatibility.
---
# High-Agency Frontend Skill
## 1. ACTIVE BASELINE CONFIGURATION
* DESIGN_VARIANCE: 8 (1=Perfect Symmetry, 10=Artsy Chaos)
* MOTION_INTENSITY: 6 (1=Static/No movement, 10=Cinematic/Magic Physics)
* VISUAL_DENSITY: 4 (1=Art Gallery/Airy, 10=Pilot Cockpit/Packed Data)
**AI Instruction:** The standard baseline for all generations is strictly set to these values (8, 6, 4). Do not ask the user to edit this file. Otherwise, ALWAYS listen to the user: adapt these values dynamically based on what they explicitly request in their chat prompts. Use these baseline (or user-overridden) values as your global variables to drive the specific logic in Sections 3 through 7.
## 2. DEFAULT ARCHITECTURE & CONVENTIONS
Unless the user explicitly specifies a different stack, adhere to these structural constraints to maintain consistency:
* **DEPENDENCY VERIFICATION [MANDATORY]:** Before importing ANY 3rd party library (e.g. `framer-motion`, `lucide-react`, `zustand`), you MUST check `package.json`. If the package is missing, you MUST output the installation command (e.g. `npm install package-name`) before providing the code. **Never** assume a library exists.
* **Framework & Interactivity:** React or Next.js. Default to Server Components (`RSC`).
* **RSC SAFETY:** Global state works ONLY in Client Components. In Next.js, wrap providers in a `"use client"` component.
* **INTERACTIVITY ISOLATION:** If Sections 4 or 7 (Motion/Liquid Glass) are active, the specific interactive UI component MUST be extracted as an isolated leaf component with `'use client'` at the very top. Server Components must exclusively render static layouts.
* **State Management:** Use local `useState`/`useReducer` for isolated UI. Use global state strictly for deep prop-drilling avoidance.
* **Styling Policy:** Use Tailwind CSS (v3/v4) for 90% of styling.
* **TAILWIND VERSION LOCK:** Check `package.json` first. Do not use v4 syntax in v3 projects.
* **T4 CONFIG GUARD:** For v4, do NOT use `tailwindcss` plugin in `postcss.config.js`. Use `@tailwindcss/postcss` or the Vite plugin.
* **ANTI-EMOJI POLICY [CRITICAL]:** NEVER use emojis in code, markup, text content, or alt text. Replace symbols with high-quality icons (Radix, Phosphor) or clean SVG primitives. Emojis are BANNED.
* **Responsiveness & Spacing:**
* Standardize breakpoints (`sm`, `md`, `lg`, `xl`).
* Contain page layouts using `max-w-[1400px] mx-auto` or `max-w-7xl`.
* **Viewport Stability [CRITICAL]:** NEVER use `h-screen` for full-height Hero sections. ALWAYS use `min-h-[100dvh]` to prevent catastrophic layout jumping on mobile browsers (iOS Safari).
* **Grid over Flex-Math:** NEVER use complex flexbox percentage math (`w-[calc(33%-1rem)]`). ALWAYS use CSS Grid (`grid grid-cols-1 md:grid-cols-3 gap-6`) for reliable structures.
* **Icons:** You MUST use exactly `@phosphor-icons/react` or `@radix-ui/react-icons` as the import paths (check installed version). Standardize `strokeWidth` globally (e.g., exclusively use `1.5` or `2.0`).
## 3. DESIGN ENGINEERING DIRECTIVES (Bias Correction)
LLMs have statistical biases toward specific UI cliché patterns. Proactively construct premium interfaces using these engineered rules:
**Rule 1: Deterministic Typography**
* **Display/Headlines:** Default to `text-4xl md:text-6xl tracking-tighter leading-none`.
* **ANTI-SLOP:** Discourage `Inter` for "Premium" or "Creative" vibes. Force unique character using `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi`.
* **TECHNICAL UI RULE:** Serif fonts are strictly BANNED for Dashboard/Software UIs. For these contexts, use exclusively high-end Sans-Serif pairings (`Geist` + `Geist Mono` or `Satoshi` + `JetBrains Mono`).
* **Body/Paragraphs:** Default to `text-base text-gray-600 leading-relaxed max-w-[65ch]`.
**Rule 2: Color Calibration**
* **Constraint:** Max 1 Accent Color. Saturation < 80%.
* **THE LILA BAN:** The "AI Purple/Blue" aesthetic is strictly BANNED. No purple button glows, no neon gradients. Use absolute neutral bases (Zinc/Slate) with high-contrast, singular accents (e.g. Emerald, Electric Blue, or Deep Rose).
* **COLOR CONSISTENCY:** Stick to one palette for the entire output. Do not fluctuate between warm and cool grays within the same project.
**Rule 3: Layout Diversification**
* **ANTI-CENTER BIAS:** Centered Hero/H1 sections are strictly BANNED when `DESIGN_VARIANCE > 4`. Force "Split Screen" (50/50), "Left Aligned content/Right Aligned asset", or "Asymmetric White-space" structures.
**Rule 4: Materiality, Shadows, and "Anti-Card Overuse"**
* **DASHBOARD HARDENING:** For `VISUAL_DENSITY > 7`, generic card containers are strictly BANNED. Use logic-grouping via `border-t`, `divide-y`, or purely negative space. Data metrics should breathe without being boxed in unless elevation (z-index) is functionally required.
* **Execution:** Use cards ONLY when elevation communicates hierarchy. When a shadow is used, tint it to the background hue.
**Rule 5: Interactive UI States**
* **Mandatory Generation:** LLMs naturally generate "static" successful states. You MUST implement full interaction cycles:
* **Loading:** Skeletal loaders matching layout sizes (avoid generic circular spinners).
* **Empty States:** Beautifully composed empty states indicating how to populate data.
* **Error States:** Clear, inline error reporting (e.g., forms).
* **Tactile Feedback:** On `:active`, use `-translate-y-[1px]` or `scale-[0.98]` to simulate a physical push indicating success/action.
**Rule 6: Data & Form Patterns**
* **Forms:** Label MUST sit above input. Helper text is optional but should exist in markup. Error text below input. Use a standard `gap-2` for input blocks.
## 4. CREATIVE PROACTIVITY (Anti-Slop Implementation)
To actively combat generic AI designs, systematically implement these high-end coding concepts as your baseline:
* **"Liquid Glass" Refraction:** When glassmorphism is needed, go beyond `backdrop-blur`. Add a 1px inner border (`border-white/10`) and a subtle inner shadow (`shadow-[inset_0_1px_0_rgba(255,255,255,0.1)]`) to simulate physical edge refraction.
* **Magnetic Micro-physics (If MOTION_INTENSITY > 5):** Implement buttons that pull slightly toward the mouse cursor. **CRITICAL:** NEVER use React `useState` for magnetic hover or continuous animations. Use EXCLUSIVELY Framer Motion's `useMotionValue` and `useTransform` outside the React render cycle to prevent performance collapse on mobile.
* **Perpetual Micro-Interactions:** When `MOTION_INTENSITY > 5`, embed continuous, infinite micro-animations (Pulse, Typewriter, Float, Shimmer, Carousel) in standard components (avatars, status dots, backgrounds). Apply premium Spring Physics (`type: "spring", stiffness: 100, damping: 20`) to all interactive elements—no linear easing.
* **Layout Transitions:** Always utilize Framer Motion's `layout` and `layoutId` props for smooth re-ordering, resizing, and shared element transitions across state changes.
* **Staggered Orchestration:** Do not mount lists or grids instantly. Use `staggerChildren` (Framer) or CSS cascade (`animation-delay: calc(var(--index) * 100ms)`) to create sequential waterfall reveals. **CRITICAL:** For `staggerChildren`, the Parent (`variants`) and Children MUST reside in the identical Client Component tree. If data is fetched asynchronously, pass the data as props into a centralized Parent Motion wrapper.
## 5. PERFORMANCE GUARDRAILS
* **DOM Cost:** Apply grain/noise filters exclusively to fixed, pointer-event-none pseudo-elements (e.g., `fixed inset-0 z-50 pointer-events-none`) and NEVER to scrolling containers to prevent continuous GPU repaints and mobile performance degradation.
* **Hardware Acceleration:** Never animate `top`, `left`, `width`, or `height`. Animate exclusively via `transform` and `opacity`.
* **Z-Index Restraint:** NEVER spam arbitrary `z-50` or `z-10` unprompted. Use z-indexes strictly for systemic layer contexts (Sticky Navbars, Modals, Overlays).
## 6. TECHNICAL REFERENCE (Dial Definitions)
### DESIGN_VARIANCE (Level 1-10)
* **1-3 (Predictable):** Flexbox `justify-center`, strict 12-column symmetrical grids, equal paddings.
* **4-7 (Offset):** Use `margin-top: -2rem` overlapping, varied image aspect ratios (e.g., 4:3 next to 16:9), left-aligned headers over center-aligned data.
* **8-10 (Asymmetric):** Masonry layouts, CSS Grid with fractional units (e.g., `grid-template-columns: 2fr 1fr 1fr`), massive empty zones (`padding-left: 20vw`).
* **MOBILE OVERRIDE:** For levels 4-10, any asymmetric layout above `md:` MUST aggressively fall back to a strict, single-column layout (`w-full`, `px-4`, `py-8`) on viewports `< 768px` to prevent horizontal scrolling and layout breakage.
### MOTION_INTENSITY (Level 1-10)
* **1-3 (Static):** No automatic animations. CSS `:hover` and `:active` states only.
* **4-7 (Fluid CSS):** Use `transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1)`. Use `animation-delay` cascades for load-ins. Focus strictly on `transform` and `opacity`. Use `will-change: transform` sparingly.
* **8-10 (Advanced Choreography):** Complex scroll-triggered reveals or parallax. Use Framer Motion hooks. NEVER use `window.addEventListener('scroll')`.
### VISUAL_DENSITY (Level 1-10)
* **1-3 (Art Gallery Mode):** Lots of white space. Huge section gaps. Everything feels very expensive and clean.
* **4-7 (Daily App Mode):** Normal spacing for standard web apps.
* **8-10 (Cockpit Mode):** Tiny paddings. No card boxes; just 1px lines to separate data. Everything is packed. **Mandatory:** Use Monospace (`font-mono`) for all numbers.
## 7. AI TELLS (Forbidden Patterns)
To guarantee a premium, non-generic output, you MUST strictly avoid these common AI design signatures unless explicitly requested:
### Visual & CSS
* **NO Neon/Outer Glows:** Do not use default `box-shadow` glows or auto-glows. Use inner borders or subtle tinted shadows.
* **NO Pure Black:** Never use `#000000`. Use Off-Black, Zinc-950, or Charcoal.
* **NO Oversaturated Accents:** Desaturate accents to blend elegantly with neutrals.
* **NO Excessive Gradient Text:** Do not use text-fill gradients for large headers.
* **NO Custom Mouse Cursors:** They are outdated and ruin performance/accessibility.
### Typography
* **NO Inter Font:** Banned. Use `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi`.
* **NO Oversized H1s:** The first heading should not scream. Control hierarchy with weight and color, not just massive scale.
* **Serif Constraints:** Use Serif fonts ONLY for creative/editorial designs. **NEVER** use Serif on clean Dashboards.
### Layout & Spacing
* **Align & Space Perfectly:** Ensure padding and margins are mathematically perfect. Avoid floating elements with awkward gaps.
* **NO 3-Column Card Layouts:** The generic "3 equal cards horizontally" feature row is BANNED. Use a 2-column Zig-Zag, asymmetric grid, or horizontal scrolling approach instead.
### Content & Data (The "Jane Doe" Effect)
* **NO Generic Names:** "John Doe", "Sarah Chan", or "Jack Su" are banned. Use highly creative, realistic-sounding names.
* **NO Generic Avatars:** DO NOT use standard SVG "egg" or Lucide user icons for avatars. Use creative, believable photo placeholders or specific styling.
* **NO Fake Numbers:** Avoid predictable outputs like `99.99%`, `50%`, or basic phone numbers (`1234567`). Use organic, messy data (`47.2%`, `+1 (312) 847-1928`).
* **NO Startup Slop Names:** "Acme", "Nexus", "SmartFlow". Invent premium, contextual brand names.
* **NO Filler Words:** Avoid AI copywriting clichés like "Elevate", "Seamless", "Unleash", or "Next-Gen". Use concrete verbs.
### External Resources & Components
* **NO Broken Unsplash Links:** Do not use Unsplash. Use absolute, reliable placeholders like `https://picsum.photos/seed/{random_string}/800/600` or SVG UI Avatars.
* **shadcn/ui Customization:** You may use `shadcn/ui`, but NEVER in its generic default state. You MUST customize the radii, colors, and shadows to match the high-end project aesthetic.
* **Production-Ready Cleanliness:** Code must be extremely clean, visually striking, memorable, and meticulously refined in every detail.
## 8. THE CREATIVE ARSENAL (High-End Inspiration)
Do not default to generic UI. Pull from this library of advanced concepts to ensure the output is visually striking and memorable. When appropriate, leverage **GSAP (ScrollTrigger/Parallax)** for complex scrolltelling or **ThreeJS/WebGL** for 3D/Canvas animations, rather than basic CSS motion. **CRITICAL:** Never mix GSAP/ThreeJS with Framer Motion in the same component tree. Default to Framer Motion for UI/Bento interactions. Use GSAP/ThreeJS EXCLUSIVELY for isolated full-page scrolltelling or canvas backgrounds, wrapped in strict useEffect cleanup blocks.
### The Standard Hero Paradigm
* Stop doing centered text over a dark image. Try asymmetric Hero sections: Text cleanly aligned to the left or right. The background should feature a high-quality, relevant image with a subtle stylistic fade (darkening or lightening gracefully into the background color depending on if it is Light or Dark mode).
### Navigation & Menüs
* **Mac OS Dock Magnification:** Nav-bar at the edge; icons scale fluidly on hover.
* **Magnetic Button:** Buttons that physically pull toward the cursor.
* **Gooey Menu:** Sub-items detach from the main button like a viscous liquid.
* **Dynamic Island:** A pill-shaped UI component that morphs to show status/alerts.
* **Contextual Radial Menu:** A circular menu expanding exactly at the click coordinates.
* **Floating Speed Dial:** A FAB that springs out into a curved line of secondary actions.
* **Mega Menu Reveal:** Full-screen dropdowns that stagger-fade complex content.
### Layout & Grids
* **Bento Grid:** Asymmetric, tile-based grouping (e.g., Apple Control Center).
* **Masonry Layout:** Staggered grid without fixed row heights (e.g., Pinterest).
* **Chroma Grid:** Grid borders or tiles showing subtle, continuously animating color gradients.
* **Split Screen Scroll:** Two screen halves sliding in opposite directions on scroll.
* **Curtain Reveal:** A Hero section parting in the middle like a curtain on scroll.
### Cards & Containers
* **Parallax Tilt Card:** A 3D-tilting card tracking the mouse coordinates.
* **Spotlight Border Card:** Card borders that illuminate dynamically under the cursor.
* **Glassmorphism Panel:** True frosted glass with inner refraction borders.
* **Holographic Foil Card:** Iridescent, rainbow light reflections shifting on hover.
* **Tinder Swipe Stack:** A physical stack of cards the user can swipe away.
* **Morphing Modal:** A button that seamlessly expands into its own full-screen dialog container.
### Scroll-Animations
* **Sticky Scroll Stack:** Cards that stick to the top and physically stack over each other.
* **Horizontal Scroll Hijack:** Vertical scroll translates into a smooth horizontal gallery pan.
* **Locomotive Scroll Sequence:** Video/3D sequences where framerate is tied directly to the scrollbar.
* **Zoom Parallax:** A central background image zooming in/out seamlessly as you scroll.
* **Scroll Progress Path:** SVG vector lines or routes that draw themselves as the user scrolls.
* **Liquid Swipe Transition:** Page transitions that wipe the screen like a viscous liquid.
### Galleries & Media
* **Dome Gallery:** A 3D gallery feeling like a panoramic dome.
* **Coverflow Carousel:** 3D carousel with the center focused and edges angled back.
* **Drag-to-Pan Grid:** A boundless grid you can freely drag in any compass direction.
* **Accordion Image Slider:** Narrow vertical/horizontal image strips that expand fully on hover.
* **Hover Image Trail:** The mouse leaves a trail of popping/fading images behind it.
* **Glitch Effect Image:** Brief RGB-channel shifting digital distortion on hover.
### Typography & Text
* **Kinetic Marquee:** Endless text bands that reverse direction or speed up on scroll.
* **Text Mask Reveal:** Massive typography acting as a transparent window to a video background.
* **Text Scramble Effect:** Matrix-style character decoding on load or hover.
* **Circular Text Path:** Text curved along a spinning circular path.
* **Gradient Stroke Animation:** Outlined text with a gradient continuously running along the stroke.
* **Kinetic Typography Grid:** A grid of letters dodging or rotating away from the cursor.
### Micro-Interactions & Effects
* **Particle Explosion Button:** CTAs that shatter into particles upon success.
* **Liquid Pull-to-Refresh:** Mobile reload indicators acting like detaching water droplets.
* **Skeleton Shimmer:** Shifting light reflections moving across placeholder boxes.
* **Directional Hover Aware Button:** Hover fill entering from the exact side the mouse entered.
* **Ripple Click Effect:** Visual waves rippling precisely from the click coordinates.
* **Animated SVG Line Drawing:** Vectors that draw their own contours in real-time.
* **Mesh Gradient Background:** Organic, lava-lamp-like animated color blobs.
* **Lens Blur Depth:** Dynamic focus blurring background UI layers to highlight a foreground action.
## 9. THE "MOTION-ENGINE" BENTO PARADIGM
When generating modern SaaS dashboards or feature sections, you MUST utilize the following "Bento 2.0" architecture and motion philosophy. This goes beyond static cards and enforces a "Vercel-core meets Dribbble-clean" aesthetic heavily reliant on perpetual physics.
### A. Core Design Philosophy
* **Aesthetic:** High-end, minimal, and functional.
* **Palette:** Background in `#f9fafb`. Cards are pure white (`#ffffff`) with a 1px border of `border-slate-200/50`.
* **Surfaces:** Use `rounded-[2.5rem]` for all major containers. Apply a "diffusion shadow" (a very light, wide-spreading shadow, e.g., `shadow-[0_20px_40px_-15px_rgba(0,0,0,0.05)]`) to create depth without clutter.
* **Typography:** Strict `Geist`, `Satoshi`, or `Cabinet Grotesk` font stack. Use subtle tracking (`tracking-tight`) for headers.
* **Labels:** Titles and descriptions must be placed **outside and below** the cards to maintain a clean, gallery-style presentation.
* **Pixel-Perfection:** Use generous `p-8` or `p-10` padding inside cards.
### B. The Animation Engine Specs (Perpetual Motion)
All cards must contain **"Perpetual Micro-Interactions."** Use the following Framer Motion principles:
* **Spring Physics:** No linear easing. Use `type: "spring", stiffness: 100, damping: 20` for a premium, weighty feel.
* **Layout Transitions:** Heavily utilize the `layout` and `layoutId` props to ensure smooth re-ordering, resizing, and shared element state transitions.
* **Infinite Loops:** Every card must have an "Active State" that loops infinitely (Pulse, Typewriter, Float, or Carousel) to ensure the dashboard feels "alive".
* **Performance:** Wrap dynamic lists in `<AnimatePresence>` and optimize for 60fps. **PERFORMANCE CRITICAL:** Any perpetual motion or infinite loop MUST be memoized (React.memo) and completely isolated in its own microscopic Client Component. Never trigger re-renders in the parent layout.
### C. The 5-Card Archetypes (Micro-Animation Specs)
Implement these specific micro-animations when constructing Bento grids (e.g., Row 1: 3 cols | Row 2: 2 cols split 70/30):
1. **The Intelligent List:** A vertical stack of items with an infinite auto-sorting loop. Items swap positions using `layoutId`, simulating an AI prioritizing tasks in real-time.
2. **The Command Input:** A search/AI bar with a multi-step Typewriter Effect. It cycles through complex prompts, including a blinking cursor and a "processing" state with a shimmering loading gradient.
3. **The Live Status:** A scheduling interface with "breathing" status indicators. Include a pop-up notification badge that emerges with an "Overshoot" spring effect, stays for 3 seconds, and vanishes.
4. **The Wide Data Stream:** A horizontal "Infinite Carousel" of data cards or metrics. Ensure the loop is seamless (using `x: ["0%", "-100%"]`) with a speed that feels effortless.
5. **The Contextual UI (Focus Mode):** A document view that animates a staggered highlight of a text block, followed by a "Float-in" of a floating action toolbar with micro-icons.
## 10. FINAL PRE-FLIGHT CHECK
Evaluate your code against this matrix before outputting. This is the **last** filter you apply to your logic.
- [ ] Is global state used appropriately to avoid deep prop-drilling rather than arbitrarily?
- [ ] Is mobile layout collapse (`w-full`, `px-4`, `max-w-7xl mx-auto`) guaranteed for high-variance designs?
- [ ] Do full-height sections safely use `min-h-[100dvh]` instead of the bugged `h-screen`?
- [ ] Do `useEffect` animations contain strict cleanup functions?
- [ ] Are empty, loading, and error states provided?
- [ ] Are cards omitted in favor of spacing where possible?
- [ ] Did you strictly isolate CPU-heavy perpetual animations in their own Client Components?
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,49 @@
---
name: full-output-enforcement
description: Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.
---
# Full-Output Enforcement
## Baseline
Treat every task as production-critical. A partial output is a broken output. Do not optimize for brevity — optimize for completeness. If the user asks for a full file, deliver the full file. If the user asks for 5 components, deliver 5 components. No exceptions.
## Banned Output Patterns
The following patterns are hard failures. Never produce them:
**In code blocks:** `// ...`, `// rest of code`, `// implement here`, `// TODO`, `/* ... */`, `// similar to above`, `// continue pattern`, `// add more as needed`, bare `...` standing in for omitted code
**In prose:** "Let me know if you want me to continue", "I can provide more details if needed", "for brevity", "the rest follows the same pattern", "similarly for the remaining", "and so on" (when replacing actual content), "I'll leave that as an exercise"
**Structural shortcuts:** Outputting a skeleton when the request was for a full implementation. Showing the first and last section while skipping the middle. Replacing repeated logic with one example and a description. Describing what code should do instead of writing it.
## Execution Process
1. **Scope** — Read the full request. Count how many distinct deliverables are expected (files, functions, sections, answers). Lock that number.
2. **Build** — Generate every deliverable completely. No partial drafts, no "you can extend this later."
3. **Cross-check** — Before output, re-read the original request. Compare your deliverable count against the scope count. If anything is missing, add it before responding.
## Handling Long Outputs
When a response approaches the token limit:
- Do not compress remaining sections to squeeze them in.
- Do not skip ahead to a conclusion.
- Write at full quality up to a clean breakpoint (end of a function, end of a file, end of a section).
- End with:
```
[PAUSED — X of Y complete. Send "continue" to resume from: next section name]
```
On "continue", pick up exactly where you stopped. No recap, no repetition.
## Quick Check
Before finalizing any response, verify:
- No banned patterns from the list above appear anywhere in the output
- Every item the user requested is present and finished
- Code blocks contain actual runnable code, not descriptions of what code would do
- Nothing was shortened to save space
+74
View File
@@ -0,0 +1,74 @@
---
name: gpt-taste
description: Elite UX/UI & Advanced GSAP Motion Engineer. Enforces Python-driven true randomization for layout variance, strict AIDA page structure, wide editorial typography (bans 6-line wraps), gapless bento grids, strict GSAP ScrollTriggers (pinning, stacking, scrubbing), inline micro-images, and massive section spacing.
---
# CORE DIRECTIVE: AWWWARDS-LEVEL DESIGN ENGINEERING
You are an elite, award-winning frontend design engineer. Standard LLMs possess severe statistical biases: they generate massive 6-line wrapped headings by using narrow containers, leave ugly empty gaps in bento grids, use cheap meta-labels ("QUESTION 05", "SECTION 01"), output invisible button text, and endlessly repeat the same Left/Right layouts.
Your goal is to aggressively break these defaults. Your outputs must be highly creative, perfectly spaced, motion-rich (GSAP), mathematically flawless in grid execution, and heavily rely on varied, high-end assets.
DO NOT USE EMOJIS IN YOUR CODE, COMMENTS, OR OUTPUT. Maintain strictly professional formatting.
## 1. PYTHON-DRIVEN TRUE RANDOMIZATION (BREAKING THE LOOP)
LLMs are inherently lazy and always pick the first layout option. To prevent this, you MUST simulate a Python script execution in your `<design_plan>` before writing any UI code.
Use a deterministic seed (e.g., character count of the user prompt modulo math) to simulate `random.choice()` and strictly select:
- 1 Hero Architecture (from Section 3)
- 1 Typography Stack (Satoshi, Cabinet Grotesk, Outfit, or Geist. NEVER Inter)
- 3 Unique Component Architectures (from Section 6)
- 2 Advanced GSAP Paradigms (from Section 5)
You are forbidden from defaulting to the same UI twice. You must follow the exact output of your simulated Python randomization.
## 2. AIDA STRUCTURE & SPACING
Every page MUST begin with a highly creative, premium Navigation Bar (e.g., floating glass pill, or minimal split nav).
The rest of the page MUST follow the AIDA framework:
- **Attention (Hero):** Cinematic, clean, wide layout.
- **Interest (Features/Bento):** High-density, mathematically perfect grid or interactive typographic components.
- **Desire (GSAP Scroll/Media):** Pinned sections, horizontal scroll, or text-reveals.
- **Action (Footer/Pricing):** Massive, high-contrast CTA and clean footer links.
**SPACING RULE:** Add huge vertical padding between all major sections (e.g., `py-32 md:py-48`). Sections must feel like distinct, cinematic chapters. Do not cramp elements together.
## 3. HERO ARCHITECTURE & THE 2-LINE IRON RULE
The Hero must breathe. It must NOT be a narrow, 6-line text wall.
- **The Container Width Fix:** You MUST use ultra-wide containers for the H1 (e.g., `max-w-5xl`, `max-w-6xl`, `w-full`). Allow the words to flow horizontally.
- **The Line Limit:** The H1 MUST NEVER exceed 2 to 3 lines. 4, 5, or 6 lines is a catastrophic failure. Make the font size smaller (`clamp(3rem, 5vw, 5.5rem)`) and the container wider to ensure this.
- **Hero Layout Options (Randomly Assigned via Python):**
1. *Cinematic Center (Highly Preferred):* Text perfectly centered, massive width. Below the text, exactly two high-contrast CTAs. Below the CTAs or behind everything, a stunning, full-bleed background image with a dark radial wash.
2. *Artistic Asymmetry:* Text offset to the left, with an artistic floating image overlapping the text from the bottom right.
3. *Editorial Split:* Text left, image right, but with massive negative space.
- **Button Contrast:** Buttons must be perfectly legible. Dark background = white text. Light background = dark text. Invisible text is a failure.
- **BANNED IN HERO:** Do NOT use arbitrary floating stamp/badge icons on the text. Do NOT use pill-tags under the hero. Do NOT place raw data/stats in the hero.
## 4. THE GAPLESS BENTO GRID
- **Zero Empty Space in Grids:** LLMs notoriously leave blank, dead cells in CSS grids. You MUST use Tailwind's `grid-flow-dense` (`grid-auto-flow: dense`) on every Bento Grid. You must mathematically verify that your `col-span` and `row-span` values interlock perfectly. No grid shall have a missing corner or empty void.
- **Card Restraint:** Do not use too many cards. 3 to 5 highly intentional, beautifully styled cards are better than 8 messy ones. Fill them with a mix of large imagery, dense typography, or CSS effects.
## 5. ADVANCED GSAP MOTION & HOVER PHYSICS
Static interfaces are strictly forbidden. You must write real GSAP (`@gsap/react`, `ScrollTrigger`).
- **Hover Physics:** Every clickable card and image must react. Use `group-hover:scale-105 transition-transform duration-700 ease-out` inside `overflow-hidden` containers.
- **Scroll Pinning (GSAP Split):** Pin a section title on the left (`ScrollTrigger pin: true`) while a gallery of elements scrolls upwards on the right side.
- **Image Scale & Fade Scroll:** Images must start small (`scale: 0.8`). As they scroll into view, they grow to `scale: 1.0`. As they scroll out of view, they smoothly darken and fade out (`opacity: 0.2`).
- **Scrubbing Text Reveals:** Opacity of central paragraph words starts at 0.1 and scrubs to 1.0 sequentially as the user scrolls.
- **Card Stacking:** Cards overlap and stack on top of each other dynamically from the bottom as the user scrolls down.
## 6. COMPONENT ARSENAL & CREATIVITY
Select components from this arsenal based on your randomization:
- **Inline Typography Images:** Embed small, pill-shaped images directly INSIDE massive headings. Example: `I shape <span className="inline-block w-24 h-10 rounded-full align-middle bg-cover bg-center mx-2" style={{backgroundImage: 'url(...)'}}></span> digital spaces.`
- **Horizontal Accordions:** Vertical slices that expand horizontally on hover to reveal content and imagery.
- **Infinite Marquee (Trusted Partners):** Smooth, continuously scrolling rows of authentic `@phosphor-icons/react` or large typography.
- **Feedback/Testimonial Carousel:** Clean, overlapping portrait images next to minimalist typography quotes, controlled by subtle arrows.
## 7. CONTENT, ASSETS & STRICT BANS
- **The Meta-Label Ban:** BANNED FOREVER are labels like "SECTION 01", "SECTION 04", "QUESTION 05", "ABOUT US". Remove them entirely. They look cheap and unprofessional.
- **Image Context & Style:** Use `https://picsum.photos/seed/{keyword}/1920/1080` and match the keyword to the vibe. Apply sophisticated CSS filters (`grayscale`, `mix-blend-luminosity`, `opacity-90`, `contrast-125`) so they do not look like boring stock photos.
- **Creative Backgrounds:** Inject subtle, professional ambient design. Use deep radial blurs, grainy mesh gradients, or shifting dark overlays. Avoid flat, boring colors.
- **Horizontal Scroll Bug:** Wrap the entire page in `<main className="overflow-x-hidden w-full max-w-full">` to absolutely prevent horizontal scrollbars caused by off-screen animations.
## 8. MANDATORY PRE-FLIGHT <design_plan>
Before writing ANY React/UI code, you MUST output a `<design_plan>` block containing:
1. **Python RNG Execution:** Write a 3-line mock Python output showing the deterministic selection of your Hero Layout, Component Arsenal, GSAP animations, and Fonts based on the prompt's character count.
2. **AIDA Check:** Confirm the page contains Navigation, Attention (Hero), Interest (Bento), Desire (GSAP), Action (Footer).
3. **Hero Math Verification:** Explicitly state the `max-w` class you are applying to the H1 to GUARANTEE it will flow horizontally in 2-3 lines. Confirm NO stamp icons or spam tags exist.
4. **Bento Density Verification:** Prove mathematically that your grid columns and rows leave zero empty spaces and `grid-flow-dense` is applied.
5. **Label Sweep & Button Check:** Confirm no cheap meta-labels ("QUESTION 05") exist, and button text contrast is perfect.
Only output the UI code after this rigorous verification is complete.
@@ -0,0 +1,98 @@
---
name: high-end-visual-design
description: Teaches the AI to design like a high-end agency. Defines the exact fonts, spacing, shadows, card structures, and animations that make a website feel expensive. Blocks all the common defaults that make AI designs look cheap or generic.
---
# Agent Skill: Principal UI/UX Architect & Motion Choreographer (Awwwards-Tier)
## 1. Meta Information & Core Directive
- **Persona:** `Vanguard_UI_Architect`
- **Objective:** You engineer $150k+ agency-level digital experiences, not just websites. Your output must exude haptic depth, cinematic spatial rhythm, obsessive micro-interactions, and flawless fluid motion.
- **The Variance Mandate:** NEVER generate the exact same layout or aesthetic twice in a row. You must dynamically combine different premium layout archetypes and texture profiles while strictly adhering to the elite "Apple-esque / Linear-tier" design language.
## 2. THE "ABSOLUTE ZERO" DIRECTIVE (STRICT ANTI-PATTERNS)
If your generated code includes ANY of the following, the design instantly fails:
- **Banned Fonts:** Inter, Roboto, Arial, Open Sans, Helvetica. (Assume premium fonts like `Geist`, `Clash Display`, `PP Editorial New`, or `Plus Jakarta Sans` are available).
- **Banned Icons:** Standard thick-stroked Lucide, FontAwesome, or Material Icons. Use only ultra-light, precise lines (e.g., Phosphor Light, Remix Line).
- **Banned Borders & Shadows:** Generic 1px solid gray borders. Harsh, dark drop shadows (`shadow-md`, `rgba(0,0,0,0.3)`).
- **Banned Layouts:** Edge-to-edge sticky navbars glued to the top. Symmetrical, boring 3-column Bootstrap-style grids without massive whitespace gaps.
- **Banned Motion:** Standard `linear` or `ease-in-out` transitions. Instant state changes without interpolation.
## 3. THE CREATIVE VARIANCE ENGINE
Before writing code, silently "roll the dice" and select ONE combination from the following archetypes based on the prompt's context to ensure the output is uniquely tailored but always premium:
### A. Vibe & Texture Archetypes (Pick 1)
1. **Ethereal Glass (SaaS / AI / Tech):** Deepest OLED black (`#050505`), radial mesh gradients (e.g., subtle glowing purple/emerald orbs) in the background. Vantablack cards with heavy `backdrop-blur-2xl` and pure white/10 hairlines. Wide geometric Grotesk typography.
2. **Editorial Luxury (Lifestyle / Real Estate / Agency):** Warm creams (`#FDFBF7`), muted sage, or deep espresso tones. High-contrast Variable Serif fonts for massive headings. Subtle CSS noise/film-grain overlay (`opacity-[0.03]`) for a physical paper feel.
3. **Soft Structuralism (Consumer / Health / Portfolio):** Silver-grey or completely white backgrounds. Massive bold Grotesk typography. Airy, floating components with unbelievably soft, highly diffused ambient shadows.
### B. Layout Archetypes (Pick 1)
1. **The Asymmetrical Bento:** A masonry-like CSS Grid of varying card sizes (e.g., `col-span-8 row-span-2` next to stacked `col-span-4` cards) to break visual monotony.
- **Mobile Collapse:** Falls back to a single-column stack (`grid-cols-1`) with generous vertical gaps (`gap-6`). All `col-span` overrides reset to `col-span-1`.
2. **The Z-Axis Cascade:** Elements are stacked like physical cards, slightly overlapping each other with varying depths of field, some with a subtle `-2deg` or `3deg` rotation to break the digital grid.
- **Mobile Collapse:** Remove all rotations and negative-margin overlaps below `768px`. Stack vertically with standard spacing. Overlapping elements cause touch-target conflicts on mobile.
3. **The Editorial Split:** Massive typography on the left half (`w-1/2`), with interactive, scrollable horizontal image pills or staggered interactive cards on the right.
- **Mobile Collapse:** Converts to a full-width vertical stack (`w-full`). Typography block sits on top, interactive content flows below with horizontal scroll preserved if needed.
**Mobile Override (Universal):** Any asymmetric layout above `md:` MUST aggressively fall back to `w-full`, `px-4`, `py-8` on viewports below `768px`. Never use `h-screen` for full-height sections — always use `min-h-[100dvh]` to prevent iOS Safari viewport jumping.
## 4. HAPTIC MICRO-AESTHETICS (COMPONENT MASTERY)
### A. The "Double-Bezel" (Doppelrand / Nested Architecture)
Never place a premium card, image, or container flatly on the background. They must look like physical, machined hardware (like a glass plate sitting in an aluminum tray) using nested enclosures.
- **Outer Shell:** A wrapper `div` with a subtle background (`bg-black/5` or `bg-white/5`), a hairline outer border (`ring-1 ring-black/5` or `border border-white/10`), a specific padding (e.g., `p-1.5` or `p-2`), and a large outer radius (`rounded-[2rem]`).
- **Inner Core:** The actual content container inside the shell. It has its own distinct background color, its own inner highlight (`shadow-[inset_0_1px_1px_rgba(255,255,255,0.15)]`), and a mathematically calculated smaller radius (e.g., `rounded-[calc(2rem-0.375rem)]`) for concentric curves.
### B. Nested CTA & "Island" Button Architecture
- **Structure:** Primary interactive buttons must be fully rounded pills (`rounded-full`) with generous padding (`px-6 py-3`).
- **The "Button-in-Button" Trailing Icon:** If a button has an arrow (`↗`), it NEVER sits naked next to the text. It must be nested inside its own distinct circular wrapper (e.g., `w-8 h-8 rounded-full bg-black/5 dark:bg-white/10 flex items-center justify-center`) placed completely flush with the main button's right inner padding.
### C. Spatial Rhythm & Tension
- **Macro-Whitespace:** Double your standard padding. Use `py-24` to `py-40` for sections. Allow the design to breathe heavily.
- **Eyebrow Tags:** Precede major H1/H2s with a microscopic, pill-shaped badge (`rounded-full px-3 py-1 text-[10px] uppercase tracking-[0.2em] font-medium`).
## 5. MOTION CHOREOGRAPHY (FLUID DYNAMICS)
Never use default transitions. All motion must simulate real-world mass and spring physics. Use custom cubic-beziers (e.g., `transition-all duration-700 ease-[cubic-bezier(0.32,0.72,0,1)]`).
### A. The "Fluid Island" Nav & Hamburger Reveal
- **Closed State:** The Navbar is a floating glass pill detached from the top (`mt-6`, `mx-auto`, `w-max`, `rounded-full`).
- **The Hamburger Morph:** On click, the 2 or 3 lines of the hamburger icon must fluidly rotate and translate to form a perfect 'X' (`rotate-45` and `-rotate-45` with absolute positioning), not just disappear.
- **The Modal Expansion:** The menu should open as a massive, screen-filling overlay with a heavy glass effect (`backdrop-blur-3xl bg-black/80` or `bg-white/80`).
- **Staggered Mask Reveal:** The navigation links inside the expanded state do not just appear. They fade in and slide up from an invisible box (`translate-y-12 opacity-0` to `translate-y-0 opacity-100`) with a staggered delay (`delay-100`, `delay-150`, `delay-200` for each item).
### B. Magnetic Button Hover Physics
- Use the `group` utility. On hover, do not just change the background color.
- Scale the entire button down slightly (`active:scale-[0.98]`) to simulate physical pressing.
- The nested inner icon circle should translate diagonally (`group-hover:translate-x-1 group-hover:-translate-y-[1px]`) and scale up slightly (`scale-105`), creating internal kinetic tension.
### C. Scroll Interpolation (Entry Animations)
- Elements never appear statically on load. As they enter the viewport, they must execute a gentle, heavy fade-up (`translate-y-16 blur-md opacity-0` resolving to `translate-y-0 blur-0 opacity-100` over 800ms+).
- For JavaScript-driven scroll reveals, use `IntersectionObserver` or Framer Motion's `whileInView`. Never use `window.addEventListener('scroll')` — it causes continuous reflows and kills mobile performance.
## 6. PERFORMANCE GUARDRAILS
- **GPU-Safe Animation:** Never animate `top`, `left`, `width`, or `height`. Animate exclusively via `transform` and `opacity`. Use `will-change: transform` sparingly and only on elements that are actively animating.
- **Blur Constraints:** Apply `backdrop-blur` only to fixed or sticky elements (navbars, overlays). Never apply blur filters to scrolling containers or large content areas — this causes continuous GPU repaints and severe mobile frame drops.
- **Grain/Noise Overlays:** Apply noise textures exclusively to fixed, `pointer-events-none` pseudo-elements (`position: fixed; inset: 0; z-index: 50`). Never attach them to scrolling containers.
- **Z-Index Discipline:** Do not use arbitrary `z-50` or `z-[9999]`. Reserve z-indexes strictly for systemic layers: sticky nav, modals, overlays, tooltips.
## 7. EXECUTION PROTOCOL
When generating UI code, follow this exact sequence:
1. **[SILENT THOUGHT]** Roll the Variance Engine (Section 3). Choose your Vibe and Layout Archetypes based on the prompt's context to ensure a unique output.
2. **[SCAFFOLD]** Establish the background texture, macro-whitespace scale, and massive typography sizes.
3. **[ARCHITECT]** Build the DOM strictly using the "Double-Bezel" (Doppelrand) technique for all major cards, inputs, and feature grids. Use exaggerated squircle radii (`rounded-[2rem]`).
4. **[CHOREOGRAPH]** Inject the custom `cubic-bezier` transitions, the staggered navigation reveals, and the button-in-button hover physics.
5. **[OUTPUT]** Deliver flawless, pixel-perfect React/Tailwind/HTML code. Do not include basic, generic fallbacks.
## 8. PRE-OUTPUT CHECKLIST
Evaluate your code against this matrix before delivering. This is the last filter.
- [ ] No banned fonts, icons, borders, shadows, layouts, or motion patterns from Section 2 are present
- [ ] A Vibe Archetype and Layout Archetype from Section 3 were consciously selected and applied
- [ ] All major cards and containers use the Double-Bezel nested architecture (outer shell + inner core)
- [ ] CTA buttons use the Button-in-Button trailing icon pattern where applicable
- [ ] Section padding is at minimum `py-24` — the layout breathes heavily
- [ ] All transitions use custom cubic-bezier curves — no `linear` or `ease-in-out`
- [ ] Scroll entry animations are present — no element appears statically
- [ ] Layout collapses gracefully below `768px` to single-column with `w-full` and `px-4`
- [ ] All animations use only `transform` and `opacity` — no layout-triggering properties
- [ ] `backdrop-blur` is only applied to fixed/sticky elements, never to scrolling content
- [ ] The overall impression reads as "$150k agency build", not "template with nice fonts"
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,987 @@
---
name: imagegen-frontend-web
description: Elite frontend image-direction skill for generating premium, conversion-aware website design references. CRITICAL OUTPUT RULE — generate ONE separate horizontal image FOR EVERY section. A landing page with 8 sections produces 8 images. Never compress multiple sections into one image. Enforces composition variety (not always left-text / right-image), background-image freedom, varied CTAs, varied hero scales (giant / mid / mini minimalist), narrative concept spine, second-read moments, and a single consistent palette across all images. Optimized for landing pages, marketing sites, and product comps that developers or coding models can accurately recreate.
---
# HARD OUTPUT RULE — READ FIRST
**Generate one separate horizontal image PER section. Always. No exceptions.**
- 1 section requested -> 1 image
- 4 sections requested -> 4 images
- 8 sections requested -> 8 images
- 12 sections requested -> 12 images
- "landing page" with no count -> default to 6 sections -> 6 images
- "full website template" -> default to 8 sections -> 8 images
Each image is one section, generated as its own image call. Never combine multiple sections into one frame. Never return a single tall image that contains the whole page.
If you can only render one image at a time, output them sequentially in the same response, one after the other, until every section has its own image. Announce each one ("Section 1 of 8: Hero", "Section 2 of 8: Trust bar", etc.).
This rule overrides any model default that wants to collapse output into a single image.
---
# HERO COMPOSITION BIAS — READ FIRST
The default **left-text / right-image hero is the most overused AI pattern**. It is allowed, but it should not be your first instinct.
Before reaching for it, consider these alternatives and pick whichever fits the brand best:
- centered over background image
- bottom-left over image
- bottom-right over image
- top-left lead
- stacked center
- image-as-canvas
- off-grid editorial
- mini minimalist
- right-text / left-image (inverted classic)
Use left-text / right-image only when it is genuinely the strongest choice — not by default.
---
# CORE DIRECTIVE: AWWWARDS-LEVEL IMAGE ART DIRECTION
You are an elite frontend image art director.
Your job is not to generate generic AI art.
Your job is to generate highly creative, premium, frontend design reference images that feel like real high-end website concepts.
Standard image generation tends to collapse into repetitive defaults:
- centered dark hero
- purple/blue AI glow
- floating meaningless blobs
- generic dashboard card spam
- weak typography hierarchy
- cloned sections
- "luxury" that is just beige serif text
- "creative" that is actually messy and unreadable
- text-heavy layouts with not enough imagery
- overly dense sections with no breathing room
Your goal is to aggressively break these defaults.
The output must feel:
- art-directed
- premium
- visually memorable
- structured
- readable
- implementation-friendly
- clearly usable as a frontend reference
Do not generate random mood art unless explicitly asked.
Default to website design comps.
---
## 1. ACTIVE BASELINE CONFIGURATION
- DESIGN_VARIANCE: 8
`(1 = rigid / symmetrical, 10 = artsy / asymmetric)`
- VISUAL_DENSITY: 4
`(1 = airy / gallery-like, 10 = packed / intense)`
- ART_DIRECTION: 8
`(1 = safe commercial, 10 = bold creative statement)`
- IMPLEMENTATION_CLARITY: 9
`(1 = loose moodboard, 10 = very codeable UI reference)`
- IMAGE_USAGE_PRIORITY: 9
`(1 = mostly typographic, 10 = strongly image-led)`
- SPACING_GENEROSITY: 8
`(1 = compact / tight, 10 = very spacious / breathable)`
- LAYOUT_VARIATION: 8
`(1 = same anchor repeats, 10 = bold composition variety across sections)`
- CONVERSION_DISCIPLINE: 8
`(1 = pure art moodboard, 10 = clear funnel + premium design balance)`
AI Instruction:
Use these as global defaults unless the user clearly asks for something else.
Do not ask the user to edit this file.
Adapt these values dynamically from the prompt.
Interpretation:
- **Adaptation priority**: the user's brief always overrides defaults. Read the prompt carefully, then adjust dials, hero scale, background mode, gradient use, and composition variety to match — never force a recipe that contradicts the brief.
- If the user says "clean", reduce density and increase clarity.
- If the user says "crazy creative", increase variance and art direction.
- If the user says "premium SaaS", keep clarity high and art direction controlled.
- If the user says "editorial", allow stronger type and more asymmetry.
- Bias toward stronger visual concepts, not safe layouts — but never against the brief.
- Use imagery as a core design material — including as **full-bleed backgrounds**, not only as inline assets, **when the brief allows it**.
- Vary composition: do not default to "text left, image right". Move text to bottom-left, center, top-right, etc. across sections.
- Keep sections breathable. Do not over-pack the page.
- Prefer slightly more whitespace between sections than default.
- Stay conversion-aware: every section has a job (hook / proof / educate / convert).
### Brief-to-direction mapping
Read the brief. Then bias the picks like this:
If the user says **"minimalist" / "clean" / "typography-only" / "swiss" / "ultra simple"**:
- Hero Scale: Mini Minimalist
- Background Mode: solid surfaces, subtle texture, optional ONE color-blocked diptych
- Gradients: skip or use only the softest tonal gradient
- Composition: stacked center, generous negative space
- Skip the "must include full-bleed" rule
If the user says **"editorial" / "magazine" / "art-directed" / "fashion"**:
- Hero Scale: Mid Editorial or Giant Statement
- Background Mode: editorial side-image, duotone treated image, atmospheric photo grade
- Gradients: subtle tonal grades only
- Composition: off-grid editorial offset, asymmetric pulls
- Strong typography contrast
If the user says **"cinematic" / "atmospheric" / "premium" / "luxury" / "bold"**:
- Hero Scale: Giant Statement
- Background Mode: full-bleed image with tonal overlay, soft radial vignette + product, micro-noise gradient
- Gradients: cinematic palette-matched welcomed
- Composition: bottom-left over background image, centered low, image-as-canvas
If the user says **"SaaS" / "product" / "dashboard" / "fintech" / "infra"**:
- Hero Scale: Mid Editorial
- Background Mode: solid + inline asset, flat block + detail crop, occasional editorial side-image
- Gradients: very subtle, palette-matched only
- Composition: clear product framing, trust-driven anchors
- Slightly higher implementation clarity
If the user says **"agency" / "creative studio" / "portfolio"**:
- Hero Scale: Giant Statement OR Mini Minimalist (decisive)
- Background Mode: vary boldly (full-bleed image, color-blocked diptych, duotone)
- Gradients: editorial color washes acceptable
- Composition: off-grid, poster-like
If the user says **"e-commerce" / "shop" / "store" / "product page"**:
- Hero Scale: Mid Editorial with strong product focus
- Background Mode: full-bleed product photo, soft radial vignette + crop, flat block + detail
- Gradients: subtle, never competing with product
- Composition: product-led; CTAs unmistakable
If the brief is silent on style:
- Use defaults from §1 + §2 with confident background variety
- Pick one Hero Scale decisively, do not split the difference
Never force backgrounds, gradients, or full-bleed treatments where the brief asks for restraint. Never strip them out where the brief asks for atmosphere.
---
## 2. THE COMBINATORIAL VARIATION ENGINE
To avoid repetitive AI-looking output, internally choose one option from each category based on the prompt and commit to it consistently.
Do not mash everything together into chaos.
Pick a strong combination and execute it clearly.
### Theme Paradigm
Choose 1:
1. Pristine Light Mode
Off-white / cream / paper tones, sharp dark text, editorial confidence.
2. Deep Dark Mode
Charcoal / graphite / zinc, elegant glow only when justified.
3. Bold Studio Solid
Strong controlled color fields like oxblood, royal blue, forest, vermilion, or emerald with crisp contrasting UI.
4. Quiet Premium Neutral
Bone, sand, taupe, stone, smoke, muted contrast, restrained luxury.
### Background Character
Choose 1:
1. Subtle technical grid / dotted field
2. Pure solid field with soft ambient gradient depth
3. Full-bleed cinematic imagery with proper contrast control
4. Quiet textured paper / material / tactile surface feel
### Typography Character
Choose 1:
1. Satoshi-like clean grotesk
2. Neue-Montreal-like refined grotesk
3. Cabinet / Clash-like expressive display
4. Monument-like compressed statement typography
5. Elegant editorial serif + sans pairing
6. Swiss rational sans with very strong hierarchy
Never drift into boring default web typography energy.
### Hero Architecture
Choose 1:
1. Cinematic Centered Minimalist
2. Asymmetric Split Hero
3. Floating Polaroid Scatter
4. Inline Typography Behemoth
5. Editorial Offset Composition
6. Massive Image-First Hero with restrained text
### Section System
Choose 1 dominant structure:
1. Strict modular bento rhythm
2. Alternating editorial blocks
3. Poster-like stacked storytelling
4. Gallery-led visual cadence
5. Swiss grid discipline
6. Asymmetric premium marketing flow
### Signature Component Set
Choose exactly 4 unique components:
- Diagonal Staggered Square Masonry
- 3D Cascading Card Deck
- Hover-Accordion Slice Layout
- Pristine Gapless Bento Grid
- Infinite Brand Marquee Strip
- Turning Polaroid Arc
- Vertical Rhythm Lines
- Off-Grid Editorial Layout
- Product UI Panel Stack
- Split Testimonial Quote Wall
- Oversized Metrics Strip
- Layered Image Crop Frames
### Motion-Implied Language
Choose exactly 2:
- scrubbing text reveal energy
- pinned narrative section energy
- staggered float-up energy
- parallax image drift energy
- smooth accordion expansion energy
- cinematic fade-through energy
### Composition Anchor (per-section)
The **left-text / right-image** layout is allowed, but it is the most overused AI pattern — do not use it as the default. Reach for it only when it is the genuinely best fit.
Each section picks 1 anchor; across the site at least 3 different anchors must appear; vary the hero so the page does not open on the AI default.
- Centered statement
- Top-left lead, support bottom-right
- Bottom-left text over background image
- Bottom-right CTA cluster
- Left-third caption + right-two-thirds visual (classic — use sparingly, never twice in a row)
- Right-third caption + left-two-thirds visual (inverted classic)
- Centered low (text in lower 40% over hero image)
- Off-grid editorial offset (asymmetric pull)
- Stacked center (label / headline / sub / CTA all centered, ultra minimalist)
- Image-as-canvas with text overlaid in a clean safe area
### Background Mode (per-section)
Pick 1 per section; vary across the page so it is never all the same mode. Be **confident** with backgrounds — they are a primary tool, not a risk.
- Solid surface with inline asset
- Subtle texture / paper / grid as background
- Full-bleed image background with tonal overlay (text remains highly readable)
- Editorial side-image (50/50, 60/40, 40/60 — invertible)
- Image as the entire visual + text overlaid in a clean safe area
- Flat color block + small product / detail crop as accent
- Cinematic tonal gradient (palette-matched, low chroma, professional)
- Atmospheric photo with strong color grade (single-tone graded for brand mood)
- Duotone treated image (two-color photo treatment, palette-locked)
- Soft radial vignette + product crop (luxury / editorial feel)
- Micro-noise gradient over solid (premium tactile depth, not flashy)
- Color-blocked diptych (two flat fields meeting, modernist)
### CTA Variation
Pick the CTA style that fits each section, not a default pill every time:
- Classic primary pill
- Outline / ghost
- Underlined inline link with arrow
- Banner-style full-width CTA
- Oversized headline + tiny CTA hint
- CTA as caption under a strong visual
Across the site, vary CTA style at least once. The page's primary action stays unmistakable.
### Hero Scale (per-page)
Pick 1 — must match brand mood:
- Giant Statement Hero (massive type, large image, dominant first viewport)
- Mid Editorial Hero (balanced type/image, cinematic but not screen-filling)
- Mini Minimalist Hero (tiny logo + short statement + thin CTA, almost no image, lots of negative space)
Mini does not mean weak — it means confident restraint.
### Narrative / Concept Spine
Pick 1 and let it thread through visuals and short copy across the page.
- Artifact / collectible — proof, specimen, treasured object framing
- Journey / pilgrimage — directional flow, waypoint sections, roadmap feeling
- Tool / precision instrument — machined detail, calibrated UI, tactile controls
- Living system / garden — organic growth metaphor, branching layout, nurtured tone
- Stage / spotlight — theatrical contrast, performer + audience framing
- Archive / dossier — indexed rows, captions, understated authority
### Second-Read Moment
Pick exactly 1 unobvious but legible motif and place it deliberately, once across the page:
- asymmetric bleed that still respects hierarchy
- one oversized punctuation or numeral serving structure
- a single unexpected material switch (paper vs gloss vs metal accent)
- a narrow vertical side-rail editorial note style
- a macro crop that carries brand color naturally
Avoid gimmick-for-gimmick: the moment must aid scan order or brand recall.
Important:
These are not coding instructions.
They are visual-direction cues the generated design should imply.
---
## 3. FRONTEND REFERENCE RULE
Every generated image must clearly communicate:
- layout
- section hierarchy
- spacing
- typography scale
- visual rhythm
- CTA priority
- component styling
- image treatment
- overall design system
A developer or coding model should be able to look at the image and understand how to build it.
Do not produce vague abstract artwork when the request is for frontend.
---
## 4. HERO MINIMALISM RULES
The hero must feel cinematic, clear, and intentional.
### Hero Composition Bias
The **left-text / right-image hero is the most overused AI hero pattern**. It is allowed, but it should not be your default starting point.
Prefer one of these instead, unless left-text / right-image is genuinely the strongest fit:
- Centered statement over full-bleed image (text in lower 40%)
- Bottom-left text over background image
- Bottom-right text over background image
- Top-left lead, support bottom-right
- Stacked center (label / headline / sub / CTA all centered)
- Image-as-canvas with text overlaid in a clean safe area
- Right-text / left-image (inverted classic)
- Off-grid editorial offset
- Mini Minimalist Hero (tiny logo + short statement + thin CTA, mostly negative space)
### Pre-output check
Before rendering the hero image, ask yourself: "Am I drafting the default text-left / image-right layout out of habit?" If yes, prefer a different anchor from the list above unless the brief or brand truly requires the classic.
### Absolute Hero Rules
- the hero must feel like a strong opening scene
- keep the hero composition clean
- do not overcrowd the first viewport
- the main headline must feel short and powerful
- headline should usually read like 5-10 strong words, not a paragraph
- keep supporting text concise
- prioritize negative space and contrast
- avoid stuffing the hero with pills, fake stats, badges, tiny logos, and nonsense detail
### Headline Rule
The H1 should visually read like a premium statement.
Do not let it feel long, weak, or overly wrapped.
### Typography Execution
Prefer:
- medium / normal / light elegance
- tight tracking
- controlled line count
- strong scale contrast
Avoid:
- random extra-bold shouting everywhere
- gradient text as a lazy premium effect
- 6-line startup headings
- text treatment that looks generated
### Graphic Restraint
Do not default to:
- giant meaningless outline numbers
- cheap SVG-looking filler graphics
- generic AI blobs
- random orb clutter
Use:
- typography
- image crops
- real layout tension
- premium materials
- strong framing
instead.
---
## 5. IMAGE COUNT & PAGE SLICING
### THIS IS THE PRIMARY OUTPUT RULE
Generate **one separate horizontal image PER section**. Always.
- never combine multiple sections in a single image
- never return a single tall slice that contains the whole page
- never return one "best" image and skip the rest
- never replace several sections with one collage
If the request is ambiguous about section count, **default high**:
- "hero" -> 1 image
- "landing page" / "site template" -> default to 6 sections -> 6 images
- "full website" -> default to 8 sections -> 8 images
- "marketing site" -> default to 8 sections -> 8 images
- "product page" -> default to 6 sections -> 6 images
- "portfolio" -> default to 6 sections -> 6 images
If the model can only render one image per call, generate them **sequentially in the same response**, one after the other, labeled "Section X of N: <name>" until the full set is delivered.
### Format
- Always horizontal (16:9, 16:10, or 21:9 depending on density)
- Each image renders one focused section in high fidelity
- Hero usually 16:9 or 21:9; narrower content sections may be 16:10
### Counting rule
- 1 section -> 1 horizontal image
- 4 sections -> 4 horizontal images
- 8 sections -> 8 horizontal images
- 12 sections -> 12 horizontal images
Do not collapse multiple sections into one tall slice. Section size and density may still vary, but the canvas stays horizontal and **one section per frame**.
### Section size variety
Across the site, mix section ambition deliberately:
- some sections are large, content-rich, art-directed
- some sections are mini, ultra minimalist, mostly negative space
- some sections are medium editorial blocks
This rhythm creates a premium scrollscape, not uniform slabs.
### Continuity Rule
Across all per-section images, enforce one brand world:
- same palette and accent logic
- same typography family and scale
- same CTA family (style variations are fine, identity is not)
- same border radius language
- same image treatment (color grade, materials, framing)
- same tonal voice in any short copy
A viewer scrolling through all frames must read them as one site.
---
## 6. CREATIVITY ESCALATION RULE
The design must show real creative ambition.
Do not settle for the first obvious layout solution.
Push the work beyond generic SaaS patterns.
Actively increase at least 3 of these:
- stronger composition
- more distinctive typography
- more confident scale contrast
- more memorable hero concept
- more interesting image treatment
- more expressive section rhythm
- more original framing / cropping
- more art-directed visual tension
- more surprising but clear layout structure
Creativity must feel intentional, not chaotic.
Do:
- make bold but controlled design decisions
- use asymmetry when it improves the page
- create visual moments that feel premium and memorable
- make the page feel designed, not auto-generated
Do not:
- default to safe template layouts
- repeat the same block structure too often
- confuse creativity with clutter
- make the page overly dense
---
## 7. IMAGE-FIRST ART DIRECTION
This skill must actively use images.
Images are not optional decoration.
Images are a core part of the frontend design language.
Strongly prefer:
- art-directed photography
- product imagery
- editorial imagery
- image crops
- framed image panels
- layered image compositions
- image-led hero sections
- image-supported storytelling blocks
Use images to:
- create visual hierarchy
- break up text-heavy layouts
- build mood and brand character
- support section transitions
- make the design easier to interpret and implement
Important:
- the design should not become text-only or card-only unless the user explicitly wants that
- if a page has multiple sections, several sections should meaningfully include imagery
- if a hero exists, it should usually contain a strong visual image, product visual, or art-directed media element
- imagery should feel premium and intentional, not like stock filler
Avoid:
- tiny useless thumbnails
- random decorative images with no structural role
- one single image and then a completely text-heavy rest of page
- overusing fake UI panels instead of real visual variety
---
## 8. ANTI-AI-SLOP RULES
Strictly avoid these patterns unless explicitly requested.
### Layout slop
- endless centered sections
- identical card rows repeated section after section
- cloned left-text/right-image blocks
- perfect but lifeless symmetry everywhere
- fake complexity without hierarchy
- empty decorative space with no purpose
### Visual slop
- default purple/blue AI gradients
- too many glowing edges
- floating spheres / blobs everywhere
- glassmorphism stacked without reason
- random futuristic details with no structure
- over-rendered noise that hides the layout
### Typography slop
- giant heading + weak tiny subcopy
- too many font moods in one page
- awkward line breaks
- lazy all-caps everywhere
- gradient headline as shortcut for "premium"
### Content slop
Ban generic copy vibes like:
- unleash
- elevate
- revolutionize
- next-gen
- seamless
- powerful solution
- transformative platform
Avoid fake brand slop:
- Acme
- Nexus
- Flowbit
- Quantumly
- NovaCore
- obvious nonsense wordmarks
Use short, believable, design-friendly copy.
### Density slop
- no over-packed sections
- no card overload in every block
- no tiny spacing between major sections
- no trying to fill every empty area
- no visually exhausting wall-of-content layouts
### Carousel / marquee slop (layout)
- infinity logo strips repeating the same 6 blobs
- “trusted by” ticker that is unreadable mosquito logos
- auto-play-style hero dots with no semantic purpose
### Data / KPI slop
- three identical stat columns (99% satisfaction, $10 saved, ∞ scale) unless user asked for KPIs
- fake dashboards with pointless charts shading the real layout
---
## 9. TYPOGRAPHY-FIRST DISCIPLINE
Typography is not filler.
Typography is a primary design material.
Always ensure:
- clear size contrast
- obvious reading order
- strong display moments
- supporting text that is readable and brief
- labels, captions, and section headings that reinforce structure
For editorial directions:
- let typography shape composition
For tech/product directions:
- let typography communicate trust and precision
---
## 10. SECTION RHYTHM RULE
A high-end site does not feel like repeated boxes.
Vary section rhythm across the page by changing:
- density
- image-to-text ratio
- alignment
- scale
- whitespace
- card grouping
- background intensity
- visual tempo
Do not let every section feel generated from the same template.
Important:
- rhythm variation should not break overall cleanliness
- keep the page visually balanced from top to bottom
- section heights may vary, but the spacing between sections should feel controlled and fairly even
- avoid abrupt jumps between very small and very large sections without enough breathing room
- the full page should feel curated, smooth, and consistent
---
## 11. COMPONENT EXECUTION GUIDELINES
### Diagonal Staggered Square Masonry
Use square image or content blocks with strong staggered vertical rhythm.
Should feel curated and graphic, not messy.
### 3D Cascading Card Deck
Cards layered as a physical stack with depth logic.
Should feel premium and tactile, not gimmicky.
### Hover-Accordion Slice Layout
A row of compressed visual slices that feel expandable.
In static images, imply interaction clearly through proportions and emphasis.
### Pristine Gapless Bento Grid
Mathematically clean grid.
No accidental gaps.
Mix large visual blocks with smaller dense information panels.
### Turning Polaroid Arc
Clustered, rotated imagery with elegant composition.
Should feel styled and intentional, not scrapbook-random.
### Off-Grid Editorial Layout
Use asymmetry and tension with control.
Must remain readable and clearly structured.
### Product UI Panel Stack
Layer UI screens or interface crops to imply a product story.
Avoid generic fake dashboards.
### Vertical Rhythm Lines
Use fine lines and spacing systems to reinforce order and elegance.
Never let them become decorative clutter.
---
## 12. DENSITY & SPACING DISCIPLINE
Do not make everything too dense.
The page should breathe.
Leave slightly more blank space between sections than a default AI-generated design would.
Rules:
- use more even vertical spacing between major sections
- keep section-to-section spacing consistent unless there is a strong design reason not to
- avoid one section feeling very cramped while the next feels too empty
- prefer a clean, balanced cadence across the page
- allow negative space to create rhythm and emphasis
- separate denser sections with calmer sections
- avoid stacking too many cards, labels, and content blocks too tightly
- smaller sections should still receive enough surrounding space so the page feels polished and intentional
A premium page should feel:
- open
- composed
- balanced
- confident
- breathable
Not:
- cramped
- noisy
- uneven
- overfilled
- visually exhausted
Section rhythm should alternate with control:
- some sections can be more content-rich
- some sections can be smaller and calmer
- but the overall spacing cadence should still feel even, clean, and deliberate
Whitespace is a design tool.
Use it deliberately.
Do not let spacing become random.
---
## 13. COLOR & MATERIAL RULES
### Palette Discipline
Use one controlled palette across the entire site:
- 1 primary (brand anchor)
- 1 secondary (supporting tone)
- 1 accent (used sparingly for CTA / highlight)
- a neutral scale (background, surface, text, hairline)
Section-level mood shifts must reuse the same palette — no full theme swap per section.
### Background-image harmony
When using full-bleed image backgrounds:
- the image must tonally match the palette (not fight it)
- use overlays (dark, light, or color tint) to keep text fully readable
- the brand accent stays consistent regardless of background image
### Gradient Discipline
Gradients are **allowed and encouraged** when professional and subtle. They are not the same as AI slop gradients.
Allowed (use confidently):
- low-chroma palette-matched tonal gradients (e.g. ink to graphite, cream to sand, ivory to warm grey)
- single-hue atmospheric grades behind hero photography
- soft vignettes and radial depth that direct the eye
- noise-textured gradients adding tactile depth without color noise
- editorial color washes that match brand mood
Banned (AI gradient slop):
- rainbow / mesh blob gradients
- purple-to-blue "AI" defaults
- pink-to-orange "creator" defaults
- neon edges and glow halos with no purpose
- gradient text as a shortcut for "premium"
- gradients that compete with imagery instead of supporting it
### Background Confidence Rule
Do not retreat to plain white surfaces by default. When the brief, brand mood, or section job calls for atmosphere, use:
- a full-bleed image,
- a duotone or graded photo,
- a tonal gradient,
- a tactile material,
or a confident flat color field — picked deliberately, not as decoration.
### Strong guidance
- avoid rainbow randomness
- avoid over-neon unless requested
- keep contrast intentional
- match accent colors to the chosen theme paradigm
- gradients must always read as professional and intentional, never as visual noise
### Materiality
Where appropriate, add:
- paper feel
- glass feel
- brushed metal feel
- soft blur depth
- tactile matte surfaces
- editorial photo treatment
But always keep the frontend structure readable.
---
## 14. IMAGE / MEDIA DIRECTION
If imagery is present, it must support the layout.
Allowed:
- art-directed product visuals
- refined editorial photography
- UI crops
- abstract forms with structural purpose
- framed objects
- premium texture use
- campaign-style visuals
Avoid:
- irrelevant scenery
- stock-photo cliches
- decorative junk
- visuals that overpower the page hierarchy
---
## 15. DEFAULT SITE PACKS
### 4-section pack
1. Hero
2. Features
3. Social proof / testimonial
4. CTA
### 8-section pack
1. Hero
2. Trust bar
3. Features
4. Product showcase
5. Benefits / use cases
6. Testimonials
7. Pricing
8. CTA
### 12-section pack
1. Hero
2. Trust bar
3. Feature grid
4. Product preview
5. Problem / solution
6. Benefits
7. Workflow
8. Metrics / proof / integration
9. Testimonials
10. Pricing
11. FAQ
12. CTA + footer
---
## 16. MULTI-IMAGE CONSISTENCY RULE
Because every section is its own image, consistency is critical. Across all per-section frames enforce:
- same brand world
- same type scale logic
- same spacing discipline
- same CTA family (style variations are fine, identity is not)
- same icon or illustration mood
- same image treatment (grade, framing, material vocabulary)
- same tonal language in any copy
Variation IS allowed in:
- composition anchor (per section)
- background mode (per section)
- section size and density
- which "second-read" moment appears
A viewer flipping through every per-section frame must still recognize one brand. Anything that breaks brand recall is over-variation.
---
## 17. CLARITY CHECK
Before finalizing, verify internally:
1. Is the hierarchy obvious?
2. Is the hero clean enough?
3. Is the design visually distinctive?
4. Is it free of obvious AI tells?
5. Is it premium rather than template-like?
6. Can someone code from this?
7. If multiple images exist, do they clearly belong together?
8. Is imagery used strongly enough (with variation, not one repeated crop)?
9. Does the page breathe, or is it too dense?
10. Is there enough spacing between sections?
11. Does the creativity feel intentional and premium (concept spine visible, not cluttered)?
12. Is the spacing between sections even and controlled?
13. Do smaller sections still have enough surrounding space to feel clean?
14. Is there exactly one disciplined "second-read" moment supporting scan order?
15. Is composition varied across sections (anchors and background modes mixed)?
16. Is the hero scale (giant / mid / mini) chosen and executed cleanly?
17. Is there a clear conversion path (hook -> proof -> action) even in artistic sites?
18. Is the palette consistent across all per-section images?
19. Is each image horizontal and one-section-only?
20. Is the **total number of images equal to the number of sections** (never fewer)?
21. Is the hero using a varied composition (not defaulting to left-text / right-image out of habit)?
If not, refine internally before output. If the count is wrong, regenerate the missing sections. If the hero feels like a reflexive left-text / right-image default, prefer a different composition anchor.
---
## 18. EXTRA CREATIVITY & IMPLEMENTATION EDGE
Apply unless the user opts out:
### Cross-section contrast
Across the slice, deliberately vary foreground/background intensity at least twice (lighter → richer → calmer) so the scroll feels paced, not monotonous slabs.
### CTA specificity
Prefer one unmistakable primary action per major viewport tier; secondary actions must look secondary (scale, outline, ghost), not clones of primary.
### Image variety inside one comp
Mix at least **two distinct image crops** where multiple sections exist — e.g. macro product + contextual environment, or portrait editorial + widescreen artifact — avoiding one repeated stock silhouette.
### Data-viz restraint
Charts, sparklines, and graphs appear only when the site type logically needs them (analytics, pricing, infra, observability brands). Else keep proof human (quotes, receipts, timelines, screenshots of real workflows).
### Cultural / tonal alignment
When the brief names an industry or region, steer palette and typographic temperament to match — dont ship default “neutral SF startup” unless the brief is intentionally generic SaaS.
### Mobile-implied fidelity (even for desktop mocks)
Maintain tap-friendly hit sizes and readable caption sizes visually; stacking order should imply a sane single-column narrative.
### Conversion focus
Each section has a job. Even when the design is artistic, the page must read as a real product or brand site:
- the hero communicates value in seconds and offers one obvious next action
- proof sections (logos, quotes, metrics) feel earned, not stuffed
- pricing or CTA sections feel decisive, not buried
- the final section closes: a single strong CTA + supporting trust cue
Avoid pure mood reels with no funnel logic.
### Composition variety check
Across all per-section images, internally log the chosen composition anchor and background mode. Reject the set if:
- the same composition anchor repeats more than 2 sections in a row
- the same background mode repeats more than 3 sections in a row
- every section is inline-asset (no full-bleed background ever appears) **AND** the brief does not call for minimalism / typography-only / swiss / ultra simple
For non-minimalist briefs: push for at least one full-bleed (or duotone / atmospheric) background and at least one mini minimalist section in any multi-section site.
For minimalist briefs: this rule is suspended. Restraint is the design.
---
## 19. RESPONSE BEHAVIOR
When the user asks for a frontend design:
1. infer site type and primary conversion goal
2. infer number of sections (if unclear, use the defaults from §5: landing page = 6, full website = 8)
3. **commit out loud** to the section count and announce it ("Generating N horizontal images, one per section")
4. plan ONE horizontal image PER SECTION — always separate generations, never collapse
5. choose Hero Scale for the whole site (giant / mid / mini)
5. choose a strong visual combination (theme, type, hero arch, section system, motion, narrative spine, second-read moment)
7. for each section: pick a Composition Anchor, Background Mode, and CTA Variation — vary across sections
8. choose 4 signature components used appropriately across sections
9. enforce hero minimalism + section size variety (some giant, some mini)
10. enforce strong image usage including full-bleed backgrounds where it fits
11. lock one consistent palette across all images
12. apply §18 EXTRA CREATIVITY & IMPLEMENTATION EDGE
13. keep spacing generous, even, and clean
14. remove AI slop (including marquee / fake KPI clichés unless requested)
15. run §17 CLARITY CHECK
16. **generate every per-section horizontal image, labeled "Section X of N: <name>"**, until the full set is delivered. Do not stop early. Do not summarize. Do not return only one image.
Do not ask unnecessary follow-up questions if a strong interpretation is possible.
---
## 20. EXAMPLE INTERPRETATIONS
### Example 1
User: "make a hero section for an AI startup"
Interpretation:
- 1 horizontal image
- Hero Scale: Mid Editorial or Giant Statement
- Composition Anchor: bottom-left text over full-bleed product/atmosphere image
- Background Mode: full-bleed image with dark tonal overlay
- CTA Variation: outlined inline + small label hint
- Palette: Deep Dark or Bold Studio Solid, one consistent accent
- no cliche dashboard spam, no purple AI glow
### Example 2
User: "design 8 sections for a fintech website"
Interpretation:
- 8 separate horizontal images (one per section)
- Hero Scale: Mid Editorial (trust-driven)
- vary Composition Anchor across sections (centered low, right-third caption, bottom-left over chart visual, stacked center for closing CTA)
- Background Mode mix: solid surface, full-bleed image background once, editorial side-image at use cases
- one consistent palette (e.g. ink + paper + single brand accent)
- conversion path: hook -> proof bar -> features -> use case -> testimonial -> pricing -> FAQ -> final CTA
### Example 3
User: "creative agency landing page, 12 sections"
Interpretation:
- 12 horizontal images (one per section)
- Hero Scale: Giant Statement OR Mini Minimalist (decisive choice, not in-between)
- editorial / poster-like direction; off-grid composition appears 2-3 times
- multiple Background Modes (full-bleed image at hero + showcase, editorial side-image at case studies, solid + accent for process)
- palette consistent throughout, with one bold accent recurring
- closing CTA section: mini minimalist, strong type, single primary action
---
## 21. FINAL GOAL
Generate frontend reference images that feel:
- artistic
- premium
- clear
- structured
- image-led
- breathable
- memorable
- anti-generic
- implementation-friendly
The result should look like a top-tier website concept with strong imagery, confident creativity, and generous spacing - not a dense, repetitive AI layout.
@@ -0,0 +1,92 @@
---
name: industrial-brutalist-ui
description: Raw mechanical interfaces fusing Swiss typographic print with military terminal aesthetics. Rigid grids, extreme type scale contrast, utilitarian color, analog degradation effects. For data-heavy dashboards, portfolios, or editorial sites that need to feel like declassified blueprints.
---
# SKILL: Industrial Brutalism & Tactical Telemetry UI
## 1. Skill Meta
**Name:** Industrial Brutalism & Tactical Telemetry Interface Engineering
**Description:** Advanced proficiency in architecting web interfaces that synthesize mid-century Swiss Typographic design, industrial manufacturing manuals, and retro-futuristic aerospace/military terminal interfaces. This discipline requires absolute mastery over rigid modular grids, extreme typographic scale contrast, purely utilitarian color palettes, and the programmatic simulation of analog degradation (halftones, CRT scanlines, bitmap dithering). The objective is to construct digital environments that project raw functionality, mechanical precision, and high data density, deliberately discarding conventional consumer UI patterns.
## 2. Visual Archetypes
The design system operates by merging two distinct but highly compatible visual paradigms. **Pick ONE per project and commit to it. Do not alternate or mix both modes within the same interface.**
### 2.1 Swiss Industrial Print
Derived from 1960s corporate identity systems and heavy machinery blueprints.
* **Characteristics:** High-contrast light modes (newsprint/off-white substrates). Reliance on monolithic, heavy sans-serif typography. Unforgiving structural grids outlined by visible dividing lines. Aggressive, asymmetric use of negative space punctuated by oversized, viewport-bleeding numerals or letterforms. Heavy use of primary red as an alert/accent color.
### 2.2 Tactical Telemetry & CRT Terminal
Derived from classified military databases, legacy mainframes, and aerospace Heads-Up Displays (HUDs).
* **Characteristics:** Dark mode exclusivity. High-density tabular data presentation. Absolute dominance of monospaced typography. Integration of technical framing devices (ASCII brackets, crosshairs). Application of simulated hardware limitations (phosphor glow, scanlines, low bit-depth rendering).
## 3. Typographic Architecture
Typography is the primary structural and decorative infrastructure. Imagery is secondary. The system demands extreme variance in scale, weight, and spacing.
### 3.1 Macro-Typography (Structural Headers)
* **Classification:** Neo-Grotesque / Heavy Sans-Serif.
* **Optimal Web Fonts:** Neue Haas Grotesk (Black), Inter (Extra Bold/Black), Archivo Black, Roboto Flex (Heavy), Monument Extended.
* **Implementation Parameters:**
* **Scale:** Deployed at massive scales using fluid typography (e.g., `clamp(4rem, 10vw, 15rem)`).
* **Tracking (Letter-spacing):** Extremely tight, often negative (`-0.03em` to `-0.06em`), forcing glyphs to form solid architectural blocks.
* **Leading (Line-height):** Highly compressed (`0.85` to `0.95`).
* **Casing:** Exclusively uppercase for structural impact.
### 3.2 Micro-Typography (Data & Telemetry)
* **Classification:** Monospace / Technical Sans.
* **Optimal Web Fonts:** JetBrains Mono, IBM Plex Mono, Space Mono, VT323, Courier Prime.
* **Implementation Parameters:**
* **Scale:** Fixed and small (`10px` to `14px` / `0.7rem` to `0.875rem`).
* **Tracking:** Generous (`0.05em` to `0.1em`) to simulate mechanical typewriter spacing or terminal matrices.
* **Leading:** Standard to tight (`1.2` to `1.4`).
* **Casing:** Exclusively uppercase. Used for all metadata, navigation, unit IDs, and coordinates.
### 3.3 Textural Contrast (Artistic Disruption)
* **Classification:** High-Contrast Serif.
* **Optimal Web Fonts:** Playfair Display, EB Garamond, Times New Roman.
* **Implementation Parameters:** Used exceedingly sparingly. Must be subjected to heavy post-processing (halftone filters, 1-bit dithering) to degrade vector perfection and create textural juxtaposition against the clean sans-serifs.
## 4. Color System
The color architecture is uncompromising. Gradients, soft drop shadows, and modern translucency are strictly prohibited. Colors simulate physical media or primitive emissive displays.
**CRITICAL: Choose ONE substrate palette per project and use it consistently. Never mix light and dark substrates within the same interface.**
### If Swiss Industrial Print (Light):
* **Background:** `#F4F4F0` or `#EAE8E3` (Matte, unbleached documentation paper).
* **Foreground:** `#050505` to `#111111` (Carbon Ink).
* **Accent:** `#E61919` or `#FF2A2A` (Aviation/Hazard Red). This is the ONLY accent color. Used for strike-throughs, thick structural dividing lines, or vital data highlights.
### If Tactical Telemetry (Dark):
* **Background:** `#0A0A0A` or `#121212` (Deactivated CRT. Avoid pure `#000000`).
* **Foreground:** `#EAEAEA` (White phosphor). This is the primary text color.
* **Accent:** `#E61919` or `#FF2A2A` (Aviation/Hazard Red). Same red, same rules.
* **Terminal Green (`#4AF626`):** Optional. Use ONLY for a single specific UI element (e.g., one status indicator or one data readout) — never as a general text color. If it doesn't serve a clear purpose, omit it entirely.
## 5. Layout and Spatial Engineering
The layout must appear mathematically engineered. It rejects conventional web padding in favor of visible compartmentalization.
* **The Blueprint Grid:** Strict adherence to CSS Grid architectures. Elements do not float; they are anchored precisely to grid tracks and intersections.
* **Visible Compartmentalization:** Extensive utilization of solid borders (`1px` or `2px solid`) to delineate distinct zones of information. Horizontal rules (`<hr>`) frequently span the entire container width to segregate operational units.
* **Bimodal Density:** Layouts oscillate between extreme data density (tightly packed monospace metadata clustered together) and vast expanses of calculated negative space framing macro-typography.
* **Geometry:** Absolute rejection of `border-radius`. All corners must be exactly 90 degrees to enforce mechanical rigidity.
## 6. UI Components and Symbology
Standard web UI conventions are replaced with utilitarian, industrial graphic elements.
* **Syntax Decoration:** Utilization of ASCII characters to frame data points.
* *Framing:* `[ DELIVERY SYSTEMS ]`, `< RE-IND >`
* *Directional:* `>>>`, `///`, `\\\\`
* **Industrial Markers:** Prominent integration of registration (`®`), copyright (`©`), and trademark (`™`) symbols functioning as structural geometric elements rather than legal text.
* **Technical Assets:** Integration of crosshairs (`+`) at grid intersections, repeating vertical lines (barcodes), thick horizontal warning stripes, and randomized string data (e.g., `REV 2.6`, `UNIT / D-01`) to simulate active mechanical processes.
## 7. Textural and Post-Processing Effects
To prevent the design from appearing purely digital, simulated analog degradation is engineered into the frontend via CSS and SVG filters.
* **Halftone and 1-Bit Dithering:** Transforming continuous-tone images or large serif typography into dot-matrix patterns. Achieved via pre-processing or CSS `mix-blend-mode: multiply` overlays combined with SVG radial dot patterns.
* **CRT Scanlines:** For terminal interfaces, applying a `repeating-linear-gradient` to the background to simulate horizontal electron beam sweeps (e.g., `repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(0,0,0,0.1) 2px, rgba(0,0,0,0.1) 4px)`).
* **Mechanical Noise:** A global, low-opacity SVG static/noise filter applied to the DOM root to introduce a unified physical grain across both dark and light modes.
## 8. Web Engineering Directives
1. **Grid Determinism:** Utilize `display: grid; gap: 1px;` with contrasting parent/child background colors to generate mathematically perfect, razor-thin dividing lines without complex border declarations.
2. **Semantic Rigidity:** Construct the DOM using precise semantic tags (`<data>`, `<samp>`, `<kbd>`, `<output>`, `<dl>`) to accurately reflect the technical nature of the telemetry.
3. **Typography Clamping:** Implement CSS `clamp()` functions exclusively for macro-typography to ensure massive text scales aggressively while maintaining structural integrity across viewports.
+85
View File
@@ -0,0 +1,85 @@
---
name: minimalist-ui
description: Clean editorial-style interfaces. Warm monochrome palette, typographic contrast, flat bento grids, muted pastels. No gradients, no heavy shadows.
---
# Protocol: Premium Utilitarian Minimalism UI Architect
## 1. Protocol Overview
Name: Premium Utilitarian Minimalism & Editorial UI
Description: An advanced frontend engineering directive for generating highly refined, ultra-minimalist, "document-style" web interfaces analogous to top-tier workspace platforms. This protocol strictly enforces a high-contrast warm monochrome palette, bespoke typographic hierarchies, meticulous structural macro-whitespace, bento-grid layouts, and an ultra-flat component architecture with deliberate muted pastel accents. It actively rejects standard generic SaaS design trends.
## 2. Absolute Negative Constraints (Banned Elements)
The AI must strictly avoid the following generic web development defaults:
- DO NOT use the "Inter", "Roboto", or "Open Sans" typefaces.
- DO NOT use generic, thin-line icon libraries like "Lucide", "Feather", or standard "Heroicons".
- DO NOT use Tailwind's default heavy drop shadows (e.g., `shadow-md`, `shadow-lg`, `shadow-xl`). Shadows must be practically non-existent or heavily customized to be ultra-diffuse and low opacity (< 0.05).
- DO NOT use primary colored backgrounds for large elements or sections (e.g., no bright blue, green, or red hero sections).
- DO NOT use gradients, neon colors, or 3D glassmorphism (beyond subtle navbar blurs).
- DO NOT use `rounded-full` (pill shapes) for large containers, cards, or primary buttons.
- DO NOT use emojis anywhere in code, markup, text content, headings, or alt text. Replace with proper icons or clean SVG primitives.
- DO NOT use generic placeholder names like "John Doe", "Acme Corp", or "Lorem Ipsum". Use realistic, contextual content.
- DO NOT use AI copywriting clichés: "Elevate", "Seamless", "Unleash", "Next-Gen", "Game-changer", "Delve". Write plain, specific language.
## 3. Typographic Architecture
The interface must rely on extreme typographic contrast and premium font selection to establish an editorial feel.
- Primary Sans-Serif (Body, UI, Buttons): Use clean, geometric, or system-native fonts with character. Target: `font-family: 'SF Pro Display', 'Geist Sans', 'Helvetica Neue', 'Switzer', sans-serif`.
- Editorial Serif (Hero Headings & Quotes): Target: `font-family: 'Lyon Text', 'Newsreader', 'Playfair Display', 'Instrument Serif', serif`. Apply tight tracking (`letter-spacing: -0.02em` to `-0.04em`) and tight line-height (`1.1`).
- Monospace (Code, Keystrokes, Meta-data): Target: `font-family: 'Geist Mono', 'SF Mono', 'JetBrains Mono', monospace`.
- Text Colors: Body text must never be absolute black (`#000000`). Use off-black/charcoal (`#111111` or `#2F3437`) with a generous `line-height` of `1.6` for legibility. Secondary text should be muted gray (`#787774`).
## 4. Color Palette (Warm Monochrome + Spot Pastels)
Color is a scarce resource, utilized only for semantic meaning or subtle accents.
- Canvas / Background: Pure White `#FFFFFF` or Warm Bone/Off-White `#F7F6F3` / `#FBFBFA`.
- Primary Surface (Cards): `#FFFFFF` or `#F9F9F8`.
- Structural Borders / Dividers: Ultra-light gray `#EAEAEA` or `rgba(0,0,0,0.06)`.
- Accent Colors: Exclusively use highly desaturated, washed-out pastels for tags, inline code backgrounds, or subtle icon backgrounds.
- Pale Red: `#FDEBEC` (Text: `#9F2F2D`)
- Pale Blue: `#E1F3FE` (Text: `#1F6C9F`)
- Pale Green: `#EDF3EC` (Text: `#346538`)
- Pale Yellow: `#FBF3DB` (Text: `#956400`)
## 5. Component Specifications
- Bento Box Feature Grids:
- Utilize asymmetrical CSS Grid layouts.
- Cards must have exactly `border: 1px solid #EAEAEA`.
- Border-radius must be crisp: `8px` or `12px` maximum.
- Internal padding must be generous (e.g., `24px` to `40px`).
- Primary Call-To-Action (Buttons):
- Solid background `#111111`, text `#FFFFFF`.
- Slight border-radius (`4px` to `6px`). No box-shadow.
- Hover state should be a subtle color shift to `#333333` or a micro-scale `transform: scale(0.98)`.
- Tags & Status Badges:
- Pill-shaped (`border-radius: 9999px`), very small typography (`text-xs`), uppercase with wide tracking (`letter-spacing: 0.05em`).
- Background must use the defined Muted Pastels.
- Accordions (FAQ):
- Strip all container boxes. Separate items only with a `border-bottom: 1px solid #EAEAEA`.
- Use a clean, sharp `+` and `-` icon for the toggle state.
- Keystroke Micro-UIs:
- Render shortcuts as physical keys using `<kbd>` tags: `border: 1px solid #EAEAEA`, `border-radius: 4px`, `background: #F7F6F3`, using the Monospace font.
- Faux-OS Window Chrome:
- When mocking up software, wrap it in a minimalist container with a white top bar containing three small, light gray circles (replicating macOS window controls).
## 6. Iconography & Imagery Directives
- System Icons: Use "Phosphor Icons (Bold or Fill weights)" or "Radix UI Icons" for a technical, slightly thicker-stroke aesthetic. Standardize stroke width across all icons.
- Illustrations: Monochromatic, rough continuous-line ink sketches on a white background, featuring a single offset geometric shape filled with a muted pastel color.
- Photography: Use high-quality, desaturated images with a warm tone. Apply subtle overlays (`opacity: 0.04` warm grain) to blend photos into the monochrome palette. Never use oversaturated stock photos. Use reliable placeholders like `https://picsum.photos/seed/{context}/1200/800` when real assets are unavailable.
- Hero & Section Backgrounds: Sections should not feel empty and flat. Use subtle full-width background imagery at very low opacity, soft radial light spots (`radial-gradient` with warm tones at `opacity: 0.03`), or minimal geometric line patterns to add depth without breaking the clean aesthetic.
## 7. Subtle Motion & Micro-Animations
Motion should feel invisible — present but never distracting. The goal is quiet sophistication, not spectacle.
- Scroll Entry: Elements fade in gently as they enter the viewport. Use `translateY(12px)` + `opacity: 0` resolving over `600ms` with `cubic-bezier(0.16, 1, 0.3, 1)`. Use `IntersectionObserver`, never `window.addEventListener('scroll')`.
- Hover States: Cards lift with an ultra-subtle shadow shift (`box-shadow` transitioning from `0 0 0` to `0 2px 8px rgba(0,0,0,0.04)` over `200ms`). Buttons respond with `scale(0.98)` on `:active`.
- Staggered Reveals: Lists and grid items enter with a cascade delay (`animation-delay: calc(var(--index) * 80ms)`). Never mount everything at once.
- Background Ambient Motion: Optional. A single, very slow-moving radial gradient blob (`animation-duration: 20s+`, `opacity: 0.02-0.04`) drifting behind hero sections. Must be applied to a `position: fixed; pointer-events: none` layer. Never on scrolling containers.
- Performance: Animate exclusively via `transform` and `opacity`. No layout-triggering properties (`top`, `left`, `width`, `height`). Use `will-change: transform` sparingly and only on actively animating elements.
## 8. Execution Protocol
When tasked with writing frontend code (HTML, React, Tailwind, Vue) or designing a layout:
1. Establish the macro-whitespace first. Use massive vertical padding between sections (e.g., `py-24` or `py-32` in Tailwind).
2. Constrain the main typography content width to `max-w-4xl` or `max-w-5xl`.
3. Apply the custom typographic hierarchy and monochromatic color variables immediately.
4. Ensure every card, divider, and border adheres strictly to the `1px solid #EAEAEA` rule.
5. Add scroll-entry animations to all major content blocks.
6. Ensure sections have visual depth through imagery, ambient gradients, or subtle textures — no empty flat backgrounds.
7. Provide code that reflects this high-end, uncluttered, editorial aesthetic natively without requiring manual adjustments.
@@ -0,0 +1,178 @@
---
name: redesign-existing-projects
description: Upgrades existing websites and apps to premium quality. Audits current design, identifies generic AI patterns, and applies high-end design standards without breaking functionality. Works with any CSS framework or vanilla CSS.
---
# Redesign Skill
## How This Works
When applied to an existing project, follow this sequence:
1. **Scan** — Read the codebase. Identify the framework, styling method (Tailwind, vanilla CSS, styled-components, etc.), and current design patterns.
2. **Diagnose** — Run through the audit below. List every generic pattern, weak point, and missing state you find.
3. **Fix** — Apply targeted upgrades working with the existing stack. Do not rewrite from scratch. Improve what's there.
## Design Audit
### Typography
Check for these problems and fix them:
- **Browser default fonts or Inter everywhere.** Replace with a font that has character. Good options: `Geist`, `Outfit`, `Cabinet Grotesk`, `Satoshi`. For editorial/creative projects, pair a serif header with a sans-serif body.
- **Headlines lack presence.** Increase size for display text, tighten letter-spacing, reduce line-height. Headlines should feel heavy and intentional.
- **Body text too wide.** Limit paragraph width to roughly 65 characters. Increase line-height for readability.
- **Only Regular (400) and Bold (700) weights used.** Introduce Medium (500) and SemiBold (600) for more subtle hierarchy.
- **Numbers in proportional font.** Use a monospace font or enable tabular figures (`font-variant-numeric: tabular-nums`) for data-heavy interfaces.
- **Missing letter-spacing adjustments.** Use negative tracking for large headers, positive tracking for small caps or labels.
- **All-caps subheaders everywhere.** Try lowercase italics, sentence case, or small-caps instead.
- **Orphaned words.** Single words sitting alone on the last line. Fix with `text-wrap: balance` or `text-wrap: pretty`.
### Color and Surfaces
- **Pure `#000000` background.** Replace with off-black, dark charcoal, or tinted dark (`#0a0a0a`, `#121212`, or a dark navy).
- **Oversaturated accent colors.** Keep saturation below 80%. Desaturate accents so they blend with neutrals instead of screaming.
- **More than one accent color.** Pick one. Remove the rest. Consistency beats variety.
- **Mixing warm and cool grays.** Stick to one gray family. Tint all grays with a consistent hue (warm or cool, not both).
- **Purple/blue "AI gradient" aesthetic.** This is the most common AI design fingerprint. Replace with neutral bases and a single, considered accent.
- **Generic `box-shadow`.** Tint shadows to match the background hue. Use colored shadows (e.g., dark blue shadow on a blue background) instead of pure black at low opacity.
- **Flat design with zero texture.** Add subtle noise, grain, or micro-patterns to backgrounds. Pure flat vectors feel sterile.
- **Perfectly even gradients.** Break the uniformity with radial gradients, noise overlays, or mesh gradients instead of standard linear 45-degree fades.
- **Inconsistent lighting direction.** Audit all shadows to ensure they suggest a single, consistent light source.
- **Random dark sections in a light mode page (or vice versa).** A single dark-background section breaking an otherwise light page looks like a copy-paste accident. Either commit to a full dark mode or keep a consistent background tone throughout. If contrast is needed, use a slightly darker shade of the same palette — not a sudden jump to `#111` in the middle of a cream page.
- **Empty, flat sections with no visual depth.** Sections that are just text on a plain background feel unfinished. Add high-quality background imagery (blurred, overlaid, or masked), subtle patterns, or ambient gradients. Use reliable placeholder sources like `https://picsum.photos/seed/{name}/1920/1080` when real assets are not available. Experiment with background images behind hero sections, feature blocks, or CTAs — even a subtle full-width photo at low opacity adds presence.
### Layout
- **Everything centered and symmetrical.** Break symmetry with offset margins, mixed aspect ratios, or left-aligned headers over centered content.
- **Three equal card columns as feature row.** This is the most generic AI layout. Replace with a 2-column zig-zag, asymmetric grid, horizontal scroll, or masonry layout.
- **Using `height: 100vh` for full-screen sections.** Replace with `min-height: 100dvh` to prevent layout jumping on mobile browsers (iOS Safari viewport bug).
- **Complex flexbox percentage math.** Replace with CSS Grid for reliable multi-column structures.
- **No max-width container.** Add a container constraint (around 1200-1440px) with auto margins so content doesn't stretch edge-to-edge on wide screens.
- **Cards of equal height forced by flexbox.** Allow variable heights or use masonry when content varies in length.
- **Uniform border-radius on everything.** Vary the radius: tighter on inner elements, softer on containers.
- **No overlap or depth.** Elements sit flat next to each other. Use negative margins to create layering and visual depth.
- **Symmetrical vertical padding.** Top and bottom padding are always identical. Adjust optically — bottom padding often needs to be slightly larger.
- **Dashboard always has a left sidebar.** Try top navigation, a floating command menu, or a collapsible panel instead.
- **Missing whitespace.** Double the spacing. Let the design breathe. Dense layouts work for data dashboards, not for marketing pages.
- **Buttons not bottom-aligned in card groups.** When cards have different content lengths, CTAs end up at random heights. Pin buttons to the bottom of each card so they form a clean horizontal line regardless of content above.
- **Feature lists starting at different vertical positions.** In pricing tables or comparison cards, the list of features should start at the same Y position across all columns. Use consistent spacing above the list or fixed-height title/price blocks.
- **Inconsistent vertical rhythm in side-by-side elements.** When placing cards, columns, or panels next to each other, align shared elements (titles, descriptions, prices, buttons) across all items. Misaligned baselines make the layout look broken.
- **Mathematical alignment that looks optically wrong.** Centering by the math doesn't always look centered to the eye. Icons next to text, play buttons in circles, or text in buttons often need 1-2px optical adjustments to feel right.
### Interactivity and States
- **No hover states on buttons.** Add background shift, slight scale, or translate on hover.
- **No active/pressed feedback.** Add a subtle `scale(0.98)` or `translateY(1px)` on press to simulate a physical click.
- **Instant transitions with zero duration.** Add smooth transitions (200-300ms) to all interactive elements.
- **Missing focus ring.** Ensure visible focus indicators for keyboard navigation. This is an accessibility requirement, not optional.
- **No loading states.** Replace generic circular spinners with skeleton loaders that match the layout shape.
- **No empty states.** An empty dashboard showing nothing is a missed opportunity. Design a composed "getting started" view.
- **No error states.** Add clear, inline error messages for forms. Do not use `window.alert()`.
- **Dead links.** Buttons that link to `#`. Either link to real destinations or visually disable them.
- **No indication of current page in navigation.** Style the active nav link differently so users know where they are.
- **Scroll jumping.** Anchor clicks jump instantly. Add `scroll-behavior: smooth`.
- **Animations using `top`, `left`, `width`, `height`.** Switch to `transform` and `opacity` for GPU-accelerated, smooth animation.
### Content
- **Generic names like "John Doe" or "Jane Smith".** Use diverse, realistic-sounding names.
- **Fake round numbers like `99.99%`, `50%`, `$100.00`.** Use organic, messy data: `47.2%`, `$99.00`, `+1 (312) 847-1928`.
- **Placeholder company names like "Acme Corp", "Nexus", "SmartFlow".** Invent contextual, believable brand names.
- **AI copywriting cliches.** Never use "Elevate", "Seamless", "Unleash", "Next-Gen", "Game-changer", "Delve", "Tapestry", or "In the world of...". Write plain, specific language.
- **Exclamation marks in success messages.** Remove them. Be confident, not loud.
- **"Oops!" error messages.** Be direct: "Connection failed. Please try again."
- **Passive voice.** Use active voice: "We couldn't save your changes" instead of "Mistakes were made."
- **All blog post dates identical.** Randomize dates to appear real.
- **Same avatar image for multiple users.** Use unique assets for every distinct person.
- **Lorem Ipsum.** Never use placeholder latin text. Write real draft copy.
- **Title Case On Every Header.** Use sentence case instead.
### Component Patterns
- **Generic card look (border + shadow + white background).** Remove the border, or use only background color, or use only spacing. Cards should exist only when elevation communicates hierarchy.
- **Always one filled button + one ghost button.** Add text links or tertiary styles to reduce visual noise.
- **Pill-shaped "New" and "Beta" badges.** Try square badges, flags, or plain text labels.
- **Accordion FAQ sections.** Use a side-by-side list, searchable help, or inline progressive disclosure.
- **3-card carousel testimonials with dots.** Replace with a masonry wall, embedded social posts, or a single rotating quote.
- **Pricing table with 3 towers.** Highlight the recommended tier with color and emphasis, not just extra height.
- **Modals for everything.** Use inline editing, slide-over panels, or expandable sections instead of popups for simple actions.
- **Avatar circles exclusively.** Try squircles or rounded squares for a less generic look.
- **Light/dark toggle always a sun/moon switch.** Use a dropdown, system preference detection, or integrate it into settings.
- **Footer link farm with 4 columns.** Simplify. Focus on main navigational paths and legally required links.
### Iconography
- **Lucide or Feather icons exclusively.** These are the "default" AI icon choice. Use Phosphor, Heroicons, or a custom set for differentiation.
- **Rocketship for "Launch", shield for "Security".** Replace cliche metaphors with less obvious icons (bolt, fingerprint, spark, vault).
- **Inconsistent stroke widths across icons.** Audit all icons and standardize to one stroke weight.
- **Missing favicon.** Always include a branded favicon.
- **Stock "diverse team" photos.** Use real team photos, candid shots, or a consistent illustration style instead of uncanny stock imagery.
### Code Quality
- **Div soup.** Use semantic HTML: `<nav>`, `<main>`, `<article>`, `<aside>`, `<section>`.
- **Inline styles mixed with CSS classes.** Move all styling to the project's styling system.
- **Hardcoded pixel widths.** Use relative units (`%`, `rem`, `em`, `max-width`) for flexible layouts.
- **Missing alt text on images.** Describe image content for screen readers. Never leave `alt=""` or `alt="image"` on meaningful images.
- **Arbitrary z-index values like `9999`.** Establish a clean z-index scale in the theme/variables.
- **Commented-out dead code.** Remove all debug artifacts before shipping.
- **Import hallucinations.** Check that every import actually exists in `package.json` or the project dependencies.
- **Missing meta tags.** Add proper `<title>`, `description`, `og:image`, and social sharing meta tags.
### Strategic Omissions (What AI Typically Forgets)
- **No legal links.** Add privacy policy and terms of service links in the footer.
- **No "back" navigation.** Dead ends in user flows. Every page needs a way back.
- **No custom 404 page.** Design a helpful, branded "page not found" experience.
- **No form validation.** Add client-side validation for emails, required fields, and format checks.
- **No "skip to content" link.** Essential for keyboard users. Add a hidden skip-link.
- **No cookie consent.** If required by jurisdiction, add a compliant consent banner.
## Upgrade Techniques
When upgrading a project, pull from these high-impact techniques to replace generic patterns:
### Typography Upgrades
- **Variable font animation.** Interpolate weight or width on scroll or hover for text that feels alive.
- **Outlined-to-fill transitions.** Text starts as a stroke outline and fills with color on scroll entry or interaction.
- **Text mask reveals.** Large typography acting as a window to video or animated imagery behind it.
### Layout Upgrades
- **Broken grid / asymmetry.** Elements that deliberately ignore column structure — overlapping, bleeding off-screen, or offset with calculated randomness.
- **Whitespace maximization.** Aggressive use of negative space to force focus on a single element.
- **Parallax card stacks.** Sections that stick and physically stack over each other during scroll.
- **Split-screen scroll.** Two halves of the screen sliding in opposite directions.
### Motion Upgrades
- **Smooth scroll with inertia.** Decouple scrolling from browser defaults for a heavier, cinematic feel.
- **Staggered entry.** Elements cascade in with slight delays, combining Y-axis translation with opacity fade. Never mount everything at once.
- **Spring physics.** Replace linear easing with spring-based motion for a natural, weighty feel on all interactive elements.
- **Scroll-driven reveals.** Content entering through expanding masks, wipes, or draw-on SVG paths tied to scroll progress.
### Surface Upgrades
- **True glassmorphism.** Go beyond `backdrop-filter: blur`. Add a 1px inner border and a subtle inner shadow to simulate edge refraction.
- **Spotlight borders.** Card borders that illuminate dynamically under the cursor.
- **Grain and noise overlays.** A fixed, pointer-events-none overlay with subtle noise to break digital flatness.
- **Colored, tinted shadows.** Shadows that carry the hue of the background rather than using generic black.
## Fix Priority
Apply changes in this order for maximum visual impact with minimum risk:
1. **Font swap** — biggest instant improvement, lowest risk
2. **Color palette cleanup** — remove clashing or oversaturated colors
3. **Hover and active states** — makes the interface feel alive
4. **Layout and spacing** — proper grid, max-width, consistent padding
5. **Replace generic components** — swap cliche patterns for modern alternatives
6. **Add loading, empty, and error states** — makes it feel finished
7. **Polish typography scale and spacing** — the premium final touch
## Rules
- Work with the existing tech stack. Do not migrate frameworks or styling libraries.
- Do not break existing functionality. Test after every change.
- Before importing any new library, check the project's dependency file first.
- If the project uses Tailwind, check the version (v3 vs v4) before modifying config.
- If the project has no framework, use vanilla CSS.
- Keep changes reviewable and focused. Small, targeted improvements over big rewrites.
@@ -0,0 +1,121 @@
# Design System: Taste Standard
**Skill:** stitch-design-taste
---
## Configuration — Set Your Style
Adjust these dials before using this design system. They control how creative, dense, and animated the output should be. Pick the level that fits your project.
| Dial | Level | Description |
|------|-------|-------------|
| **Creativity** | `8` | `1` = Ultra-minimal, Swiss, silent, monochrome. `5` = Balanced, clean but with personality. `10` = Expressive, editorial, bold typography experiments, inline images in headlines, strong asymmetry. Default: `8` |
| **Density** | `4` | `1` = Gallery-airy, massive whitespace. `5` = Balanced sections. `10` = Cockpit-dense, data-heavy. Default: `4` |
| **Variance** | `8` | `1` = Predictable, symmetric grids. `5` = Subtle offsets. `10` = Artsy chaotic, no two sections alike. Default: `8` |
| **Motion Intent** | `6` | `1` = Static, no animation noted. `5` = Subtle hover/entrance cues. `10` = Cinematic orchestration noted in every component. Default: `6` |
> **How to use:** Change the numbers above to match your project's vibe. At **Creativity 13**, the system produces clean, quiet, Notion-like interfaces. At **Creativity 710**, expect inline image typography, dramatic scale contrast, and strong editorial layouts. The rest of the rules below adapt to your chosen levels.
---
## 1. Visual Theme & Atmosphere
A restrained, gallery-airy interface with confident asymmetric layouts and fluid spring-physics motion. The atmosphere is clinical yet warm — like a well-lit architecture studio where every element earns its place through function. Density is balanced (Level 4), variance runs high (Level 8) to prevent symmetrical boredom, and motion is fluid but never theatrical (Level 6). The overall impression: expensive, intentional, alive.
## 2. Color Palette & Roles
- **Canvas White** (#F9FAFB) — Primary background surface. Warm-neutral, never clinical blue-white
- **Pure Surface** (#FFFFFF) — Card and container fill. Used with whisper shadow for elevation
- **Charcoal Ink** (#18181B) — Primary text. Zinc-950 depth — never pure black
- **Steel Secondary** (#71717A) — Body text, descriptions, metadata. Zinc-500 warmth
- **Muted Slate** (#94A3B8) — Tertiary text, timestamps, disabled states
- **Whisper Border** (rgba(226,232,240,0.5)) — Card borders, structural 1px lines. Semi-transparent for depth
- **Diffused Shadow** (rgba(0,0,0,0.05)) — Card elevation. Wide-spreading, 40px blur, -15px offset. Never harsh
### Accent Selection (Pick ONE per project)
- **Emerald Signal** (#10B981) — For growth, success, positive data dashboards
- **Electric Blue** (#3B82F6) — For productivity, SaaS, developer tools
- **Deep Rose** (#E11D48) — For creative, editorial, fashion-adjacent projects
- **Amber Warmth** (#F59E0B) — For community, social, warm-toned products
### Banned Colors
- Purple/Violet neon gradients — the "AI Purple" aesthetic
- Pure Black (#000000) — always Off-Black or Zinc-950
- Oversaturated accents above 80% saturation
- Mixed warm/cool gray systems within one project
## 3. Typography Rules
- **Display:** `Geist`, `Satoshi`, `Cabinet Grotesk`, or `Outfit` — Track-tight (`-0.025em`), controlled fluid scale, weight-driven hierarchy (700900). Not screaming. Leading compressed (`1.1`). Alternatives forced — `Inter` is BANNED for premium contexts
- **Body:** Same family at weight 400 — Relaxed leading (`1.65`), 65ch max-width, Steel Secondary color (#71717A)
- **Mono:** `Geist Mono` or `JetBrains Mono` — For code blocks, metadata, timestamps. When density exceeds Level 7, all numbers switch to monospace
- **Scale:** Display at `clamp(2.25rem, 5vw, 3.75rem)`. Body at `1rem/1.125rem`. Mono metadata at `0.8125rem`
### Banned Fonts
- `Inter` — banned everywhere in premium/creative contexts
- Generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`, `Palatino`) — BANNED. If serif is needed for editorial/creative, use only distinctive modern serifs like `Fraunces`, `Gambarino`, `Editorial New`, or `Instrument Serif`. Never use default browser serif stacks. Serif is always BANNED in dashboards or software UIs regardless
## 4. Component Stylings
* **Buttons:** Flat surface, no outer glow. Primary: accent fill with white text. Secondary: ghost/outline. Active state: `-1px translateY` or `scale(0.98)` for tactile push. Hover: subtle background shift, never glow
* **Cards/Containers:** Generously rounded corners (`2.5rem`). Pure white fill. Whisper border (`1px`, semi-transparent). Diffused shadow (`0 20px 40px -15px rgba(0,0,0,0.05)`). Internal padding `2rem2.5rem`. Used ONLY when elevation communicates hierarchy — high-density layouts replace cards with `border-top` dividers or negative space
* **Inputs/Forms:** Label positioned above input. Helper text optional. Error text below in Deep Rose. Focus ring in accent color, `2px` offset. No floating labels. Standard `0.5rem` gap between label-input-error stack
* **Navigation:** Sleek, sticky. Icons scale on hover (Dock Magnification optional). No hamburger on desktop. Clean horizontal with generous spacing
* **Loaders:** Skeletal shimmer matching exact layout dimensions and rounded corners. Shifting light reflection across placeholder shapes. Never circular spinners
* **Empty States:** Composed illustration or icon composition with guidance text. Never just "No data found"
* **Error States:** Inline, contextual. Red accent underline or border. Clear recovery action
## 5. Hero Section
The Hero is the first impression — it must be striking, creative, and never generic.
- **Inline Image Typography:** Embed small, contextual photos or visuals directly between words or letters in the headline. Example: "We build [photo of hands typing] digital [photo of screen] products" — images sit inline at type-height, rounded, acting as visual punctuation between words. This is the signature creative technique
- **No Overlapping Elements:** Text must never overlap images or other text. Every element has its own clear spatial zone. No z-index stacking of content layers, no absolute-positioned headlines over images. Clean separation always
- **No Filler Text:** "Scroll to explore", "Swipe down", scroll arrow icons, bouncing chevrons, and any instructional UI chrome are BANNED. The user knows how to scroll. Let the content pull them in naturally
- **Asymmetric Structure:** Centered Hero layouts are BANNED at this variance level. Use Split Screen (50/50), Left-Aligned text / Right visual, or Asymmetric Whitespace with large empty zones
- **CTA Restraint:** Maximum one primary CTA button. No secondary "Learn more" links. No redundant micro-copy below the headline
## 6. Layout Principles
- **Grid-First:** CSS Grid for all structural layouts. Never flexbox percentage math (`calc(33% - 1rem)` is BANNED)
- **No Overlapping:** Elements must never overlap each other. No absolute-positioned layers stacking content on content. Every element occupies its own grid cell or flow position. Clean, separated spatial zones
- **Feature Sections:** The "3 equal cards in a row" pattern is BANNED. Use 2-column Zig-Zag, asymmetric Bento grids (2fr 1fr 1fr), or horizontal scroll galleries
- **Containment:** All content within `max-width: 1400px`, centered. Generous horizontal padding (`1rem` mobile, `2rem` tablet, `4rem` desktop)
- **Full-Height:** Use `min-height: 100dvh` — never `height: 100vh` (iOS Safari address bar jump)
- **Bento Architecture:** For feature grids, use Row 1: 3 columns | Row 2: 2 columns (70/30 split). Each tile contains a perpetual micro-animation
## 7. Responsive Rules
Every screen must work flawlessly across all viewports. **Responsive is not optional — it is a hard requirement. Every single element must be tested at 375px, 768px, and 1440px.**
- **Mobile-First Collapse (< 768px):** All multi-column layouts collapse to a strict single column. `width: 100%`, `padding: 1rem`, `gap: 1.5rem`. No exceptions
- **No Horizontal Scroll:** Horizontal overflow on mobile is a critical failure. All elements must fit within viewport width. If any element causes horizontal scroll, the design is broken
- **Typography Scaling:** Headlines scale down gracefully via `clamp()`. Body text stays `1rem` minimum. Never shrink body below `14px`. Headlines must remain readable on 375px screens
- **Touch Targets:** All interactive elements minimum `44px` tap target. Generous spacing between clickable items. Buttons must be full-width on mobile
- **Image Behavior:** Hero and inline images scale proportionally. Inline typography images (photos between words) stack below the headline on mobile instead of inline
- **Navigation:** Desktop horizontal nav collapses to a clean mobile menu (slide-in or full-screen overlay). No tiny hamburger icons without labels
- **Cards & Grids:** Bento grids and asymmetric layouts revert to stacked single-column cards with full-width. Maintain internal padding (`1rem`)
- **Spacing Consistency:** Vertical section gaps reduce proportionally on mobile (`clamp(3rem, 8vw, 6rem)`). Never cramped, never excessively airy
- **Testing Viewports:** Designs must be verified at: `375px` (iPhone SE), `390px` (iPhone 14), `768px` (iPad), `1024px` (small laptop), `1440px` (desktop)
## 8. Motion & Interaction (Code-Phase Intent)
> **Note:** Stitch generates static screens — it does not animate. This section documents the **intended motion behavior** so that the coding agent (Antigravity, Cursor, etc.) knows exactly how to implement animations when building the exported design into a live product.
- **Physics Engine:** Spring-based exclusively. `stiffness: 100, damping: 20`. No linear easing anywhere. Premium, weighty feel on all interactive elements
- **Perpetual Micro-Loops:** Every active dashboard component has an infinite-loop state — Pulse on status dots, Typewriter on search bars, Float on feature icons, Shimmer on loading states
- **Staggered Orchestration:** Lists and grids mount with cascaded delays (`animation-delay: calc(var(--index) * 100ms)`). Waterfall reveals, never instant mount
- **Layout Transitions:** Smooth re-ordering via shared element IDs. Items swap positions with physics, simulating real-time intelligence
- **Hardware Rules:** Animate ONLY `transform` and `opacity`. Never `top`, `left`, `width`, `height`. Grain/noise filters on fixed, pointer-events-none pseudo-elements only
- **Performance:** CPU-heavy perpetual animations isolated in microscopic leaf components. Never trigger parent re-renders. Target 60fps minimum
## 9. Anti-Patterns (Banned)
- No emojis — anywhere in UI, code, or alt text
- No `Inter` font — use `Geist`, `Outfit`, `Cabinet Grotesk`, `Satoshi`
- No generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`) — if serif is needed, use distinctive modern serifs only (`Fraunces`, `Instrument Serif`)
- No pure black (`#000000`) — Off-Black or Zinc-950 only
- No neon outer glows or default box-shadow glows
- No oversaturated accent colors above 80%
- No excessive gradient text on large headers
- No custom mouse cursors
- No overlapping elements — text never overlaps images or other content. Clean spatial separation always
- No 3-column equal card layouts for features
- No centered Hero sections (at this variance level)
- No filler UI text: "Scroll to explore", "Swipe down", "Discover more below", scroll arrows, bouncing chevrons — all BANNED
- No generic names: "John Doe", "Sarah Chan", "Acme", "Nexus", "SmartFlow"
- No fake round numbers: `99.99%`, `50%`, `1234567` — use organic data: `47.2%`, `+1 (312) 847-1928`
- No AI copywriting clichés: "Elevate", "Seamless", "Unleash", "Next-Gen", "Revolutionize"
- No broken Unsplash links — use `picsum.photos/seed/{id}/800/600` or SVG UI Avatars
- No generic `shadcn/ui` defaults — customize radii, colors, shadows to match this system
- No `z-index` spam — use only for Navbar, Modal, Overlay layer contexts
- No `h-screen` — always `min-h-[100dvh]`
- No circular loading spinners — skeletal shimmer only
+184
View File
@@ -0,0 +1,184 @@
---
name: stitch-design-taste
description: Semantic Design System Skill for Google Stitch. Generates agent-friendly DESIGN.md files that enforce premium, anti-generic UI standards — strict typography, calibrated color, asymmetric layouts, perpetual micro-motion, and hardware-accelerated performance.
---
# Stitch Design Taste — Semantic Design System Skill
## Overview
This skill generates `DESIGN.md` files optimized for Google Stitch screen generation. It translates the battle-tested anti-slop frontend engineering directives into Stitch's native semantic design language — descriptive, natural-language rules paired with precise values that Stitch's AI agent can interpret to produce premium, non-generic interfaces.
The generated `DESIGN.md` serves as the **single source of truth** for prompting Stitch to generate new screens that align with a curated, high-agency design language. Stitch interprets design through **"Visual Descriptions"** supported by specific color values, typography specs, and component behaviors.
## Prerequisites
- Access to Google Stitch via [labs.google/stitch](https://labs.google/stitch)
- Optionally: Stitch MCP Server for programmatic integration with Cursor, Antigravity, or Gemini CLI
## The Goal
Generate a `DESIGN.md` file that encodes:
1. **Visual atmosphere** — the mood, density, and design philosophy
2. **Color calibration** — neutrals, accents, and banned patterns with hex codes
3. **Typographic architecture** — font stacks, scale hierarchy, and anti-patterns
4. **Component behaviors** — buttons, cards, inputs with interaction states
5. **Layout principles** — grid systems, spacing philosophy, responsive strategy
6. **Motion philosophy** — animation engine specs, spring physics, perpetual micro-interactions
7. **Anti-patterns** — explicit list of banned AI design clichés
## Analysis & Synthesis Instructions
### 1. Define the Atmosphere
Evaluate the target project's intent. Use evocative adjectives from the taste spectrum:
- **Density:** "Art Gallery Airy" (13) → "Daily App Balanced" (47) → "Cockpit Dense" (810)
- **Variance:** "Predictable Symmetric" (13) → "Offset Asymmetric" (47) → "Artsy Chaotic" (810)
- **Motion:** "Static Restrained" (13) → "Fluid CSS" (47) → "Cinematic Choreography" (810)
Default baseline: Variance 8, Motion 6, Density 4. Adapt dynamically based on user's vibe description.
### 2. Map the Color Palette
For each color provide: **Descriptive Name** + **Hex Code** + **Functional Role**.
**Mandatory constraints:**
- Maximum 1 accent color. Saturation below 80%
- The "AI Purple/Blue Neon" aesthetic is strictly BANNED — no purple button glows, no neon gradients
- Use absolute neutral bases (Zinc/Slate) with high-contrast singular accents
- Stick to one palette for the entire output — no warm/cool gray fluctuation
- Never use pure black (`#000000`) — use Off-Black, Zinc-950, or Charcoal
### 3. Establish Typography Rules
- **Display/Headlines:** Track-tight, controlled scale. Not screaming. Hierarchy through weight and color, not just massive size
- **Body:** Relaxed leading, max 65 characters per line
- **Font Selection:** `Inter` is BANNED for premium/creative contexts. Force unique character: `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi`
- **Serif Ban:** Generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`, `Palatino`) are BANNED. If serif is needed for editorial/creative contexts, use only distinctive modern serifs: `Fraunces`, `Gambarino`, `Editorial New`, or `Instrument Serif`. Serif is always BANNED in dashboards or software UIs
- **Dashboard Constraint:** Use Sans-Serif pairings exclusively (`Geist` + `Geist Mono` or `Satoshi` + `JetBrains Mono`)
- **High-Density Override:** When density exceeds 7, all numbers must use Monospace
### 4. Define the Hero Section
The Hero is the first impression and must be creative, striking, and never generic:
- **Inline Image Typography:** Embed small, contextual photos or visuals directly between words or letters in the headline. Images sit inline at type-height, rounded, acting as visual punctuation. This is the signature creative technique
- **No Overlapping:** Text must never overlap images or other text. Every element occupies its own clean spatial zone
- **No Filler Text:** "Scroll to explore", "Swipe down", scroll arrow icons, bouncing chevrons are BANNED. The content should pull users in naturally
- **Asymmetric Structure:** Centered Hero layouts BANNED when variance exceeds 4
- **CTA Restraint:** Maximum one primary CTA. No secondary "Learn more" links
### 5. Describe Component Stylings
For each component type, describe shape, color, shadow depth, and interaction behavior:
- **Buttons:** Tactile push feedback on active state. No neon outer glows. No custom mouse cursors
- **Cards:** Use ONLY when elevation communicates hierarchy. Tint shadows to background hue. For high-density layouts, replace cards with border-top dividers or negative space
- **Inputs/Forms:** Label above input, helper text optional, error text below. Standard gap spacing
- **Loading States:** Skeletal loaders matching layout dimensions — no generic circular spinners
- **Empty States:** Composed compositions indicating how to populate data
- **Error States:** Clear, inline error reporting
### 6. Define Layout Principles
- No overlapping elements — every element occupies its own clear spatial zone. No absolute-positioned content stacking
- Centered Hero sections are BANNED when variance exceeds 4 — force Split Screen, Left-Aligned, or Asymmetric Whitespace
- The generic "3 equal cards horizontally" feature row is BANNED — use 2-column Zig-Zag, asymmetric grid, or horizontal scroll
- CSS Grid over Flexbox math — never use `calc()` percentage hacks
- Contain layouts using max-width constraints (e.g., 1400px centered)
- Full-height sections must use `min-h-[100dvh]` — never `h-screen` (iOS Safari catastrophic jump)
### 7. Define Responsive Rules
Every design must work across all viewports:
- **Mobile-First Collapse (< 768px):** All multi-column layouts collapse to single column. No exceptions
- **No Horizontal Scroll:** Horizontal overflow on mobile is a critical failure
- **Typography Scaling:** Headlines scale via `clamp()`. Body text minimum `1rem`/`14px`
- **Touch Targets:** All interactive elements minimum `44px` tap target
- **Image Behavior:** Inline typography images (photos between words) stack below headline on mobile
- **Navigation:** Desktop horizontal nav collapses to clean mobile menu
- **Spacing:** Vertical section gaps reduce proportionally (`clamp(3rem, 8vw, 6rem)`)
### 8. Encode Motion Philosophy
- **Spring Physics default:** `stiffness: 100, damping: 20` — premium, weighty feel. No linear easing
- **Perpetual Micro-Interactions:** Every active component should have an infinite loop state (Pulse, Typewriter, Float, Shimmer)
- **Staggered Orchestration:** Never mount lists instantly — use cascade delays for waterfall reveals
- **Performance:** Animate exclusively via `transform` and `opacity`. Never animate `top`, `left`, `width`, `height`. Grain/noise filters on fixed pseudo-elements only
### 9. List Anti-Patterns (AI Tells)
Encode these as explicit "NEVER DO" rules in the DESIGN.md:
- No emojis anywhere
- No `Inter` font
- No generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`) — distinctive modern serifs only if needed
- No pure black (`#000000`)
- No neon/outer glow shadows
- No oversaturated accents
- No excessive gradient text on large headers
- No custom mouse cursors
- No overlapping elements — clean spatial separation always
- No 3-column equal card layouts
- No generic names ("John Doe", "Acme", "Nexus")
- No fake round numbers (`99.99%`, `50%`)
- No AI copywriting clichés ("Elevate", "Seamless", "Unleash", "Next-Gen")
- No filler UI text: "Scroll to explore", "Swipe down", scroll arrows, bouncing chevrons
- No broken Unsplash links — use `picsum.photos` or SVG avatars
- No centered Hero sections (for high-variance projects)
## Output Format (DESIGN.md Structure)
```markdown
# Design System: [Project Title]
## 1. Visual Theme & Atmosphere
(Evocative description of the mood, density, variance, and motion intensity.
Example: "A restrained, gallery-airy interface with confident asymmetric layouts
and fluid spring-physics motion. The atmosphere is clinical yet warm — like a
well-lit architecture studio.")
## 2. Color Palette & Roles
- **Canvas White** (#F9FAFB) — Primary background surface
- **Pure Surface** (#FFFFFF) — Card and container fill
- **Charcoal Ink** (#18181B) — Primary text, Zinc-950 depth
- **Muted Steel** (#71717A) — Secondary text, descriptions, metadata
- **Whisper Border** (rgba(226,232,240,0.5)) — Card borders, 1px structural lines
- **[Accent Name]** (#XXXXXX) — Single accent for CTAs, active states, focus rings
(Max 1 accent. Saturation < 80%. No purple/neon.)
## 3. Typography Rules
- **Display:** [Font Name] — Track-tight, controlled scale, weight-driven hierarchy
- **Body:** [Font Name] — Relaxed leading, 65ch max-width, neutral secondary color
- **Mono:** [Font Name] — For code, metadata, timestamps, high-density numbers
- **Banned:** Inter, generic system fonts for premium contexts. Serif fonts banned in dashboards.
## 4. Component Stylings
* **Buttons:** Flat, no outer glow. Tactile -1px translate on active. Accent fill for primary, ghost/outline for secondary.
* **Cards:** Generously rounded corners (2.5rem). Diffused whisper shadow. Used only when elevation serves hierarchy. High-density: replace with border-top dividers.
* **Inputs:** Label above, error below. Focus ring in accent color. No floating labels.
* **Loaders:** Skeletal shimmer matching exact layout dimensions. No circular spinners.
* **Empty States:** Composed, illustrated compositions — not just "No data" text.
## 5. Layout Principles
(Grid-first responsive architecture. Asymmetric splits for Hero sections.
Strict single-column collapse below 768px. Max-width containment.
No flexbox percentage math. Generous internal padding.)
## 6. Motion & Interaction
(Spring physics for all interactive elements. Staggered cascade reveals.
Perpetual micro-loops on active dashboard components. Hardware-accelerated
transforms only. Isolated Client Components for CPU-heavy animations.)
## 7. Anti-Patterns (Banned)
(Explicit list of forbidden patterns: no emojis, no Inter, no pure black,
no neon glows, no 3-column equal grids, no AI copywriting clichés,
no generic placeholder names, no broken image links.)
```
## Best Practices
- **Be Descriptive:** "Deep Charcoal Ink (#18181B)" — not just "dark text"
- **Be Functional:** Explain what each element is used for
- **Be Consistent:** Same terminology throughout the document
- **Be Precise:** Include exact hex codes, rem values, pixel values in parentheses
- **Be Opinionated:** This is not a neutral template — it enforces a specific, premium aesthetic
## Tips for Success
1. Start with the atmosphere — understand the vibe before detailing tokens
2. Look for patterns — identify consistent spacing, sizing, and styling
3. Think semantically — name colors by purpose, not just appearance
4. Consider hierarchy — document how visual weight communicates importance
5. Encode the bans — anti-patterns are as important as the rules themselves
## Common Pitfalls to Avoid
- Using technical jargon without translation ("rounded-xl" instead of "generously rounded corners")
- Omitting hex codes or using only descriptive names
- Forgetting functional roles of design elements
- Being too vague in atmosphere descriptions
- Ignoring the anti-pattern list — these are what make the output premium
- Defaulting to generic "safe" designs instead of enforcing the curated aesthetic
+117
View File
@@ -0,0 +1,117 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# sqlalchemy.url = driver://user:pass@localhost/dbname
# 实际数据库 URL 从环境变量读取
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+71
View File
@@ -0,0 +1,71 @@
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.models.user import User
from app.schemas.user import Token, UserCreate, UserLogin, UserResponse
from app.services.auth import AuthService, auth_service
router = APIRouter(prefix="/api/auth", tags=["auth"])
@router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def register(
user_data: UserCreate,
db: AsyncSession = Depends(get_db),
):
"""
注册新用户
"""
user = await auth_service.register_user(db, user_data)
return user
@router.post("/login", response_model=dict)
async def login(
login_data: UserLogin,
db: AsyncSession = Depends(get_db),
):
"""
用户登录
"""
user, access_token = await auth_service.authenticate_user(db, login_data)
return {
"access_token": access_token,
"token_type": "bearer",
"user": UserResponse.model_validate(user)
}
@router.post("/logout")
async def logout(
current_user: User = Depends(auth_service.get_current_user),
):
"""
用户登出(客户端需清除 Token)
"""
return {"message": "登出成功"}
@router.get("/me", response_model=UserResponse)
async def get_current_user_info(
current_user: User = Depends(auth_service.get_current_user),
):
"""
获取当前用户信息
"""
return current_user
@router.post("/refresh", response_model=Token)
async def refresh_token(
current_user: User = Depends(auth_service.get_current_user),
):
"""
刷新 Token
"""
from app.core.security import create_access_token
access_token = create_access_token(data={"sub": str(current_user.id), "email": current_user.email})
return Token(access_token=access_token)
+219
View File
@@ -0,0 +1,219 @@
"""
异常处理 API
提供异常的查询、更新、批量操作等接口
"""
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Body
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.tenant import get_current_company_id
from app.models.exception_item import ExceptionItem
from app.services.exception_service import (
get_exceptions,
update_exception,
batch_resolve_exceptions,
ExceptionService,
)
router = APIRouter(prefix="/api/exceptions", tags=["异常处理"])
@router.get("/")
async def list_exceptions(
task_id: Optional[int] = Query(None, description="任务ID"),
status: Optional[str] = Query(None, description="状态"),
severity: Optional[str] = Query(None, description="严重程度"),
exception_type: Optional[str] = Query(None, description="异常类型"),
page: int = Query(1, ge=1, description="页码"),
page_size: int = Query(20, ge=1, le=100, description="每页数量"),
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
) -> Dict[str, Any]:
"""
查询异常列表
支持按任务、状态、严重程度、类型筛选
"""
exceptions, total = await get_exceptions(
db=db,
task_id=task_id,
company_id=company_id,
status=status,
severity=severity,
exception_type=exception_type,
page=page,
page_size=page_size,
)
return {
"items": [
{
"id": e.id,
"task_id": e.task_id,
"exception_type": e.exception_type,
"severity": e.severity.lower() if e.severity else None,
"status": e.status.lower() if e.status else None,
"employee_id": e.employee_id,
"employee_name": e.employee_name,
"description": e.description,
"detail": e.detail,
"salary_amount": e.salary_amount,
"social_security_amount": e.social_security_amount,
"tax_amount": e.tax_amount,
"bank_amount": e.bank_amount,
"difference_amount": e.difference_amount,
"suggested_action": e.suggested_action,
"ai_suggestion": e.ai_suggestion,
"handling_note": e.handling_note,
"handled_by": e.handled_by,
"handler_name": e.handler.full_name if e.handler else None,
"handled_at": e.handled_at.isoformat() if e.handled_at else None,
"created_at": e.created_at.isoformat() if e.created_at else None,
"updated_at": e.updated_at.isoformat() if e.updated_at else None,
}
for e in exceptions
],
"total": total,
"page": page,
"page_size": page_size,
}
@router.get("/summary")
async def get_exception_summary(
task_id: Optional[int] = Query(None, description="任务ID"),
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
) -> Dict[str, Any]:
"""获取异常汇总统计"""
service = ExceptionService(db)
summary = await service.get_exception_summary(
task_id=task_id,
company_id=company_id,
)
return summary
@router.get("/{exception_id}")
async def get_exception_detail(
exception_id: int,
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
) -> Dict[str, Any]:
"""获取异常详情"""
service = ExceptionService(db)
exception = await service.get_exception(exception_id)
if not exception:
raise HTTPException(status_code=404, detail="异常不存在")
if exception.company_id != company_id:
raise HTTPException(status_code=403, detail="无权访问该异常")
return {
"id": exception.id,
"task_id": exception.task_id,
"exception_type": exception.exception_type,
"severity": exception.severity,
"status": exception.status,
"employee_id": exception.employee_id,
"employee_name": exception.employee_name,
"description": exception.description,
"detail": exception.detail,
"salary_amount": exception.salary_amount,
"social_security_amount": exception.social_security_amount,
"tax_amount": exception.tax_amount,
"bank_amount": exception.bank_amount,
"difference_amount": exception.difference_amount,
"suggested_action": exception.suggested_action,
"ai_suggestion": exception.ai_suggestion,
"handling_note": exception.handling_note,
"handled_by": exception.handled_by,
"handler_name": exception.handler.full_name if exception.handler else None,
"handled_at": exception.handled_at.isoformat() if exception.handled_at else None,
"created_at": exception.created_at.isoformat() if exception.created_at else None,
"updated_at": exception.updated_at.isoformat() if exception.updated_at else None,
}
@router.patch("/{exception_id}")
async def update_exception_status(
exception_id: int,
status: Optional[str] = Body(None),
handling_note: Optional[str] = Body(None),
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
):
"""更新异常状态"""
service = ExceptionService(db)
# 检查权限
exception = await service.get_exception(exception_id)
if not exception:
raise HTTPException(status_code=404, detail="异常不存在")
if exception.company_id != company_id:
raise HTTPException(status_code=403, detail="无权访问该异常")
updated = await service.update_exception(
exception_id=exception_id,
status=status,
handling_note=handling_note,
)
return {"success": True, "data": updated}
@router.post("/batch-update")
async def batch_update_exceptions(
exception_ids: List[int] = Body(..., description="异常ID列表"),
status: str = Body(..., description="新状态"),
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
) -> Dict[str, Any]:
"""批量更新异常状态"""
service = ExceptionService(db)
# 检查权限
query = select(ExceptionItem).where(ExceptionItem.id.in_(exception_ids))
result = await db.execute(query)
exceptions = result.scalars().all()
# 验证权限
for e in exceptions:
if e.company_id != company_id:
raise HTTPException(status_code=403, detail="存在无权访问的异常")
count = await service.batch_update_status(exception_ids, status)
return {"success": True, "updated_count": count}
@router.post("/batch-resolve")
async def batch_resolve(
exception_ids: List[int] = Body(..., description="异常ID列表"),
handling_note: str = Body(..., description="处理备注"),
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
) -> Dict[str, Any]:
"""批量处理异常(标记为已解决)"""
service = ExceptionService(db)
# 检查权限
query = select(ExceptionItem).where(ExceptionItem.id.in_(exception_ids))
result = await db.execute(query)
exceptions = result.scalars().all()
# 验证权限
for e in exceptions:
if e.company_id != company_id:
raise HTTPException(status_code=403, detail="存在无权访问的异常")
count = await service.batch_resolve(exception_ids, handling_note)
return {"success": True, "resolved_count": count}
+95
View File
@@ -0,0 +1,95 @@
"""
导出 API
提供对账结果导出、金蝶凭证导出等接口
"""
from typing import Any, Dict
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.tenant import get_current_company_id
from app.services.export_service import export_task_result, export_kingdee_voucher
router = APIRouter(prefix="/api/exports", tags=["导出"])
@router.get("/task/{task_id}")
async def export_task(
task_id: int,
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
):
"""
导出任务对账结果
返回 Excel 文件,包含:
- 概览
- 异常列表
- 异常统计
"""
try:
data = await export_task_result(db, task_id)
return StreamingResponse(
iter([data]),
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={
"Content-Disposition": f"attachment; filename=对账结果_{task_id}.xlsx"
},
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except ImportError as e:
raise HTTPException(status_code=500, detail="导出功能未启用,请安装 openpyxl")
@router.get("/kingdee/{task_id}")
async def export_kingdee(
task_id: int,
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
):
"""
导出金蝶凭证
返回 Excel 文件,可导入到金蝶系统
"""
try:
data = await export_kingdee_voucher(db, task_id)
return StreamingResponse(
iter([data]),
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={
"Content-Disposition": f"attachment; filename=金蝶凭证_{task_id}.xlsx"
},
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except ImportError as e:
raise HTTPException(status_code=500, detail="导出功能未启用,请安装 openpyxl")
@router.post("/task/{task_id}/async")
async def export_task_async(
task_id: int,
background_tasks: BackgroundTasks,
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
):
"""
异步导出任务对账结果
适用于大数据量导出的场景,返回导出任务ID
"""
# TODO: 实现异步导出任务
return {
"success": True,
"message": "异步导出任务已创建",
"task_id": task_id,
}
+288
View File
@@ -0,0 +1,288 @@
"""
字段映射 API 端点
提供字段识别、映射确认和规则管理功能
"""
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.services.auth import AuthService
from app.core.tenant import get_current_company
from app.schemas.mapping import (
FieldMappingResponse,
FieldMappingUpdate,
ConfirmMappingsRequest,
ConfirmMappingsResponse,
SaveAsRuleRequest,
SaveAsRuleResponse,
CompanyRuleResponse,
UpdateRuleStatusRequest,
RecognizeFieldsRequest,
RecognizeFieldsResponse,
TaskMappingOverview,
FileMappingSummary,
)
from app.services.mapping import MappingService
from app.models.user import User
from app.models.company import Company
router = APIRouter(prefix="/mappings", tags=["字段映射"])
def get_mapping_service(db: AsyncSession = Depends(get_db)) -> MappingService:
return MappingService(db)
@router.post("/recognize", response_model=RecognizeFieldsResponse)
async def recognize_fields(
request: RecognizeFieldsRequest,
company_id: int = Depends(get_current_company),
current_user: User = Depends(AuthService.get_current_user),
service: MappingService = Depends(get_mapping_service),
):
"""
触发 AI 字段识别
- 读取已上传文件的表头和样例数据
- 调用 AI 识别服务
- 保存映射建议
- 返回映射结果
"""
try:
mappings = await service.recognize_and_save(
company_id=company_id,
file_id=request.file_id,
file_type=request.file_type
)
# 统计置信度分布
high = sum(1 for m in mappings if m.confidence > 0.9)
medium = sum(1 for m in mappings if 0.7 <= m.confidence <= 0.9)
low = sum(1 for m in mappings if m.confidence < 0.7)
return RecognizeFieldsResponse(
file_id=request.file_id,
mappings=[FieldMappingResponse.model_validate(m) for m in mappings],
high_confidence_count=high,
medium_confidence_count=medium,
low_confidence_count=low,
needs_review=low > 0 or medium > 0
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"字段识别失败: {str(e)}")
@router.get("/task/{task_id}", response_model=TaskMappingOverview)
async def get_task_mappings(
task_id: int,
company_id: int = Depends(get_current_company),
current_user: User = Depends(AuthService.get_current_user),
service: MappingService = Depends(get_mapping_service),
):
"""
获取任务的字段映射概览
- 按文件分组返回所有映射
- 包含置信度统计
"""
try:
grouped_mappings = await service.get_mappings_by_task(task_id, company_id)
files = []
total_fields = 0
confirmed_fields = 0
for file_id, mappings in grouped_mappings.items():
file = mappings[0].file if mappings else None
high = sum(1 for m in mappings if m.confidence > 0.9)
medium = sum(1 for m in mappings if 0.7 <= m.confidence <= 0.9)
low = sum(1 for m in mappings if m.confidence < 0.7)
confirmed = sum(1 for m in mappings if m.confirmed)
files.append(FileMappingSummary(
file_id=file_id,
file_type=file.file_type if file else "",
file_name=file.original_filename if file else "",
total_fields=len(mappings),
confirmed_fields=confirmed,
high_confidence=high,
medium_confidence=medium,
low_confidence=low,
mappings=[FieldMappingResponse.model_validate(m) for m in mappings]
))
total_fields += len(mappings)
confirmed_fields += confirmed
needs_review = any(
f.medium_confidence > 0 or f.low_confidence > 0
for f in files
)
return TaskMappingOverview(
task_id=task_id,
total_files=len(files),
total_fields=total_fields,
confirmed_fields=confirmed_fields,
needs_review=needs_review,
files=files
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取映射失败: {str(e)}")
@router.get("/{mapping_id}", response_model=FieldMappingResponse)
async def get_mapping(
mapping_id: int,
current_user: User = Depends(AuthService.get_current_user),
service: MappingService = Depends(get_mapping_service),
):
"""获取单个字段映射"""
# 这里需要添加 company_id 检查
mapping = await service.db.get(mapping_id)
if not mapping:
raise HTTPException(status_code=404, detail="映射不存在")
return FieldMappingResponse.model_validate(mapping)
@router.put("/{mapping_id}", response_model=FieldMappingResponse)
async def update_mapping(
mapping_id: int,
update: FieldMappingUpdate,
current_user: User = Depends(AuthService.get_current_user),
service: MappingService = Depends(get_mapping_service),
):
"""
修改字段映射
- 修改标准字段
- 标记跳过
"""
mapping = await service.update_mapping(
mapping_id=mapping_id,
standard_field=update.standard_field,
is_skipped=update.is_skipped
)
if not mapping:
raise HTTPException(status_code=404, detail="映射不存在")
return FieldMappingResponse.model_validate(mapping)
@router.post("/confirm", response_model=ConfirmMappingsResponse)
async def confirm_mappings(
request: ConfirmMappingsRequest,
current_user: User = Depends(AuthService.get_current_user),
service: MappingService = Depends(get_mapping_service),
):
"""
批量确认字段映射
- 确认后映射将用于数据处理
- 不会自动保存为规则
"""
confirmed = await service.confirm_mappings(
mapping_ids=request.mapping_ids,
user_id=current_user.id
)
return ConfirmMappingsResponse(
confirmed_count=len(confirmed),
mappings=[FieldMappingResponse.model_validate(m) for m in confirmed]
)
@router.post("/{mapping_id}/save-as-rule", response_model=SaveAsRuleResponse)
async def save_mapping_as_rule(
mapping_id: int,
current_user: User = Depends(AuthService.get_current_user),
service: MappingService = Depends(get_mapping_service),
):
"""
将字段映射保存为企业规则
- 下次上传同类文件时自动应用规则
- 可在规则管理页面查看和管理
"""
from app.models.field_mapping import FieldMapping
# 获取映射
mapping = await service.db.get(FieldMapping, mapping_id)
if not mapping:
raise HTTPException(status_code=404, detail="映射不存在")
# 保存为规则
rule = await service.save_as_rule(mapping, current_user.id)
return SaveAsRuleResponse(
rule_id=rule.id,
source_field=mapping.source_field,
target_field=mapping.standard_field,
message=f"规则已保存:'{mapping.source_field}' -> '{mapping.standard_field}'"
)
# ===== 规则管理 API =====
@router.get("/rules/list", response_model=List[CompanyRuleResponse])
async def list_rules(
rule_type: Optional[str] = Query(None, description="规则类型"),
company_id: int = Depends(get_current_company),
current_user: User = Depends(AuthService.get_current_user),
service: MappingService = Depends(get_mapping_service),
):
"""获取企业的规则列表"""
rules = await service.get_company_rules(company_id, rule_type)
return [CompanyRuleResponse.model_validate(r) for r in rules]
@router.patch("/rules/{rule_id}/status", response_model=CompanyRuleResponse)
async def update_rule_status(
rule_id: int,
request: UpdateRuleStatusRequest,
company_id: int = Depends(get_current_company),
current_user: User = Depends(AuthService.get_current_user),
service: MappingService = Depends(get_mapping_service),
):
"""更新规则状态(启用/停用)"""
rule = await service.update_rule_status(rule_id, request.status)
if not rule:
raise HTTPException(status_code=404, detail="规则不存在")
if rule.company_id != company_id:
raise HTTPException(status_code=403, detail="无权操作此规则")
return CompanyRuleResponse.model_validate(rule)
@router.delete("/rules/{rule_id}")
async def delete_rule(
rule_id: int,
company_id: int = Depends(get_current_company),
current_user: User = Depends(AuthService.get_current_user),
service: MappingService = Depends(get_mapping_service),
):
"""删除规则"""
from app.models.company_rule import CompanyRule
rule = await service.db.get(CompanyRule, rule_id)
if not rule:
raise HTTPException(status_code=404, detail="规则不存在")
if rule.company_id != company_id:
raise HTTPException(status_code=403, detail="无权操作此规则")
success = await service.delete_rule(rule_id)
if not success:
raise HTTPException(status_code=500, detail="删除失败")
return {"message": "规则已删除"}
+141
View File
@@ -0,0 +1,141 @@
"""
对账执行 API
执行对账任务
"""
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.tenant import get_current_company_id
from app.models.reconciliation_task import ReconciliationTask
from app.services.reconciliation.engine import run_reconciliation
router = APIRouter(prefix="/api/reconciliation", tags=["对账执行"])
@router.post("/execute/{task_id}")
async def execute_reconciliation(
task_id: int,
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
) -> Dict[str, Any]:
"""
执行对账
触发对账引擎,处理上传的数据并返回结果
"""
# 获取任务
task = await db.get(ReconciliationTask, task_id)
if not task:
raise HTTPException(status_code=404, detail="任务不存在")
if task.company_id != company_id:
raise HTTPException(status_code=403, detail="无权访问该任务")
if task.status not in ["MAPPING_COMPLETED", "DATA_UPLOADED"]:
raise HTTPException(status_code=400, detail="任务状态不允许执行对账")
try:
# 获取上传的数据
salary_data = task.salary_data or []
social_security_data = task.social_security_data or []
tax_data = task.tax_data or []
bank_data = task.bank_data if hasattr(task, 'bank_data') else None
# 执行对账
result = await run_reconciliation(
db=db,
company_id=company_id,
task_id=task_id,
period=task.period,
salary_records=salary_data,
social_security_records=social_security_data,
tax_records=tax_data,
bank_records=bank_data,
enable_bank_rules=bool(bank_data),
)
return {
"success": True,
"task_id": task_id,
"result": {
"total_employees": result.total_employees,
"matched_employees": result.matched_employees,
"exception_count": result.exception_count,
"exceptions_by_type": result.exceptions_by_type,
"exceptions_by_severity": result.exceptions_by_severity,
"execution_time_ms": result.execution_time_ms,
"completed_at": result.completed_at,
},
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"对账执行失败: {str(e)}")
@router.get("/result/{task_id}")
async def get_reconciliation_result(
task_id: int,
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
) -> Dict[str, Any]:
"""
获取对账结果
返回已执行的对账结果汇总
"""
task = await db.get(ReconciliationTask, task_id)
if not task:
raise HTTPException(status_code=404, detail="任务不存在")
if task.company_id != company_id:
raise HTTPException(status_code=403, detail="无权访问该任务")
# 获取异常统计
from app.services.exception_service import ExceptionService
service = ExceptionService(db)
summary = await service.get_exception_summary(task_id=task_id, company_id=company_id)
return {
"task_id": task_id,
"period": task.period,
"total_employees": task.total_employees,
"matched_employees": task.matched_count,
"exception_count": task.exception_count,
"exceptions_by_type": summary.get("by_type", {}),
"exceptions_by_severity": summary.get("by_severity", {}),
"exceptions_by_status": summary.get("by_status", {}),
"completed_at": task.updated_at.isoformat() if task.updated_at else None,
}
@router.post("/retry/{task_id}")
async def retry_reconciliation(
task_id: int,
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
) -> Dict[str, Any]:
"""
重试对账
重新执行已完成的或失败的对账任务
"""
task = await db.get(ReconciliationTask, task_id)
if not task:
raise HTTPException(status_code=404, detail="任务不存在")
if task.company_id != company_id:
raise HTTPException(status_code=403, detail="无权访问该任务")
# 重置任务状态
task.status = "PROCESSING"
task.matched_count = 0
task.exception_count = 0
await db.commit()
# 执行对账
return await execute_reconciliation(task_id, db, company_id)
+181
View File
@@ -0,0 +1,181 @@
"""
对账任务 API
管理对账任务的生命周期
"""
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import Float
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from app.core.database import get_db
from app.core.tenant import get_current_company_id
from app.models.reconciliation_task import ReconciliationTask
from app.models.user import User
from app.schemas.user import UserResponse
router = APIRouter(prefix="/api/tasks", tags=["对账任务"])
@router.get("/", response_model=List[Dict[str, Any]])
async def list_tasks(
period: Optional[str] = Query(None, description="筛选月份,格式: 2026-04"),
status: Optional[str] = Query(None, description="筛选状态"),
skip: int = Query(0, ge=0, description="跳过记录数"),
limit: int = Query(50, ge=1, le=100, description="返回记录数"),
db: AsyncSession = Depends(get_db),
company_id: Optional[int] = Depends(get_current_company_id),
) -> List[Dict[str, Any]]:
"""
获取对账任务列表
支持按月份和状态筛选
"""
# 构建查询
query = select(ReconciliationTask).where(
ReconciliationTask.company_id == company_id
)
if period:
query = query.where(ReconciliationTask.period == period)
if status:
query = query.where(ReconciliationTask.status == status)
# 按创建时间倒序
query = query.order_by(ReconciliationTask.created_at.desc())
# 分页
query = query.offset(skip).limit(limit)
result = await db.execute(query)
tasks = result.scalars().all()
return [
{
"id": task.id,
"period": task.period,
"status": task.status,
"total_employees": task.total_employees,
"matched_count": task.matched_count,
"exception_count": task.exception_count,
"created_at": task.created_at.isoformat() if task.created_at else None,
}
for task in tasks
]
@router.get("/stats", response_model=Dict[str, Any])
async def get_task_stats(
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
) -> Dict[str, Any]:
"""
获取任务统计信息
返回本月任务数、待处理异常、已完成、匹配率等统计
"""
from datetime import datetime
from dateutil.relativedelta import relativedelta
# 计算本月时间范围
now = datetime.now()
first_day_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
next_month = first_day_of_month + relativedelta(months=1)
current_period = now.strftime("%Y-%m")
# 统计本月任务
from sqlalchemy import case as sql_case
query = select(
func.count(ReconciliationTask.id).label("total"),
func.sum(
sql_case(
(ReconciliationTask.status == "COMPLETED", 1),
else_=0
)
).label("completed"),
func.sum(
sql_case(
(ReconciliationTask.exception_count > 0, 1),
else_=0
)
).label("with_exceptions"),
).where(
ReconciliationTask.company_id == company_id,
ReconciliationTask.period == current_period,
)
result = await db.execute(query)
row = result.one()
total_tasks = row.total or 0
completed_tasks = row.completed or 0
# 获取待处理异常数
from app.models.exception_item import ExceptionItem
exception_query = select(
func.count(ExceptionItem.id)
).where(
ExceptionItem.company_id == company_id,
ExceptionItem.status == "PENDING",
)
exception_result = await db.execute(exception_query)
pending_exceptions = exception_result.scalar() or 0
# 计算匹配率
match_rate = 0.0
if total_tasks > 0:
match_query = select(
func.avg(
func.cast(ReconciliationTask.matched_count * 100.0 / func.nullif(ReconciliationTask.total_employees, 0), Float)
)
).where(
ReconciliationTask.company_id == company_id,
ReconciliationTask.period == current_period,
ReconciliationTask.status == "COMPLETED",
)
match_result = await db.execute(match_query)
match_rate = match_result.scalar() or 0.0
return {
"monthly_tasks": total_tasks,
"pending_exceptions": pending_exceptions,
"completed_tasks": completed_tasks,
"match_rate": round(match_rate, 1),
"current_period": current_period,
}
@router.get("/{task_id}", response_model=Dict[str, Any])
async def get_task(
task_id: int,
db: AsyncSession = Depends(get_db),
company_id: int = Depends(get_current_company_id),
) -> Dict[str, Any]:
"""
获取任务详情
"""
task = await db.get(ReconciliationTask, task_id)
if not task:
raise HTTPException(status_code=404, detail="任务不存在")
if task.company_id != company_id:
raise HTTPException(status_code=403, detail="无权访问该任务")
return {
"id": task.id,
"period": task.period,
"status": task.status,
"total_employees": task.total_employees,
"matched_count": task.matched_count,
"exception_count": task.exception_count,
"file_ids": task.file_ids,
"reconciliation_result": task.reconciliation_result,
"created_at": task.created_at.isoformat() if task.created_at else None,
"error_message": task.error_message,
}
+65
View File
@@ -0,0 +1,65 @@
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from app.core.config import get_settings
settings = get_settings()
# 创建异步数据库引擎
engine = create_async_engine(
settings.database_url,
echo=settings.debug,
pool_size=5,
max_overflow=10,
pool_pre_ping=True,
)
# 创建异步会话工厂
async_session_maker = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
# 声明式基类
class Base(DeclarativeBase):
pass
async def get_db() -> AsyncGenerator[AsyncSession, None]:
"""
数据库会话依赖注入
Yields:
AsyncSession: 数据库会话
"""
async with async_session_maker() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
async def init_db() -> None:
"""
初始化数据库(创建所有表)
仅用于开发环境,生产环境使用 Alembic 迁移
"""
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async def close_db() -> None:
"""
关闭数据库连接
"""
await engine.dispose()
+191
View File
@@ -0,0 +1,191 @@
from typing import Any
from fastapi import HTTPException, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from sqlalchemy.exc import IntegrityError
from app.core.exceptions import (
BusinessException,
ExternalServiceException,
ForbiddenException,
NotFoundException,
S2FException,
UnauthorizedException,
ValidationException,
)
from app.core.logging import logger
def create_error_response(
code: str,
message: str,
details: Any = None,
status_code: int = status.HTTP_500_INTERNAL_SERVER_ERROR,
) -> JSONResponse:
"""
创建统一错误响应
Args:
code: 错误代码
message: 错误消息
details: 错误详情
status_code: HTTP 状态码
Returns:
JSON 响应
"""
error_data = {
"error": {
"code": code,
"message": message,
}
}
if details:
error_data["error"]["details"] = details
return JSONResponse(
status_code=status_code,
content=error_data,
)
async def s2f_exception_handler(request: Request, exc: S2FException) -> JSONResponse:
"""
处理自定义业务异常
Args:
request: 请求对象
exc: 异常对象
Returns:
JSON 响应
"""
logger.warning(
"business_exception",
code=exc.code,
message=exc.message,
details=exc.details,
path=request.url.path,
)
# 根据异常类型映射 HTTP 状态码
status_code_map = {
NotFoundException: status.HTTP_404_NOT_FOUND,
UnauthorizedException: status.HTTP_401_UNAUTHORIZED,
ForbiddenException: status.HTTP_403_FORBIDDEN,
ValidationException: status.HTTP_422_UNPROCESSABLE_ENTITY,
BusinessException: status.HTTP_400_BAD_REQUEST,
ExternalServiceException: status.HTTP_503_SERVICE_UNAVAILABLE,
}
status_code = status_code_map.get(type(exc), status.HTTP_500_INTERNAL_SERVER_ERROR)
return create_error_response(
code=exc.code,
message=exc.message,
details=exc.details,
status_code=status_code,
)
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
"""
处理请求验证异常
Args:
request: 请求对象
exc: 验证异常
Returns:
JSON 响应
"""
logger.warning(
"validation_error",
errors=exc.errors(),
body=exc.body,
path=request.url.path,
)
return create_error_response(
code="VALIDATION_ERROR",
message="请求参数验证失败",
details={"errors": exc.errors()},
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
)
async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
"""
处理 HTTP 异常
Args:
request: 请求对象
exc: HTTP 异常
Returns:
JSON 响应
"""
logger.warning(
"http_exception",
status_code=exc.status_code,
detail=exc.detail,
path=request.url.path,
)
return create_error_response(
code="HTTP_ERROR",
message=str(exc.detail),
status_code=exc.status_code,
)
async def integrity_error_handler(request: Request, exc: IntegrityError) -> JSONResponse:
"""
处理数据库完整性错误
Args:
request: 请求对象
exc: 完整性错误
Returns:
JSON 响应
"""
logger.error(
"database_integrity_error",
error=str(exc),
path=request.url.path,
)
return create_error_response(
code="DATABASE_ERROR",
message="数据库操作失败,可能存在重复或约束冲突",
status_code=status.HTTP_409_CONFLICT,
)
async def generic_exception_handler(request: Request, exc: Exception) -> JSONResponse:
"""
处理未捕获的异常
Args:
request: 请求对象
exc: 异常对象
Returns:
JSON 响应
"""
logger.error(
"unhandled_exception",
error=str(exc),
error_type=type(exc).__name__,
path=request.url.path,
exc_info=True,
)
return create_error_response(
code="INTERNAL_ERROR",
message="服务器内部错误",
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
+65
View File
@@ -0,0 +1,65 @@
from typing import Any, Optional
class S2FException(Exception):
"""
财务 AI 助手基础异常类
Attributes:
message: 错误消息
code: 错误代码
details: 错误详情
"""
def __init__(
self,
message: str,
code: str = "INTERNAL_ERROR",
details: Optional[dict[str, Any]] = None,
) -> None:
self.message = message
self.code = code
self.details = details or {}
super().__init__(self.message)
class NotFoundException(S2FException):
"""资源未找到异常"""
def __init__(self, message: str = "资源未找到", details: Optional[dict[str, Any]] = None) -> None:
super().__init__(message=message, code="NOT_FOUND", details=details)
class UnauthorizedException(S2FException):
"""未授权异常"""
def __init__(self, message: str = "未授权访问", details: Optional[dict[str, Any]] = None) -> None:
super().__init__(message=message, code="UNAUTHORIZED", details=details)
class ForbiddenException(S2FException):
"""禁止访问异常"""
def __init__(self, message: str = "禁止访问", details: Optional[dict[str, Any]] = None) -> None:
super().__init__(message=message, code="FORBIDDEN", details=details)
class ValidationException(S2FException):
"""数据验证异常"""
def __init__(self, message: str = "数据验证失败", details: Optional[dict[str, Any]] = None) -> None:
super().__init__(message=message, code="VALIDATION_ERROR", details=details)
class BusinessException(S2FException):
"""业务逻辑异常"""
def __init__(self, message: str, code: str = "BUSINESS_ERROR", details: Optional[dict[str, Any]] = None) -> None:
super().__init__(message=message, code=code, details=details)
class ExternalServiceException(S2FException):
"""外部服务异常"""
def __init__(self, message: str = "外部服务调用失败", details: Optional[dict[str, Any]] = None) -> None:
super().__init__(message=message, code="EXTERNAL_SERVICE_ERROR", details=details)
+61
View File
@@ -0,0 +1,61 @@
# 权限常量定义
# 基于 PRD 第7章权限设计
# 任务管理权限
PERM_TASK_CREATE = "task:create"
PERM_TASK_VIEW = "task:view"
PERM_TASK_UPDATE = "task:update"
PERM_TASK_DELETE = "task:delete"
PERM_TASK_EXPORT = "task:export"
# 用户管理权限
PERM_USER_CREATE = "user:create"
PERM_USER_VIEW = "user:view"
PERM_USER_UPDATE = "user:update"
PERM_USER_DELETE = "user:delete"
# 企业管理权限
PERM_COMPANY_VIEW = "company:view"
PERM_COMPANY_UPDATE = "company:update"
# 审计日志权限
PERM_AUDIT_VIEW = "audit:view"
# 角色默认权限映射
ROLE_PERMISSIONS = {
"管理员": [
PERM_TASK_CREATE, PERM_TASK_VIEW, PERM_TASK_UPDATE, PERM_TASK_DELETE, PERM_TASK_EXPORT,
PERM_USER_CREATE, PERM_USER_VIEW, PERM_USER_UPDATE, PERM_USER_DELETE,
PERM_COMPANY_VIEW, PERM_COMPANY_UPDATE,
PERM_AUDIT_VIEW,
],
"财务主管": [
PERM_TASK_CREATE, PERM_TASK_VIEW, PERM_TASK_UPDATE, PERM_TASK_DELETE, PERM_TASK_EXPORT,
PERM_USER_CREATE, PERM_USER_VIEW, PERM_USER_UPDATE,
PERM_COMPANY_VIEW,
PERM_AUDIT_VIEW,
],
"会计": [
PERM_TASK_CREATE, PERM_TASK_VIEW, PERM_TASK_UPDATE, PERM_TASK_EXPORT,
PERM_USER_VIEW,
],
"出纳": [
PERM_TASK_VIEW, PERM_TASK_EXPORT,
],
"人事": [
PERM_TASK_VIEW,
],
}
def get_role_permissions(role: str) -> list[str]:
"""
获取角色的默认权限列表
Args:
role: 角色名称
Returns:
权限列表
"""
return ROLE_PERMISSIONS.get(role, [])
+76
View File
@@ -0,0 +1,76 @@
from datetime import datetime, timedelta
from typing import Any
import bcrypt
from jose import JWTError, jwt
from app.core.config import get_settings
settings = get_settings()
def hash_password(password: str) -> str:
"""
加密密码
Args:
password: 明文密码
Returns:
加密后的密码
"""
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""
验证密码
Args:
plain_password: 明文密码
hashed_password: 加密后的密码
Returns:
密码是否正确
"""
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
def create_access_token(data: dict[str, Any], expires_delta: timedelta | None = None) -> str:
"""
创建访问令牌
Args:
data: 要编码的数据
expires_delta: 过期时间(可选)
Returns:
JWT token
"""
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=settings.jwt_access_token_expire_minutes)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
return encoded_jwt
def decode_access_token(token: str) -> dict[str, Any] | None:
"""
解码访问令牌
Args:
token: JWT token
Returns:
解码后的数据,解码失败返回 None
"""
try:
payload = jwt.decode(token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm])
return payload
except JWTError:
return None
+108
View File
@@ -0,0 +1,108 @@
from contextvars import ContextVar
from typing import Optional
from fastapi import Depends, Request
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.models.company import Company
from app.services.company import company_service
# 当前租户的上下文变量
_current_company_id: ContextVar[Optional[int]] = ContextVar("current_company_id", default=None)
def get_current_company_id(
request: Request,
) -> Optional[int]:
"""
获取当前租户 ID
从请求头 X-Company-ID 获取租户 ID
Args:
request: FastAPI 请求对象
Returns:
当前租户 ID,未设置则返回 None
"""
company_id_str = request.headers.get("X-Company-ID")
if not company_id_str:
return None
try:
return int(company_id_str)
except ValueError:
return None
def set_current_company_id(company_id: Optional[int]) -> None:
"""
设置当前租户 ID
Args:
company_id: 租户 ID
"""
_current_company_id.set(company_id)
async def get_current_company(
request: Request,
db: AsyncSession = Depends(get_db),
) -> Optional[Company]:
"""
从请求头获取当前企业
支持两种方式:
1. HTTP Header: X-Company-ID
2. JWT Token 中的 company_id(后续实现认证后)
Args:
request: FastAPI 请求对象
db: 数据库会话
Returns:
当前企业对象,不存在则返回 None
"""
# 从请求头获取 company_id
company_id_str = request.headers.get("X-Company-ID")
if not company_id_str:
return None
try:
company_id = int(company_id_str)
except ValueError:
return None
# 设置上下文变量
set_current_company_id(company_id)
# 查询企业
company = await company_service.get_company(db, company_id)
return company
def require_company(
company: Optional[Company] = Depends(get_current_company),
) -> Company:
"""
要求必须有企业上下文的依赖
Args:
company: 当前企业
Returns:
企业对象
Raises:
HTTPException: 未提供企业 ID 或企业不存在
"""
if not company:
from fastapi import HTTPException, status
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="未提供企业 ID 或企业不存在",
)
return company
+25
View File
@@ -1,7 +1,18 @@
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.exc import IntegrityError
from app.api import auth, mappings, exceptions, exports, reconciliation, tasks
from app.core.config import get_settings
from app.core.error_handlers import (
generic_exception_handler,
http_exception_handler,
integrity_error_handler,
s2f_exception_handler,
validation_exception_handler,
)
from app.core.exceptions import S2FException
from app.core.logging import configure_logging
settings = get_settings()
@@ -21,6 +32,20 @@ app.add_middleware(
allow_headers=["*"],
)
# 注册异常处理器
app.add_exception_handler(S2FException, s2f_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(IntegrityError, integrity_error_handler)
app.add_exception_handler(Exception, generic_exception_handler)
# 注册路由
app.include_router(auth.router)
app.include_router(mappings.router)
app.include_router(exceptions.router)
app.include_router(exports.router)
app.include_router(reconciliation.router)
app.include_router(tasks.router)
@app.get("/api/health", tags=["health"])
async def health_check() -> dict[str, str]:
+53
View File
@@ -0,0 +1,53 @@
from enum import Enum
from sqlalchemy import Integer, JSON, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import BaseModel
class AuditAction(str, Enum):
"""审计操作类型"""
CREATE = "CREATE"
UPDATE = "UPDATE"
DELETE = "DELETE"
VIEW = "VIEW"
EXPORT = "EXPORT"
LOGIN = "LOGIN"
LOGOUT = "LOGOUT"
UPLOAD = "UPLOAD"
DOWNLOAD = "DOWNLOAD"
class AuditLog(BaseModel):
"""
审计日志模型
记录所有关键业务操作
Attributes:
company_id: 企业 ID
user_id: 用户 ID
action: 操作类型
resource_type: 资源类型 (如 company, user, task, file)
resource_id: 资源 ID
details: 操作详情 (JSON)
ip_address: IP 地址
user_agent: User-Agent
"""
__tablename__ = "audit_logs"
company_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
user_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
action: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
resource_type: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
resource_id: Mapped[str | None] = mapped_column(String(200), nullable=True, index=True)
details: Mapped[dict | None] = mapped_column(JSON, nullable=True)
ip_address: Mapped[str | None] = mapped_column(String(50), nullable=True)
user_agent: Mapped[str | None] = mapped_column(Text, nullable=True)
def __repr__(self) -> str:
return (
f"<AuditLog(id={self.id}, company_id={self.company_id}, "
f"action='{self.action}', resource_type='{self.resource_type}')>"
)
+39
View File
@@ -0,0 +1,39 @@
from datetime import datetime
from typing import Any
from sqlalchemy import DateTime, Integer
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.sql import func
from app.core.database import Base
class BaseModel(Base):
"""
所有数据库模型的基类
包含通用字段:id, created_at, updated_at
"""
__abstract__ = True
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True, autoincrement=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
server_default=func.now(),
nullable=False,
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
server_default=func.now(),
onupdate=func.now(),
nullable=False,
)
def dict(self) -> dict[str, Any]:
"""
将模型转换为字典
"""
return {
column.name: getattr(self, column.name)
for column in self.__table__.columns
}
+63
View File
@@ -0,0 +1,63 @@
from enum import Enum
from sqlalchemy import Boolean, Integer, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import BaseModel
class CompanyPlan(str, Enum):
"""企业套餐类型"""
FREE = "免费版"
BASIC = "基础版"
PROFESSIONAL = "专业版"
ENTERPRISE = "企业版"
class CompanyStatus(str, Enum):
"""企业状态"""
ACTIVE = "正常"
SUSPENDED = "暂停"
EXPIRED = "已过期"
DELETED = "已删除"
class Company(BaseModel):
"""
企业模型 - 多租户隔离的核心实体
Attributes:
name: 企业名称
plan: 套餐类型
data_retention_months: 数据保留月数
status: 企业状态
max_users: 最大用户数
is_trial: 是否试用
"""
__tablename__ = "companies"
name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
plan: Mapped[str] = mapped_column(
String(50),
nullable=False,
default=CompanyPlan.FREE.value
)
data_retention_months: Mapped[int] = mapped_column(Integer, nullable=False, default=12)
status: Mapped[str] = mapped_column(
String(20),
nullable=False,
default=CompanyStatus.ACTIVE.value,
index=True,
)
max_users: Mapped[int] = mapped_column(Integer, nullable=False, default=5)
is_trial: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
# 关系
users = relationship("User", back_populates="company")
field_mappings = relationship("FieldMapping", back_populates="company")
rules = relationship("CompanyRule", back_populates="company")
tasks = relationship("ReconciliationTask", back_populates="company")
def __repr__(self) -> str:
return f"<Company(id={self.id}, name='{self.name}', plan='{self.plan}')>"
+57
View File
@@ -0,0 +1,57 @@
"""
企业规则模型
用于存储企业自定义的映射规则,实现规则复用
"""
from datetime import datetime
from enum import Enum
from typing import Optional
from sqlalchemy import ForeignKey, Integer, String, Boolean, DateTime, JSON
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import BaseModel
class RuleType(str, Enum):
"""规则类型"""
FIELD_MAPPING = "FIELD_MAPPING" # 字段映射规则
ACCOUNT_MAPPING = "ACCOUNT_MAPPING" # 科目映射规则
DEPARTMENT_MAPPING = "DEPARTMENT_MAPPING" # 部门映射规则
class RuleStatus(str, Enum):
"""规则状态"""
ACTIVE = "ACTIVE" # 启用
INACTIVE = "INACTIVE" # 停用
class CompanyRule(BaseModel):
"""
企业规则模型
存储企业自定义的业务规则,用于自动应用
"""
__tablename__ = "company_rules"
company_id: Mapped[int] = mapped_column(Integer, ForeignKey("companies.id"), nullable=False, index=True)
rule_type: Mapped[str] = mapped_column(String(50), nullable=False, index=True, comment="规则类型")
match_condition: Mapped[dict] = mapped_column(JSON, nullable=False, comment="匹配条件")
target_value: Mapped[str] = mapped_column(String(100), nullable=False, comment="目标值")
priority: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment="优先级,数字越大优先级越高")
status: Mapped[str] = mapped_column(String(20), nullable=False, default=RuleStatus.ACTIVE.value, comment="状态")
description: Mapped[Optional[str]] = mapped_column(String(500), nullable=True, comment="规则描述")
match_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment="匹配次数")
last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey("users.id"), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey("users.id"), nullable=True)
# 关系
company = relationship("Company", back_populates="rules")
creator = relationship("User", foreign_keys=[created_by])
updater = relationship("User", foreign_keys=[updated_by])
def __repr__(self) -> str:
return f"<CompanyRule(type='{self.rule_type}', target='{self.target_value}', priority={self.priority})>"
+98
View File
@@ -0,0 +1,98 @@
"""
异常项模型
存储对账过程中检测到的异常
"""
from datetime import datetime
from enum import Enum
from typing import Optional
from sqlalchemy import ForeignKey, Integer, String, Text, DateTime, JSON, Float
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import BaseModel
class ExceptionType(str, Enum):
"""异常类型"""
# 第一阶段:工资表内部异常
MISSING_EMPLOYEE = "MISSING_EMPLOYEE" # 员工缺失(三个表之一缺失该员工)
AMOUNT_MISMATCH = "AMOUNT_MISMATCH" # 金额不匹配
ZERO_AMOUNT = "ZERO_AMOUNT" # 金额为零
NEGATIVE_AMOUNT = "NEGATIVE_AMOUNT" # 负数金额
UNUSUAL_AMOUNT = "UNUSUAL_AMOUNT" # 金额异常(过大或过小)
DUPLICATE_EMPLOYEE = "DUPLICATE_EMPLOYEE" # 重复员工
# 第二阶段:银行实发对账(预留)
BANK_MISMATCH = "BANK_MISMATCH" # 银行实发与工资表不匹配
BANK_MISSING = "BANK_MISSING" # 银行记录缺失
BANK_EXTRA = "BANK_EXTRA" # 银行多余记录
class ExceptionStatus(str, Enum):
"""异常状态"""
PENDING = "PENDING" # 待处理
CONFIRMED = "CONFIRMED" # 已确认
IGNORED = "IGNORED" # 已忽略
RESOLVED = "RESOLVED" # 已解决
class ExceptionSeverity(str, Enum):
"""异常严重程度"""
LOW = "LOW" # 低
MEDIUM = "MEDIUM" # 中
HIGH = "HIGH" # 高
CRITICAL = "CRITICAL" # 严重
class ExceptionItem(BaseModel):
"""
异常项模型
记录对账过程中检测到的各类异常
"""
__tablename__ = "exception_items"
company_id: Mapped[int] = mapped_column(Integer, ForeignKey("companies.id"), nullable=False, index=True)
task_id: Mapped[int] = mapped_column(Integer, ForeignKey("reconciliation_tasks.id"), nullable=False, index=True)
# 异常基本信息
exception_type: Mapped[str] = mapped_column(String(50), nullable=False, index=True, comment="异常类型")
severity: Mapped[str] = mapped_column(String(20), nullable=False, default=ExceptionSeverity.MEDIUM.value, comment="严重程度")
status: Mapped[str] = mapped_column(String(20), nullable=False, default=ExceptionStatus.PENDING.value, index=True, comment="状态")
# 关联的员工信息
employee_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True, comment="员工ID")
employee_name: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, comment="员工姓名")
# 异常详情
description: Mapped[str] = mapped_column(Text, nullable=False, comment="异常描述")
detail: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True, comment="详细信息")
# 涉及的金额
salary_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True, comment="工资表金额")
social_security_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True, comment="社保表金额")
tax_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True, comment="个税表金额")
bank_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True, comment="银行实发金额")
# 差异金额
difference_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True, comment="差异金额")
# 建议处理方式
suggested_action: Mapped[Optional[str]] = mapped_column(String(200), nullable=True, comment="建议处理方式")
ai_suggestion: Mapped[Optional[str]] = mapped_column(Text, nullable=True, comment="AI 分析建议")
# 处理信息
handled_by: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey("users.id"), nullable=True)
handled_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
handling_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True, comment="处理备注")
# 关系
company = relationship("Company", backref="exceptions")
task = relationship("ReconciliationTask", backref="exceptions")
handler = relationship("User", foreign_keys=[handled_by])
def __repr__(self) -> str:
return f"<ExceptionItem(id={self.id}, type='{self.exception_type}', status='{self.status}')>"
+43
View File
@@ -0,0 +1,43 @@
"""
字段映射模型
用于存储 AI 识别的字段映射结果
"""
from datetime import datetime
from typing import List, Optional
from sqlalchemy import ForeignKey, Integer, String, Float, Boolean, DateTime, JSON, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import BaseModel
class FieldMapping(BaseModel):
"""
字段映射模型
记录源字段到标准字段的映射关系
"""
__tablename__ = "field_mappings"
company_id: Mapped[int] = mapped_column(Integer, ForeignKey("companies.id"), nullable=False, index=True)
file_id: Mapped[int] = mapped_column(Integer, ForeignKey("uploaded_files.id"), nullable=False, index=True)
source_field: Mapped[str] = mapped_column(String(100), nullable=False, comment="源字段名")
standard_field: Mapped[str] = mapped_column(String(100), nullable=False, comment="标准字段名")
confidence: Mapped[float] = mapped_column(Float, nullable=False, default=0.0, comment="置信度 0-1")
confirmed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, comment="是否已确认")
confirmed_by: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey("users.id"), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sample_values: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True, comment="样例值")
reasoning: Mapped[Optional[str]] = mapped_column(Text, nullable=True, comment="AI 判断依据")
is_skipped: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, comment="是否跳过")
# 关系
company = relationship("Company", back_populates="field_mappings")
file = relationship("UploadedFile", back_populates="field_mappings")
confirmed_by_user = relationship("User", foreign_keys=[confirmed_by])
def __repr__(self) -> str:
return f"<FieldMapping(source='{self.source_field}' -> standard='{self.standard_field}', confidence={self.confidence})>"
+73
View File
@@ -0,0 +1,73 @@
"""
对账任务模型
用于管理工资对账任务的生命周期
"""
from datetime import datetime
from enum import Enum
from typing import List, Optional
from sqlalchemy import ForeignKey, Integer, String, DateTime, JSON, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import BaseModel
class TaskStatus(str, Enum):
"""任务状态"""
CREATED = "CREATED" # 已创建
FILES_UPLOADED = "FILES_UPLOADED" # 文件已上传
PARSING = "PARSING" # 解析中
WAITING_MAPPING_CONFIRM = "WAITING_MAPPING_CONFIRM" # 等待字段映射确认
MAPPING_CONFIRMED = "MAPPING_CONFIRMED" # 字段映射已确认
RECONCILING = "RECONCILING" # 对账中
COMPLETED = "COMPLETED" # 完成
FAILED = "FAILED" # 失败
class ReconciliationTask(BaseModel):
"""
对账任务模型
管理一次完整的工资对账流程
"""
__tablename__ = "reconciliation_tasks"
company_id: Mapped[int] = mapped_column(Integer, ForeignKey("companies.id"), nullable=False, index=True)
name: Mapped[str] = mapped_column(String(200), nullable=False, comment="任务名称")
period: Mapped[str] = mapped_column(String(20), nullable=False, index=True, comment="对账期间,如 2024-01")
status: Mapped[str] = mapped_column(String(30), nullable=False, default=TaskStatus.CREATED.value, index=True)
# 文件信息 (JSON 格式存储)
file_ids: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True, comment="关联的文件ID")
# 字段映射状态
mapping_completed: Mapped[bool] = mapped_column(Integer, nullable=False, default=False)
mapping_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
mapping_confirmed_by: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey("users.id"), nullable=True)
# 对账结果摘要
total_employees: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
matched_count: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
exception_count: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# 结果数据 (JSON)
reconciliation_result: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
# 错误信息
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 确认信息
created_by: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey("users.id"), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
# 关系
company = relationship("Company", back_populates="tasks")
creator = relationship("User", foreign_keys=[created_by])
confirm_user = relationship("User", foreign_keys=[mapping_confirmed_by])
def __repr__(self) -> str:
return f"<ReconciliationTask(id={self.id}, name='{self.name}', status='{self.status}')>"
+130
View File
@@ -0,0 +1,130 @@
"""
标准字段定义
定义工资表、社保表、个税表的标准字段
"""
from enum import Enum
class StandardField(str, Enum):
"""标准字段枚举"""
# ===== 公共字段 =====
EMPLOYEE_NAME = "员工姓名" # 员工姓名
EMPLOYEE_ID = "工号" # 工号
DEPARTMENT = "部门" # 部门
POSITION = "岗位" # 岗位/职位
# ===== 工资表字段 =====
BASE_SALARY = "基本工资" # 基本工资
BONUS = "奖金" # 奖金
ALLOWANCE = "补贴" # 补贴
OVERTIME_PAY = "加班费" # 加班费
DEDUCTION = "扣款" # 扣款
GROSS_SALARY = "应发工资" # 应发工资
NET_SALARY = "实发工资" # 实发工资/净工资
BANK_CARD = "银行账号" # 银行账号
ID_CARD = "身份证号" # 身份证号
# ===== 社保表字段 =====
SOCIAL_SECURITY_BASE = "社保基数" # 社保基数
PENSION_INSURANCE = "养老保险" # 养老保险(个人)
MEDICAL_INSURANCE = "医疗保险" # 医疗保险(个人)
UNEMPLOYMENT_INSURANCE = "失业保险" # 失业保险(个人)
HOUSING_FUND = "公积金" # 住房公积金(个人)
PENSION_INSURANCE_COMPANY = "养老保险(公司)" # 养老保险(公司)
MEDICAL_INSURANCE_COMPANY = "医疗保险(公司)" # 医疗保险(公司)
UNEMPLOYMENT_INSURANCE_COMPANY = "失业保险(公司)" # 失业保险(公司)
HOUSING_FUND_COMPANY = "公积金(公司)" # 住房公积金(公司)
SOCIAL_SECURITY_TOTAL = "社保合计" # 社保合计
# ===== 个税表字段 =====
TAXABLE_INCOME = "应税收入" # 应税收入
PRE_TAX_DEDUCTION = "税前扣除" # 税前扣除(三险一金等)
TAX_FREE_INCOME = "免税收入" # 免税收入
TAX_EXEMPT_INCOME = "税前减免" # 税前减免
QUICK_DEDUCTION = "速算扣除数" # 速算扣除数
TAX_AMOUNT = "应缴个税" # 应缴个人所得税
TAX_PAID = "已缴个税" # 已缴个人所得税
AFTER_TAX_INCOME = "税后收入" # 税后收入
# 标准字段分组
FIELD_GROUPS = {
"公共字段": [
StandardField.EMPLOYEE_NAME,
StandardField.EMPLOYEE_ID,
StandardField.DEPARTMENT,
StandardField.POSITION,
],
"工资表字段": [
StandardField.BASE_SALARY,
StandardField.BONUS,
StandardField.ALLOWANCE,
StandardField.OVERTIME_PAY,
StandardField.DEDUCTION,
StandardField.GROSS_SALARY,
StandardField.NET_SALARY,
StandardField.BANK_CARD,
StandardField.ID_CARD,
],
"社保表字段": [
StandardField.SOCIAL_SECURITY_BASE,
StandardField.PENSION_INSURANCE,
StandardField.MEDICAL_INSURANCE,
StandardField.UNEMPLOYMENT_INSURANCE,
StandardField.HOUSING_FUND,
StandardField.PENSION_INSURANCE_COMPANY,
StandardField.MEDICAL_INSURANCE_COMPANY,
StandardField.UNEMPLOYMENT_INSURANCE_COMPANY,
StandardField.HOUSING_FUND_COMPANY,
StandardField.SOCIAL_SECURITY_TOTAL,
],
"个税表字段": [
StandardField.TAXABLE_INCOME,
StandardField.PRE_TAX_DEDUCTION,
StandardField.TAX_FREE_INCOME,
StandardField.TAX_EXEMPT_INCOME,
StandardField.QUICK_DEDUCTION,
StandardField.TAX_AMOUNT,
StandardField.TAX_PAID,
StandardField.AFTER_TAX_INCOME,
],
}
# 字段类型映射
FIELD_TYPES = {
StandardField.EMPLOYEE_NAME.value: "string",
StandardField.EMPLOYEE_ID.value: "string",
StandardField.DEPARTMENT.value: "string",
StandardField.POSITION.value: "string",
StandardField.BASE_SALARY.value: "number",
StandardField.BONUS.value: "number",
StandardField.ALLOWANCE.value: "number",
StandardField.OVERTIME_PAY.value: "number",
StandardField.DEDUCTION.value: "number",
StandardField.GROSS_SALARY.value: "number",
StandardField.NET_SALARY.value: "number",
StandardField.BANK_CARD.value: "string",
StandardField.ID_CARD.value: "string",
StandardField.SOCIAL_SECURITY_BASE.value: "number",
StandardField.PENSION_INSURANCE.value: "number",
StandardField.MEDICAL_INSURANCE.value: "number",
StandardField.UNEMPLOYMENT_INSURANCE.value: "number",
StandardField.HOUSING_FUND.value: "number",
StandardField.PENSION_INSURANCE_COMPANY.value: "number",
StandardField.MEDICAL_INSURANCE_COMPANY.value: "number",
StandardField.UNEMPLOYMENT_INSURANCE_COMPANY.value: "number",
StandardField.HOUSING_FUND_COMPANY.value: "number",
StandardField.SOCIAL_SECURITY_TOTAL.value: "number",
StandardField.TAXABLE_INCOME.value: "number",
StandardField.PRE_TAX_DEDUCTION.value: "number",
StandardField.TAX_FREE_INCOME.value: "number",
StandardField.TAX_EXEMPT_INCOME.value: "number",
StandardField.QUICK_DEDUCTION.value: "number",
StandardField.TAX_AMOUNT.value: "number",
StandardField.TAX_PAID.value: "number",
StandardField.AFTER_TAX_INCOME.value: "number",
}
+59
View File
@@ -0,0 +1,59 @@
from enum import Enum
from typing import List
from sqlalchemy import ForeignKey, Integer, String, BigInteger, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import BaseModel
class FileType(str, Enum):
"""文件类型"""
SALARY = "工资表"
SOCIAL_SECURITY = "社保表"
TAX = "个税表"
class ParseStatus(str, Enum):
"""解析状态"""
PENDING = "待解析"
PARSING = "解析中"
SUCCESS = "解析成功"
FAILED = "解析失败"
class UploadedFile(BaseModel):
"""
上传文件模型
Attributes:
company_id: 企业ID
task_id: 对账任务ID(可选)
file_type: 文件类型
original_filename: 原始文件名
stored_filename: 存储文件名
file_size: 文件大小(字节)
mime_type: MIME类型
parse_status: 解析状态
parse_error: 解析错误信息
"""
__tablename__ = "uploaded_files"
company_id: Mapped[int] = mapped_column(Integer, ForeignKey("companies.id"), nullable=False, index=True)
task_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
file_type: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
stored_filename: Mapped[str] = mapped_column(String(255), nullable=False, unique=True)
file_size: Mapped[int] = mapped_column(BigInteger, nullable=False)
mime_type: Mapped[str] = mapped_column(String(100), nullable=False)
parse_status: Mapped[str] = mapped_column(String(20), nullable=False, default=ParseStatus.PENDING.value, index=True)
parse_error: Mapped[str | None] = mapped_column(Text, nullable=True)
# 关系
field_mappings: Mapped[List["FieldMapping"]] = relationship(
"FieldMapping", back_populates="file", lazy="selectin"
)
def __repr__(self) -> str:
return f"<UploadedFile(id={self.id}, filename='{self.original_filename}', type='{self.file_type}')>"
+62
View File
@@ -0,0 +1,62 @@
from enum import Enum
from sqlalchemy import Boolean, ForeignKey, Integer, JSON, String, DateTime
from sqlalchemy.orm import Mapped, mapped_column, relationship
from datetime import datetime
from app.models.base import BaseModel
class UserRole(str, Enum):
"""用户角色"""
ADMIN = "管理员"
FINANCE_MANAGER = "财务主管"
ACCOUNTANT = "会计"
CASHIER = "出纳"
HR = "人事"
class UserStatus(str, Enum):
"""用户状态"""
ACTIVE = "正常"
DISABLED = "禁用"
LOCKED = "锁定"
class User(BaseModel):
"""
用户模型
Attributes:
company_id: 企业ID
email: 邮箱(登录账号)
hashed_password: 加密后的密码
full_name: 姓名
role: 角色
permissions: 权限列表(JSONB
status: 状态
last_login_at: 最后登录时间
"""
__tablename__ = "users"
company_id: Mapped[int] = mapped_column(Integer, ForeignKey("companies.id"), nullable=False, index=True)
email: Mapped[str] = mapped_column(String(255), nullable=False, unique=True, index=True)
hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
full_name: Mapped[str] = mapped_column(String(100), nullable=False)
role: Mapped[str] = mapped_column(String(50), nullable=False, default=UserRole.ACCOUNTANT.value)
permissions: Mapped[dict | None] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(20), nullable=False, default=UserStatus.ACTIVE.value, index=True)
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
# 关系
company = relationship("Company", back_populates="users")
def __repr__(self) -> str:
return f"<User(id={self.id}, email='{self.email}', role='{self.role}')>"
def has_permission(self, permission: str) -> bool:
"""检查用户是否有指定权限"""
if not self.permissions:
return False
return permission in self.permissions.get("permissions", [])
+45
View File
@@ -0,0 +1,45 @@
from datetime import datetime
from typing import Any, Optional
from pydantic import BaseModel, ConfigDict, Field
class AuditLogCreate(BaseModel):
"""创建审计日志的 Schema"""
company_id: int = Field(..., description="企业 ID")
user_id: Optional[int] = Field(None, description="用户 ID")
action: str = Field(..., max_length=50, description="操作类型")
resource_type: str = Field(..., max_length=100, description="资源类型")
resource_id: Optional[str] = Field(None, max_length=200, description="资源 ID")
details: Optional[dict[str, Any]] = Field(None, description="操作详情")
ip_address: Optional[str] = Field(None, max_length=50, description="IP 地址")
user_agent: Optional[str] = Field(None, description="User-Agent")
class AuditLogResponse(BaseModel):
"""审计日志响应 Schema"""
model_config = ConfigDict(from_attributes=True)
id: int
company_id: int
user_id: Optional[int]
action: str
resource_type: str
resource_id: Optional[str]
details: Optional[dict[str, Any]]
ip_address: Optional[str]
user_agent: Optional[str]
created_at: datetime
class AuditLogQuery(BaseModel):
"""审计日志查询参数"""
company_id: Optional[int] = None
user_id: Optional[int] = None
action: Optional[str] = None
resource_type: Optional[str] = None
resource_id: Optional[str] = None
start_date: Optional[datetime] = None
end_date: Optional[datetime] = None
skip: int = Field(default=0, ge=0)
limit: int = Field(default=50, ge=1, le=1000)
+38
View File
@@ -0,0 +1,38 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, ConfigDict, Field
class CompanyBase(BaseModel):
"""Company 基础 Schema"""
name: str = Field(..., min_length=1, max_length=200, description="企业名称")
plan: str = Field(default="免费版", description="套餐类型")
data_retention_months: int = Field(default=12, ge=1, le=120, description="数据保留月数")
max_users: int = Field(default=5, ge=1, description="最大用户数")
class CompanyCreate(CompanyBase):
"""创建 Company 的 Schema"""
pass
class CompanyUpdate(BaseModel):
"""更新 Company 的 Schema"""
name: Optional[str] = Field(None, min_length=1, max_length=200)
plan: Optional[str] = None
data_retention_months: Optional[int] = Field(None, ge=1, le=120)
status: Optional[str] = None
max_users: Optional[int] = Field(None, ge=1)
is_trial: Optional[bool] = None
class CompanyResponse(CompanyBase):
"""Company 响应 Schema"""
model_config = ConfigDict(from_attributes=True)
id: int
status: str
is_trial: bool
created_at: datetime
updated_at: datetime
+147
View File
@@ -0,0 +1,147 @@
"""
字段映射相关 Pydantic Schema
"""
from datetime import datetime
from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field
# ===== 字段映射 Schema =====
class FieldMappingBase(BaseModel):
"""字段映射基础 schema"""
source_field: str = Field(..., description="源字段名")
standard_field: str = Field(..., description="标准字段名")
confidence: float = Field(..., ge=0, le=1, description="置信度 0-1")
reasoning: Optional[str] = Field(None, description="AI 判断依据")
sample_values: Optional[List[Any]] = Field(None, description="样例值")
is_skipped: bool = Field(False, description="是否跳过")
class FieldMappingCreate(FieldMappingBase):
"""创建字段映射"""
file_id: int = Field(..., description="文件ID")
class FieldMappingUpdate(BaseModel):
"""更新字段映射"""
standard_field: Optional[str] = Field(None, description="标准字段名")
is_skipped: Optional[bool] = Field(None, description="是否跳过")
class FieldMappingResponse(FieldMappingBase):
"""字段映射响应"""
id: int
company_id: int
file_id: int
confirmed: bool
confirmed_by: Optional[int] = None
confirmed_at: Optional[datetime] = None
class Config:
from_attributes = True
class FieldMappingWithFileResponse(FieldMappingResponse):
"""带文件信息的字段映射响应"""
file_type: Optional[str] = None
file_name: Optional[str] = None
# ===== 批量操作 Schema =====
class ConfirmMappingsRequest(BaseModel):
"""批量确认映射请求"""
mapping_ids: List[int] = Field(..., description="要确认的映射ID列表")
class ConfirmMappingsResponse(BaseModel):
"""批量确认映射响应"""
confirmed_count: int = Field(..., description="确认数量")
mappings: List[FieldMappingResponse]
class SaveAsRuleRequest(BaseModel):
"""保存为规则请求"""
mapping_id: int = Field(..., description="映射ID")
class SaveAsRuleResponse(BaseModel):
"""保存为规则响应"""
rule_id: int
source_field: str
target_field: str
message: str
# ===== 规则 Schema =====
class CompanyRuleBase(BaseModel):
"""企业规则基础 schema"""
rule_type: str = Field(..., description="规则类型")
match_condition: Dict[str, Any] = Field(..., description="匹配条件")
target_value: str = Field(..., description="目标值")
priority: int = Field(0, description="优先级")
description: Optional[str] = Field(None, description="规则描述")
class CompanyRuleResponse(CompanyRuleBase):
"""企业规则响应"""
id: int
company_id: int
status: str
match_count: int
last_used_at: Optional[datetime] = None
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class UpdateRuleStatusRequest(BaseModel):
"""更新规则状态请求"""
status: str = Field(..., description="状态 ACTIVE/INACTIVE")
class RecognizeFieldsRequest(BaseModel):
"""识别字段请求"""
file_id: int = Field(..., description="文件ID")
file_type: str = Field("工资表", description="文件类型")
class RecognizeFieldsResponse(BaseModel):
"""识别字段响应"""
file_id: int
mappings: List[FieldMappingResponse]
high_confidence_count: int = Field(..., description="高置信度数量")
medium_confidence_count: int = Field(..., description="中等置信度数量")
low_confidence_count: int = Field(..., description="低置信度数量")
needs_review: bool = Field(..., description="是否需要人工确认")
# ===== 文件映射概览 =====
class FileMappingSummary(BaseModel):
"""文件映射概览"""
file_id: int
file_type: str
file_name: str
total_fields: int
confirmed_fields: int
high_confidence: int
medium_confidence: int
low_confidence: int
mappings: List[FieldMappingResponse]
class TaskMappingOverview(BaseModel):
"""任务映射概览"""
task_id: int
total_files: int
total_fields: int
confirmed_fields: int
needs_review: bool
files: List[FileMappingSummary]
+56
View File
@@ -0,0 +1,56 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, ConfigDict, EmailStr, Field
class UserBase(BaseModel):
"""User 基础 Schema"""
email: EmailStr = Field(..., description="邮箱")
full_name: str = Field(..., min_length=1, max_length=100, description="姓名")
role: str = Field(default="会计", description="角色")
class UserCreate(UserBase):
"""创建用户的 Schema"""
password: str = Field(..., min_length=6, max_length=50, description="密码")
company_id: int = Field(..., description="企业ID")
class UserUpdate(BaseModel):
"""更新用户的 Schema"""
full_name: Optional[str] = Field(None, min_length=1, max_length=100)
role: Optional[str] = None
permissions: Optional[dict] = None
status: Optional[str] = None
class UserResponse(UserBase):
"""用户响应 Schema"""
model_config = ConfigDict(from_attributes=True)
id: int
company_id: int
status: str
permissions: Optional[dict]
last_login_at: Optional[datetime]
created_at: datetime
updated_at: datetime
class UserLogin(BaseModel):
"""用户登录 Schema"""
email: EmailStr = Field(..., description="邮箱")
password: str = Field(..., description="密码")
class Token(BaseModel):
"""Token Schema"""
access_token: str
token_type: str = "bearer"
class TokenData(BaseModel):
"""Token 数据 Schema"""
user_id: Optional[int] = None
email: Optional[str] = None
+225
View File
@@ -0,0 +1,225 @@
"""
AI 字段识别服务
使用 AI 自动识别 Excel 表头对应的标准字段
"""
import json
import re
from typing import List, Dict, Optional, Tuple
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.models.standard_field import StandardField, FIELD_TYPES
class AIFieldRecognizer:
"""AI 字段识别器"""
# 字段关键词映射(用于规则匹配兜底)
FIELD_KEYWORDS = {
StandardField.EMPLOYEE_NAME.value: ["姓名", "名字", "员工名", "name", "员工姓名"],
StandardField.EMPLOYEE_ID.value: ["工号", "员工号", "编号", "id", "员工编号"],
StandardField.DEPARTMENT.value: ["部门", "科室", "事业部", "department", "所属部门"],
StandardField.POSITION.value: ["岗位", "职位", "职务", "position", "job"],
StandardField.BASE_SALARY.value: ["基本工资", "岗位工资", "底薪", "base", "基本薪资"],
StandardField.BONUS.value: ["奖金", "绩效", "bonus", "绩效工资", "奖励"],
StandardField.ALLOWANCE.value: ["补贴", "津贴", "allowance", "餐补", "交通补贴"],
StandardField.OVERTIME_PAY.value: ["加班费", "加班工资", "overtime"],
StandardField.DEDUCTION.value: ["扣款", "扣除", "deduction", "罚款", "迟到扣款"],
StandardField.GROSS_SALARY.value: ["应发工资", "应发", "税前工资", "gross", "工资总额"],
StandardField.NET_SALARY.value: ["实发工资", "实发", "净工资", "net", "实发金额", "银行实发"],
StandardField.BANK_CARD.value: ["银行账号", "卡号", "账号", "bank", "银行卡"],
StandardField.ID_CARD.value: ["身份证", "证件号", "id_card", "身份证号"],
StandardField.SOCIAL_SECURITY_BASE.value: ["社保基数", "缴费基数", "基数"],
StandardField.PENSION_INSURANCE.value: ["养老保险", "养老", "pension", "养保"],
StandardField.MEDICAL_INSURANCE.value: ["医疗保险", "医保", "medical"],
StandardField.UNEMPLOYMENT_INSURANCE.value: ["失业保险", "失业", "unemployment"],
StandardField.HOUSING_FUND.value: ["公积金", "住房基金", "housing", "住房公金"],
StandardField.PENSION_INSURANCE_COMPANY.value: ["养老保险(公司)", "养老保险公司", "养保公司"],
StandardField.MEDICAL_INSURANCE_COMPANY.value: ["医疗保险(公司)", "医疗公司"],
StandardField.UNEMPLOYMENT_INSURANCE_COMPANY.value: ["失业保险(公司)", "失业公司"],
StandardField.HOUSING_FUND_COMPANY.value: ["公积金(公司)", "公积金公司"],
StandardField.SOCIAL_SECURITY_TOTAL.value: ["社保合计", "社保总计", "社保总额"],
StandardField.TAXABLE_INCOME.value: ["应税收入", "应税工资", "税前收入", "taxable"],
StandardField.PRE_TAX_DEDUCTION.value: ["税前扣除", "三险一金", "个人缴费"],
StandardField.TAX_FREE_INCOME.value: ["免税收入", "免税", "tax_free"],
StandardField.TAX_EXEMPT_INCOME.value: ["税前减免", "减免"],
StandardField.QUICK_DEDUCTION.value: ["速算扣除", "速算"],
StandardField.TAX_AMOUNT.value: ["应缴个税", "个人所得税", "个税", "tax"],
StandardField.TAX_PAID.value: ["已缴个税", "已扣税", "已缴税"],
StandardField.AFTER_TAX_INCOME.value: ["税后收入", "税后工资", "after_tax"],
}
def __init__(self, db: AsyncSession, company_id: int):
self.db = db
self.company_id = company_id
async def recognize_fields(
self,
headers: List[str],
sample_data: List[Dict],
file_type: str = "工资表"
) -> List[Dict]:
"""
识别字段映射
Args:
headers: 表头列表
sample_data: 样例数据(前10行)
file_type: 文件类型
Returns:
字段映射列表
"""
mappings = []
for header in headers:
# 获取该列的样例值
samples = [row.get(header) for row in sample_data if row.get(header)]
sample_values = samples[:5] if samples else []
# 先尝试规则匹配
matched_field, confidence, reasoning = self._rule_match(header, sample_values)
if matched_field:
mappings.append({
"source_field": header,
"standard_field": matched_field,
"confidence": confidence,
"reasoning": reasoning,
"sample_values": sample_values,
})
else:
# 无法匹配
mappings.append({
"source_field": header,
"standard_field": "",
"confidence": 0.0,
"reasoning": "无法识别字段类型",
"sample_values": sample_values,
})
return mappings
def _rule_match(
self,
header: str,
sample_values: List
) -> Tuple[Optional[str], float, str]:
"""
规则匹配
Args:
header: 字段名
sample_values: 样例值
Returns:
(标准字段, 置信度, 判断依据)
"""
header_lower = header.lower().strip()
header_normalized = header.strip()
best_match = None
best_confidence = 0.0
best_reasoning = ""
for standard_field, keywords in self.FIELD_KEYWORDS.items():
for keyword in keywords:
keyword_lower = keyword.lower()
# 精确匹配(完全相同)
if header_normalized == keyword or header_lower == keyword_lower:
return (
standard_field,
1.0,
f"字段名完全匹配:'{keyword}'"
)
# 包含匹配
if keyword_lower in header_lower or header_lower in keyword_lower:
confidence = 0.9
reasoning = f"字段名包含关键词:'{keyword}'"
# 数值字段检查样例值
field_type = FIELD_TYPES.get(standard_field, "string")
if field_type == "number" and sample_values:
if self._validate_numeric_samples(sample_values):
confidence = 0.95
reasoning += ",样例值验证为数值类型"
if confidence > best_confidence:
best_match = standard_field
best_confidence = confidence
best_reasoning = reasoning
# 模糊匹配(编辑距离)
distance = self._levenshtein_distance(header_lower, keyword_lower)
max_len = max(len(header_lower), len(keyword_lower))
similarity = 1 - (distance / max_len) if max_len > 0 else 0
if similarity > 0.7 and similarity > best_confidence:
best_match = standard_field
best_confidence = similarity * 0.8 # 模糊匹配降权
best_reasoning = f"字段名相似度:{similarity:.0%},参考词:'{keyword}'"
return best_match, best_confidence, best_reasoning
def _validate_numeric_samples(self, samples: List) -> bool:
"""验证样例值是否为数值"""
numeric_count = 0
for sample in samples[:5]:
if sample is None:
continue
sample_str = str(sample).strip()
# 移除常见的货币符号和逗号
sample_str = sample_str.replace("¥", "").replace(",", "").replace("", "")
try:
float(sample_str)
numeric_count += 1
except ValueError:
pass
return numeric_count >= len(samples) * 0.8
@staticmethod
def _levenshtein_distance(s1: str, s2: str) -> int:
"""计算编辑距离"""
if len(s1) < len(s2):
return AIFieldRecognizer._levenshtein_distance(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
async def recognize_fields_with_ai(
db: AsyncSession,
company_id: int,
headers: List[str],
sample_data: List[Dict],
file_type: str = "工资表"
) -> List[Dict]:
"""
使用 AI 识别字段(带重试的版本)
优先使用 OpenAI API,失败时降级到规则匹配
"""
recognizer = AIFieldRecognizer(db, company_id)
# 优先使用规则匹配(当前实现)
# TODO: 后续集成 OpenAI API
mappings = await recognizer.recognize_fields(headers, sample_data, file_type)
return mappings
+180
View File
@@ -0,0 +1,180 @@
from datetime import datetime
from functools import wraps
from typing import Any, Callable, Optional
from fastapi import Request
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.audit_log import AuditAction, AuditLog
from app.schemas.audit_log import AuditLogCreate, AuditLogQuery
class AuditService:
"""审计日志服务"""
@staticmethod
async def log_action(
db: AsyncSession,
company_id: int,
action: str,
resource_type: str,
user_id: Optional[int] = None,
resource_id: Optional[str] = None,
details: Optional[dict[str, Any]] = None,
ip_address: Optional[str] = None,
user_agent: Optional[str] = None,
) -> AuditLog:
"""
记录审计日志
Args:
db: 数据库会话
company_id: 企业 ID
action: 操作类型
resource_type: 资源类型
user_id: 用户 ID
resource_id: 资源 ID
details: 操作详情
ip_address: IP 地址
user_agent: User-Agent
Returns:
创建的审计日志对象
"""
log_data = AuditLogCreate(
company_id=company_id,
user_id=user_id,
action=action,
resource_type=resource_type,
resource_id=resource_id,
details=details,
ip_address=ip_address,
user_agent=user_agent,
)
audit_log = AuditLog(**log_data.model_dump())
db.add(audit_log)
await db.commit()
await db.refresh(audit_log)
return audit_log
@staticmethod
async def get_logs(
db: AsyncSession,
query_params: AuditLogQuery,
) -> list[AuditLog]:
"""
查询审计日志
Args:
db: 数据库会话
query_params: 查询参数
Returns:
审计日志列表
"""
stmt = select(AuditLog)
# 添加过滤条件
if query_params.company_id:
stmt = stmt.where(AuditLog.company_id == query_params.company_id)
if query_params.user_id:
stmt = stmt.where(AuditLog.user_id == query_params.user_id)
if query_params.action:
stmt = stmt.where(AuditLog.action == query_params.action)
if query_params.resource_type:
stmt = stmt.where(AuditLog.resource_type == query_params.resource_type)
if query_params.resource_id:
stmt = stmt.where(AuditLog.resource_id == query_params.resource_id)
if query_params.start_date:
stmt = stmt.where(AuditLog.created_at >= query_params.start_date)
if query_params.end_date:
stmt = stmt.where(AuditLog.created_at <= query_params.end_date)
# 排序和分页
stmt = stmt.order_by(AuditLog.created_at.desc())
stmt = stmt.offset(query_params.skip).limit(query_params.limit)
result = await db.execute(stmt)
return list(result.scalars().all())
@staticmethod
async def log_from_request(
db: AsyncSession,
request: Request,
company_id: int,
action: str,
resource_type: str,
user_id: Optional[int] = None,
resource_id: Optional[str] = None,
details: Optional[dict[str, Any]] = None,
) -> AuditLog:
"""
从 Request 对象中提取信息并记录审计日志
Args:
db: 数据库会话
request: FastAPI 请求对象
company_id: 企业 ID
action: 操作类型
resource_type: 资源类型
user_id: 用户 ID
resource_id: 资源 ID
details: 操作详情
Returns:
创建的审计日志对象
"""
# 提取 IP 地址
ip_address = request.client.host if request.client else None
# 提取 User-Agent
user_agent = request.headers.get("user-agent")
return await AuditService.log_action(
db=db,
company_id=company_id,
action=action,
resource_type=resource_type,
user_id=user_id,
resource_id=resource_id,
details=details,
ip_address=ip_address,
user_agent=user_agent,
)
# 单例实例
audit_service = AuditService()
def audit_log(
action: str,
resource_type: str,
get_resource_id: Optional[Callable] = None,
):
"""
审计日志装饰器
Args:
action: 操作类型
resource_type: 资源类型
get_resource_id: 从函数返回值中获取 resource_id 的函数
Example:
@audit_log(action=AuditAction.CREATE, resource_type="company")
async def create_company(...):
...
"""
def decorator(func: Callable):
@wraps(func)
async def wrapper(*args, **kwargs):
result = await func(*args, **kwargs)
# TODO: 在实现认证后,从上下文获取 company_id 和 user_id
# 目前暂时跳过实际记录
return result
return wrapper
return decorator
+158
View File
@@ -0,0 +1,158 @@
from datetime import datetime
from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.security import create_access_token, hash_password, verify_password, decode_access_token
from app.models.user import User, UserStatus
from app.schemas.user import UserCreate, UserLogin, Token
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
class AuthService:
"""认证服务"""
@staticmethod
async def register_user(
db: AsyncSession,
user_data: UserCreate,
) -> User:
"""
注册用户
Args:
db: 数据库会话
user_data: 用户数据
Returns:
创建的用户对象
"""
# 检查邮箱是否已存在
result = await db.execute(select(User).where(User.email == user_data.email))
if result.scalar_one_or_none():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="邮箱已被注册"
)
# 创建用户
hashed_password = hash_password(user_data.password)
user = User(
company_id=user_data.company_id,
email=user_data.email,
hashed_password=hashed_password,
full_name=user_data.full_name,
role=user_data.role,
)
db.add(user)
await db.commit()
await db.refresh(user)
return user
@staticmethod
async def authenticate_user(
db: AsyncSession,
login_data: UserLogin,
) -> tuple[User, str]:
"""
认证用户并生成 Token
Args:
db: 数据库会话
login_data: 登录数据
Returns:
用户对象和访问令牌
Raises:
HTTPException: 认证失败
"""
# 查找用户
result = await db.execute(select(User).where(User.email == login_data.email))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="邮箱或密码错误"
)
# 验证密码
if not verify_password(login_data.password, user.hashed_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="邮箱或密码错误"
)
# 检查用户状态
if user.status != UserStatus.ACTIVE.value:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"用户已被{user.status}"
)
# 更新最后登录时间
user.last_login_at = datetime.utcnow()
await db.commit()
await db.refresh(user)
# 生成 Token
access_token = create_access_token(data={"sub": str(user.id), "email": user.email})
return user, access_token
@staticmethod
async def get_current_user(
token: str = Depends(oauth2_scheme),
db: AsyncSession = Depends(get_db),
) -> User:
"""
获取当前用户
Args:
token: JWT token
db: 数据库会话
Returns:
当前用户对象
Raises:
HTTPException: Token 无效或用户不存在
"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="无法验证凭据",
headers={"WWW-Authenticate": "Bearer"},
)
payload = decode_access_token(token)
if not payload:
raise credentials_exception
user_id: str = payload.get("sub")
if not user_id:
raise credentials_exception
result = await db.execute(select(User).where(User.id == int(user_id)))
user = result.scalar_one_or_none()
if not user:
raise credentials_exception
if user.status != UserStatus.ACTIVE.value:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="用户已被禁用"
)
return user
# 单例实例
auth_service = AuthService()
+113
View File
@@ -0,0 +1,113 @@
from typing import Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.company import Company, CompanyStatus
from app.schemas.company import CompanyCreate, CompanyUpdate
class CompanyService:
"""企业服务"""
@staticmethod
async def create_company(
db: AsyncSession,
company_data: CompanyCreate,
) -> Company:
"""
创建企业
Args:
db: 数据库会话
company_data: 企业数据
Returns:
创建的企业对象
"""
company = Company(**company_data.model_dump())
db.add(company)
await db.commit()
await db.refresh(company)
return company
@staticmethod
async def get_company(
db: AsyncSession,
company_id: int,
) -> Optional[Company]:
"""
获取企业信息
Args:
db: 数据库会话
company_id: 企业 ID
Returns:
企业对象,不存在则返回 None
"""
result = await db.execute(
select(Company).where(
Company.id == company_id,
Company.status != CompanyStatus.DELETED.value,
)
)
return result.scalar_one_or_none()
@staticmethod
async def update_company(
db: AsyncSession,
company_id: int,
company_data: CompanyUpdate,
) -> Optional[Company]:
"""
更新企业信息
Args:
db: 数据库会话
company_id: 企业 ID
company_data: 更新数据
Returns:
更新后的企业对象,不存在则返回 None
"""
company = await CompanyService.get_company(db, company_id)
if not company:
return None
update_data = company_data.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(company, field, value)
await db.commit()
await db.refresh(company)
return company
@staticmethod
async def list_companies(
db: AsyncSession,
skip: int = 0,
limit: int = 100,
) -> list[Company]:
"""
获取企业列表
Args:
db: 数据库会话
skip: 跳过数量
limit: 返回数量
Returns:
企业列表
"""
result = await db.execute(
select(Company)
.where(Company.status != CompanyStatus.DELETED.value)
.offset(skip)
.limit(limit)
)
return list(result.scalars().all())
# 单例实例
company_service = CompanyService()
+399
View File
@@ -0,0 +1,399 @@
"""
数据清洗服务
清洗和标准化工资表数据,为对账做准备
"""
import re
from datetime import datetime
from decimal import Decimal, InvalidOperation
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from dataclasses import dataclass
@dataclass
class CleaningResult:
"""清洗结果"""
original_value: Any
cleaned_value: Any
is_valid: bool
error_message: Optional[str] = None
@dataclass
class ValidationRule:
"""验证规则"""
name: str
validate: Callable[[Any], bool]
error_message: str
class DataCleaner:
"""
数据清洗器
用于清洗和验证工资表数据
"""
def __init__(self):
self.validation_rules: Dict[str, List[ValidationRule]] = {}
self._init_default_rules()
def _init_default_rules(self):
"""初始化默认验证规则"""
# 姓名验证:2-20个中文字符或英文字母
self.add_rule(
"employee_name",
ValidationRule(
name="name_length",
validate=lambda v: bool(v) and 1 < len(str(v).strip()) <= 50,
error_message="姓名长度应在2-50个字符之间"
)
)
# 工号验证:数字或字母组合
self.add_rule(
"employee_id",
ValidationRule(
name="id_format",
validate=lambda v: bool(v) and bool(re.match(r'^[\w\-]+$', str(v))),
error_message="工号格式不正确"
)
)
# 金额验证:正数且在合理范围内
self.add_rule(
"amount",
ValidationRule(
name="amount_positive",
validate=lambda v: self._parse_number(v) is not None and self._parse_number(v) >= 0,
error_message="金额必须为非负数"
)
)
# 身份证号验证
self.add_rule(
"id_card",
ValidationRule(
name="id_card_length",
validate=lambda v: bool(v) and len(str(v).strip()) in [15, 18],
error_message="身份证号长度应为15或18位"
)
)
# 银行账号验证
self.add_rule(
"bank_card",
ValidationRule(
name="bank_card_digits",
validate=lambda v: bool(v) and str(v).isdigit() and len(str(v)) >= 10,
error_message="银行账号应为至少10位数字"
)
)
def add_rule(self, field_type: str, rule: ValidationRule):
"""添加验证规则"""
if field_type not in self.validation_rules:
self.validation_rules[field_type] = []
self.validation_rules[field_type].append(rule)
def _parse_number(self, value: Any) -> Optional[Decimal]:
"""解析数字"""
if value is None:
return None
if isinstance(value, (int, float, Decimal)):
return Decimal(str(value))
if isinstance(value, str):
# 移除常见的货币符号、逗号和空格
cleaned = value.strip()
cleaned = re.sub(r'[¥$,\s]', '', cleaned)
# 处理负数
is_negative = cleaned.startswith('-')
cleaned = cleaned.lstrip('-')
# 检查是否包含有效数字
if not cleaned or not re.match(r'^\d+(\.\d+)?$', cleaned):
return None
try:
result = Decimal(cleaned)
return -result if is_negative else result
except InvalidOperation:
return None
return None
def _parse_date(self, value: Any) -> Optional[datetime]:
"""解析日期"""
if value is None:
return None
if isinstance(value, datetime):
return value
if isinstance(value, str):
# 尝试多种日期格式
formats = [
'%Y-%m-%d',
'%Y/%m/%d',
'%Y年%m月%d',
'%Y%m%d',
'%Y-%m-%d %H:%M:%S',
]
for fmt in formats:
try:
return datetime.strptime(value.strip(), fmt)
except ValueError:
continue
return None
def clean_string(self, value: Any, strip: bool = True) -> str:
"""清洗字符串"""
if value is None:
return ""
result = str(value)
if strip:
result = result.strip()
return result
def clean_amount(self, value: Any) -> CleaningResult:
"""清洗金额字段"""
original = value
parsed = self._parse_number(value)
if parsed is None:
return CleaningResult(
original_value=original,
cleaned_value=None,
is_valid=False,
error_message="无法解析为数字"
)
return CleaningResult(
original_value=original,
cleaned_value=float(parsed),
is_valid=True
)
def clean_employee_name(self, value: Any) -> CleaningResult:
"""清洗员工姓名"""
cleaned = self.clean_string(value)
if not cleaned:
return CleaningResult(
original_value=value,
cleaned_value=None,
is_valid=False,
error_message="姓名为空"
)
# 移除多余空格
cleaned = re.sub(r'\s+', ' ', cleaned)
return CleaningResult(
original_value=value,
cleaned_value=cleaned,
is_valid=True
)
def clean_employee_id(self, value: Any) -> CleaningResult:
"""清洗工号"""
cleaned = self.clean_string(value)
if not cleaned:
return CleaningResult(
original_value=value,
cleaned_value=None,
is_valid=False,
error_message="工号为空"
)
return CleaningResult(
original_value=value,
cleaned_value=cleaned.upper(), # 统一大写
is_valid=True
)
def clean_bank_card(self, value: Any) -> CleaningResult:
"""清洗银行账号"""
original = value
cleaned = self.clean_string(value)
# 只保留数字
cleaned = re.sub(r'\D', '', cleaned)
if len(cleaned) < 10:
return CleaningResult(
original_value=original,
cleaned_value=None,
is_valid=False,
error_message="银行账号长度不足"
)
return CleaningResult(
original_value=original,
cleaned_value=cleaned,
is_valid=True
)
def clean_id_card(self, value: Any) -> CleaningResult:
"""清洗身份证号"""
original = value
cleaned = self.clean_string(value)
# 统一大写
cleaned = cleaned.upper()
# 只保留数字和X
cleaned = re.sub(r'[^0-9X]', '', cleaned)
if len(cleaned) not in [15, 18]:
return CleaningResult(
original_value=original,
cleaned_value=None,
is_valid=False,
error_message="身份证号长度应为15或18位"
)
return CleaningResult(
original_value=original,
cleaned_value=cleaned,
is_valid=True
)
def validate_field(self, field_type: str, value: Any) -> Tuple[bool, Optional[str]]:
"""
验证字段
Returns:
(是否通过, 错误信息)
"""
rules = self.validation_rules.get(field_type, [])
for rule in rules:
if not rule.validate(value):
return False, rule.error_message
return True, None
def clean_row(self, row: Dict[str, Any], field_mappings: Dict[str, str]) -> Dict[str, Any]:
"""
清洗一行数据
Args:
row: 原始行数据 {源字段名: 值}
field_mappings: 字段映射 {标准字段名: 源字段名}
Returns:
清洗后的数据 {标准字段名: 清洗后的值}
"""
cleaned = {}
errors = {}
# 反转映射:标准字段 -> 源字段
standard_to_source = {v: k for k, v in field_mappings.items()}
for standard_field, source_field in standard_to_source.items():
raw_value = row.get(source_field)
# 根据字段类型选择清洗方法
if standard_field in ["员工姓名", "姓名"]:
result = self.clean_employee_name(raw_value)
elif standard_field in ["工号", "员工号"]:
result = self.clean_employee_id(raw_value)
elif standard_field in ["银行账号", "卡号"]:
result = self.clean_bank_card(raw_value)
elif standard_field in ["身份证号", "证件号"]:
result = self.clean_id_card(raw_value)
elif standard_field in ["基本工资", "奖金", "补贴", "加班费", "扣款",
"应发工资", "实发工资", "社保基数",
"养老保险", "医疗保险", "失业保险", "公积金",
"个税", "应税收入", "税后收入"]:
result = self.clean_amount(raw_value)
else:
result = CleaningResult(
original_value=raw_value,
cleaned_value=self.clean_string(raw_value),
is_valid=bool(raw_value)
)
cleaned[standard_field] = result.cleaned_value
if not result.is_valid:
errors[standard_field] = result.error_message
return cleaned
def batch_clean(
self,
data: List[Dict[str, Any]],
field_mappings: Dict[str, str]
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""
批量清洗数据
Returns:
(有效数据, 无效数据)
"""
valid_data = []
invalid_data = []
for row in data:
cleaned_row = self.clean_row(row, field_mappings)
# 检查是否有无效字段
has_invalid = any(v is None for v in cleaned_row.values())
if has_invalid:
invalid_data.append({
"original": row,
"cleaned": cleaned_row
})
else:
valid_data.append(cleaned_row)
return valid_data, invalid_data
# 单例实例
_cleaner_instance: Optional[DataCleaner] = None
def get_cleaner() -> DataCleaner:
"""获取数据清洗器单例"""
global _cleaner_instance
if _cleaner_instance is None:
_cleaner_instance = DataCleaner()
return _cleaner_instance
async def clean_salary_data(
data: List[Dict[str, Any]],
field_mappings: Dict[str, str]
) -> Dict[str, Any]:
"""
清洗工资数据
Args:
data: 原始工资数据
field_mappings: 字段映射
Returns:
清洗结果
"""
cleaner = get_cleaner()
valid_data, invalid_data = cleaner.batch_clean(data, field_mappings)
return {
"total_count": len(data),
"valid_count": len(valid_data),
"invalid_count": len(invalid_data),
"valid_data": valid_data,
"invalid_data": invalid_data,
"cleaning_time": datetime.utcnow().isoformat(),
}
+308
View File
@@ -0,0 +1,308 @@
"""
异常处理服务
处理异常的查询、更新、批量操作等
"""
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import select, update, func, and_, or_
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.exception_item import ExceptionItem, ExceptionStatus
from app.models.reconciliation_task import ReconciliationTask
class ExceptionService:
"""异常处理服务"""
def __init__(self, db: AsyncSession):
self.db = db
async def get_exceptions(
self,
task_id: Optional[int] = None,
company_id: Optional[int] = None,
status: Optional[str] = None,
severity: Optional[str] = None,
exception_type: Optional[str] = None,
page: int = 1,
page_size: int = 20,
) -> Tuple[List[ExceptionItem], int]:
"""
查询异常列表
Args:
task_id: 任务ID
company_id: 企业ID
status: 状态
severity: 严重程度
exception_type: 异常类型
page: 页码
page_size: 每页数量
Returns:
(异常列表, 总数)
"""
from sqlalchemy.orm import selectinload
query = select(ExceptionItem).options(selectinload(ExceptionItem.handler))
count_query = select(func.count(ExceptionItem.id))
# 条件
filters = []
if task_id:
filters.append(ExceptionItem.task_id == task_id)
if company_id:
filters.append(ExceptionItem.company_id == company_id)
if status:
filters.append(ExceptionItem.status == status)
if severity:
filters.append(ExceptionItem.severity == severity)
if exception_type:
filters.append(ExceptionItem.exception_type == exception_type)
if filters:
query = query.where(and_(*filters))
count_query = count_query.where(and_(*filters))
# 总数
total_result = await self.db.execute(count_query)
total = total_result.scalar() or 0
# 分页
query = query.order_by(
ExceptionItem.created_at.desc()
).offset((page - 1) * page_size).limit(page_size)
result = await self.db.execute(query)
exceptions = result.scalars().all()
return list(exceptions), total
async def get_exception(self, exception_id: int) -> Optional[ExceptionItem]:
"""获取单个异常"""
return await self.db.get(ExceptionItem, exception_id)
async def update_exception(
self,
exception_id: int,
status: Optional[str] = None,
handling_note: Optional[str] = None,
handled_by: Optional[int] = None,
) -> Optional[ExceptionItem]:
"""
更新异常
Args:
exception_id: 异常ID
status: 新状态
handling_note: 处理备注
handled_by: 处理人ID
Returns:
更新后的异常
"""
exception = await self.db.get(ExceptionItem, exception_id)
if not exception:
return None
if status:
exception.status = status
if handling_note:
exception.handling_note = handling_note
if handled_by:
exception.handled_by = handled_by
exception.updated_at = datetime.utcnow()
await self.db.commit()
await self.db.refresh(exception)
return exception
async def batch_update_status(
self,
exception_ids: List[int],
status: str,
) -> int:
"""
批量更新状态
Args:
exception_ids: 异常ID列表
status: 新状态
Returns:
更新的数量
"""
if not exception_ids:
return 0
stmt = (
update(ExceptionItem)
.where(ExceptionItem.id.in_(exception_ids))
.values(
status=status,
updated_at=datetime.utcnow(),
)
)
result = await self.db.execute(stmt)
await self.db.commit()
return result.rowcount or 0
async def batch_resolve(
self,
exception_ids: List[int],
handling_note: str,
handled_by: Optional[int] = None,
) -> int:
"""
批量处理异常
Args:
exception_ids: 异常ID列表
handling_note: 处理备注
handled_by: 处理人ID
Returns:
处理的数量
"""
if not exception_ids:
return 0
update_data = {
"status": ExceptionStatus.RESOLVED.value,
"handling_note": handling_note,
"updated_at": datetime.utcnow(),
}
if handled_by:
update_data["handled_by"] = handled_by
stmt = (
update(ExceptionItem)
.where(ExceptionItem.id.in_(exception_ids))
.values(**update_data)
)
result = await self.db.execute(stmt)
await self.db.commit()
return result.rowcount or 0
async def get_exception_summary(
self,
task_id: Optional[int] = None,
company_id: Optional[int] = None,
) -> Dict[str, Any]:
"""
获取异常汇总统计
Args:
task_id: 任务ID
company_id: 企业ID
Returns:
汇总统计
"""
# 按状态统计
status_query = select(
ExceptionItem.status,
func.count(ExceptionItem.id).label("count")
).group_by(ExceptionItem.status)
# 按严重程度统计
severity_query = select(
ExceptionItem.severity,
func.count(ExceptionItem.id).label("count")
).group_by(ExceptionItem.severity)
# 按类型统计
type_query = select(
ExceptionItem.exception_type,
func.count(ExceptionItem.id).label("count")
).group_by(ExceptionItem.exception_type)
# 条件
filters = []
if task_id:
filters.append(ExceptionItem.task_id == task_id)
if company_id:
filters.append(ExceptionItem.company_id == company_id)
if filters:
status_query = status_query.where(and_(*filters))
severity_query = severity_query.where(and_(*filters))
type_query = type_query.where(and_(*filters))
# 执行查询
status_result = await self.db.execute(status_query)
severity_result = await self.db.execute(severity_query)
type_result = await self.db.execute(type_query)
return {
"by_status": {
row.status: row.count for row in status_result.all()
},
"by_severity": {
row.severity: row.count for row in severity_result.all()
},
"by_type": {
row.exception_type: row.count for row in type_result.all()
},
}
async def get_pending_exceptions(
self,
company_id: int,
limit: int = 10,
) -> List[ExceptionItem]:
"""获取待处理的异常"""
query = (
select(ExceptionItem)
.where(
and_(
ExceptionItem.company_id == company_id,
ExceptionItem.status == ExceptionStatus.PENDING.value,
)
)
.order_by(ExceptionItem.created_at.desc())
.limit(limit)
)
result = await self.db.execute(query)
return list(result.scalars().all())
# 便捷函数
async def get_exceptions(
db: AsyncSession,
**kwargs,
) -> Tuple[List[ExceptionItem], int]:
"""查询异常列表"""
service = ExceptionService(db)
return await service.get_exceptions(**kwargs)
async def update_exception(
db: AsyncSession,
exception_id: int,
**kwargs,
) -> Optional[ExceptionItem]:
"""更新异常"""
service = ExceptionService(db)
return await service.update_exception(exception_id, **kwargs)
async def batch_resolve_exceptions(
db: AsyncSession,
exception_ids: List[int],
handling_note: str,
handled_by: Optional[int] = None,
) -> int:
"""批量处理异常"""
service = ExceptionService(db)
return await service.batch_resolve(exception_ids, handling_note, handled_by)
+353
View File
@@ -0,0 +1,353 @@
"""
导出服务
导出对账结果为 Excel 和金蝶凭证格式
"""
import io
from datetime import datetime
from typing import Any, Dict, List, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.reconciliation_task import ReconciliationTask
from app.models.exception_item import ExceptionItem
try:
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from openpyxl.utils import get_column_letter
OPENPYXL_AVAILABLE = True
except ImportError:
OPENPYXL_AVAILABLE = False
class ExportService:
"""导出服务"""
def __init__(self, db: AsyncSession):
self.db = db
async def export_task_result(self, task_id: int) -> bytes:
"""
导出任务对账结果
Args:
task_id: 任务ID
Returns:
Excel 文件二进制数据
"""
if not OPENPYXL_AVAILABLE:
raise ImportError("openpyxl 未安装")
# 获取任务信息
task = await self.db.get(ReconciliationTask, task_id)
if not task:
raise ValueError("任务不存在")
# 获取异常列表
from sqlalchemy import select
query = select(ExceptionItem).where(ExceptionItem.task_id == task_id)
result = await self.db.execute(query)
exceptions = result.scalars().all()
# 创建工作簿
wb = Workbook()
# Sheet 1: 概览
ws_summary = wb.active
ws_summary.title = "概览"
self._fill_summary_sheet(ws_summary, task, exceptions)
# Sheet 2: 异常列表
ws_exceptions = wb.create_sheet("异常列表")
self._fill_exceptions_sheet(ws_exceptions, exceptions)
# Sheet 3: 异常类型统计
ws_stats = wb.create_sheet("异常统计")
self._fill_stats_sheet(ws_stats, exceptions)
# 保存到字节流
output = io.BytesIO()
wb.save(output)
output.seek(0)
return output.read()
def _fill_summary_sheet(
self,
ws,
task: ReconciliationTask,
exceptions: List[ExceptionItem],
):
"""填充概览Sheet"""
# 标题样式
title_font = Font(bold=True, size=14)
header_font = Font(bold=True)
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
header_font_white = Font(bold=True, color="FFFFFF")
thin_border = Border(
left=Side(style="thin"),
right=Side(style="thin"),
top=Side(style="thin"),
bottom=Side(style="thin"),
)
# 标题
ws["A1"] = f"对账结果汇总 - {task.name}"
ws["A1"].font = title_font
ws.merge_cells("A1:D1")
# 基本信息
ws["A3"] = "任务名称"
ws["B3"] = task.name
ws["A4"] = "对账期间"
ws["B4"] = task.period
ws["A5"] = "创建时间"
ws["B5"] = task.created_at.strftime("%Y-%m-%d %H:%M:%S") if task.created_at else ""
ws["A6"] = "完成时间"
ws["B6"] = task.completed_at.strftime("%Y-%m-%d %H:%M:%S") if task.completed_at else ""
# 统计数据
ws["A8"] = "统计数据"
ws["A8"].font = header_font
ws["A9"] = "总人数"
ws["B9"] = task.total_employees
ws["A10"] = "匹配人数"
ws["B10"] = task.matched_count
ws["A11"] = "异常数量"
ws["B11"] = task.exception_count
ws["A12"] = "匹配率"
ws["B12"] = f"{(task.matched_count / task.total_employees * 100):.1f}%" if task.total_employees > 0 else "0%"
# 设置列宽
ws.column_dimensions["A"].width = 15
ws.column_dimensions["B"].width = 30
def _fill_exceptions_sheet(self, ws, exceptions: List[ExceptionItem]):
"""填充异常列表Sheet"""
# 样式
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
header_font = Font(bold=True, color="FFFFFF")
thin_border = Border(
left=Side(style="thin"),
right=Side(style="thin"),
top=Side(style="thin"),
bottom=Side(style="thin"),
)
# 表头
headers = [
"异常ID", "员工ID", "员工姓名", "异常类型", "严重程度",
"状态", "描述", "工资", "社保", "个税", "银行", "差异金额",
"解决方案", "处理人", "创建时间"
]
for col, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col, value=header)
cell.fill = header_fill
cell.font = header_font
cell.border = thin_border
cell.alignment = Alignment(horizontal="center")
# 数据
for row_idx, exc in enumerate(exceptions, 2):
ws.cell(row=row_idx, column=1, value=exc.id).border = thin_border
ws.cell(row=row_idx, column=2, value=exc.employee_id).border = thin_border
ws.cell(row=row_idx, column=3, value=exc.employee_name).border = thin_border
ws.cell(row=row_idx, column=4, value=exc.exception_type).border = thin_border
ws.cell(row=row_idx, column=5, value=exc.severity).border = thin_border
ws.cell(row=row_idx, column=6, value=exc.status).border = thin_border
ws.cell(row=row_idx, column=7, value=exc.description).border = thin_border
# 金额(保留两位小数)
ws.cell(row=row_idx, column=8, value=exc.salary_amount).border = thin_border
ws.cell(row=row_idx, column=9, value=exc.social_security_amount).border = thin_border
ws.cell(row=row_idx, column=10, value=exc.tax_amount).border = thin_border
ws.cell(row=row_idx, column=11, value=exc.bank_amount).border = thin_border
ws.cell(row=row_idx, column=12, value=exc.difference_amount).border = thin_border
ws.cell(row=row_idx, column=13, value=exc.resolution).border = thin_border
ws.cell(row=row_idx, column=14, value=exc.handler).border = thin_border
ws.cell(row=row_idx, column=15, value=exc.created_at.strftime("%Y-%m-%d %H:%M:%S") if exc.created_at else "").border = thin_border
# 设置列宽
col_widths = [10, 15, 15, 20, 10, 10, 40, 12, 12, 12, 12, 12, 20, 15, 20]
for col, width in enumerate(col_widths, 1):
ws.column_dimensions[get_column_letter(col)].width = width
def _fill_stats_sheet(self, ws, exceptions: List[ExceptionItem]):
"""填充统计Sheet"""
from collections import Counter
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
header_font = Font(bold=True, color="FFFFFF")
thin_border = Border(
left=Side(style="thin"),
right=Side(style="thin"),
top=Side(style="thin"),
bottom=Side(style="thin"),
)
# 按类型统计
ws["A1"] = "按异常类型统计"
ws["A1"].font = Font(bold=True)
ws["A2"] = "类型"
ws["B2"] = "数量"
ws["A2"].fill = header_fill
ws["B2"].fill = header_fill
ws["A2"].font = header_font
ws["B2"].font = header_font
ws["A2"].border = thin_border
ws["B2"].border = thin_border
type_counts = Counter(e.exception_type for e in exceptions)
for row_idx, (exc_type, count) in enumerate(type_counts.items(), 3):
ws.cell(row=row_idx, column=1, value=exc_type).border = thin_border
ws.cell(row=row_idx, column=2, value=count).border = thin_border
# 按严重程度统计
start_row = len(type_counts) + 5
ws.cell(row=start_row, column=1, value="按严重程度统计").font = Font(bold=True)
ws.cell(row=start_row + 1, column=1, value="严重程度")
ws.cell(row=start_row + 1, column=2, value="数量")
ws.cell(row=start_row + 1, column=1).fill = header_fill
ws.cell(row=start_row + 1, column=2).fill = header_fill
ws.cell(row=start_row + 1, column=1).font = header_font
ws.cell(row=start_row + 1, column=2).font = header_font
severity_counts = Counter(e.severity for e in exceptions)
for row_idx, (severity, count) in enumerate(severity_counts.items(), start_row + 2):
ws.cell(row=row_idx, column=1, value=severity).border = thin_border
ws.cell(row=row_idx, column=2, value=count).border = thin_border
# 按状态统计
start_row = start_row + len(severity_counts) + 3
ws.cell(row=start_row, column=1, value="按状态统计").font = Font(bold=True)
ws.cell(row=start_row + 1, column=1, value="状态")
ws.cell(row=start_row + 1, column=2, value="数量")
ws.cell(row=start_row + 1, column=1).fill = header_fill
ws.cell(row=start_row + 1, column=2).fill = header_fill
ws.cell(row=start_row + 1, column=1).font = header_font
ws.cell(row=start_row + 1, column=2).font = header_font
status_counts = Counter(e.status for e in exceptions)
for row_idx, (status, count) in enumerate(status_counts.items(), start_row + 2):
ws.cell(row=row_idx, column=1, value=status).border = thin_border
ws.cell(row=row_idx, column=2, value=count).border = thin_border
async def export_kingdee_voucher(self, task_id: int) -> bytes:
"""
导出金蝶凭证
Args:
task_id: 任务ID
Returns:
Excel 文件二进制数据
"""
if not OPENPYXL_AVAILABLE:
raise ImportError("openpyxl 未安装")
# 获取任务信息
task = await self.db.get(ReconciliationTask, task_id)
if not task:
raise ValueError("任务不存在")
# 获取已解决的异常(排除已忽略的)
from sqlalchemy import select
query = select(ExceptionItem).where(
ExceptionItem.task_id == task_id,
ExceptionItem.status == "resolved"
)
result = await self.db.execute(query)
resolved_exceptions = result.scalars().all()
# 创建工作簿
wb = Workbook()
ws = wb.active
ws.title = "凭证数据"
# 样式
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
header_font = Font(bold=True, color="FFFFFF")
thin_border = Border(
left=Side(style="thin"),
right=Side(style="thin"),
top=Side(style="thin"),
bottom=Side(style="thin"),
)
# 金蝶凭证格式表头
headers = [
"凭证字", "凭证号", "凭证日期", "附单据数",
"摘要", "科目代码", "科目名称",
"借方金额", "贷方金额", "币种", "汇率"
]
for col, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col, value=header)
cell.fill = header_fill
cell.font = header_font
cell.border = thin_border
cell.alignment = Alignment(horizontal="center")
# 填充数据(根据金蝶凭证格式要求)
row_idx = 2
for exc in resolved_exceptions:
# 生成凭证摘要
summary = f"工资对账调整 - {exc.employee_name} ({exc.employee_id})"
# 如果有差异金额,生成借贷分录
if exc.difference_amount and exc.difference_amount != 0:
# 借方分录
ws.cell(row=row_idx, column=1, value="").border = thin_border
ws.cell(row=row_idx, column=2, value="").border = thin_border # 凭证号自动生成
ws.cell(row=row_idx, column=3, value=task.period + "-01").border = thin_border
ws.cell(row=row_idx, column=4, value=1).border = thin_border
ws.cell(row=row_idx, column=5, value=summary).border = thin_border
ws.cell(row=row_idx, column=6, value="").border = thin_border # 科目代码
ws.cell(row=row_idx, column=7, value="待处理").border = thin_border # 科目名称
if exc.difference_amount > 0:
ws.cell(row=row_idx, column=8, value=abs(exc.difference_amount)).border = thin_border
ws.cell(row=row_idx, column=9, value=0).border = thin_border
else:
ws.cell(row=row_idx, column=8, value=0).border = thin_border
ws.cell(row=row_idx, column=9, value=abs(exc.difference_amount)).border = thin_border
ws.cell(row=row_idx, column=10, value="人民币").border = thin_border
ws.cell(row=row_idx, column=11, value=1).border = thin_border
row_idx += 1
# 设置列宽
col_widths = [10, 12, 15, 10, 40, 15, 20, 15, 15, 10, 10]
for col, width in enumerate(col_widths, 1):
ws.column_dimensions[get_column_letter(col)].width = width
# 保存到字节流
output = io.BytesIO()
wb.save(output)
output.seek(0)
return output.read()
# 便捷函数
async def export_task_result(db: AsyncSession, task_id: int) -> bytes:
"""导出任务对账结果"""
service = ExportService(db)
return await service.export_task_result(task_id)
async def export_kingdee_voucher(db: AsyncSession, task_id: int) -> bytes:
"""导出金蝶凭证"""
service = ExportService(db)
return await service.export_kingdee_voucher(task_id)
+114
View File
@@ -0,0 +1,114 @@
import csv
from pathlib import Path
from typing import Any
import openpyxl
import pandas as pd
class FileParserService:
"""文件解析服务"""
@staticmethod
def parse_excel(file_path: str | Path) -> dict[str, Any]:
"""
解析 Excel 文件
Args:
file_path: 文件路径
Returns:
解析结果:headers, sample_rows, total_rows
"""
file_path = Path(file_path)
# 使用 openpyxl 解析 .xlsx
if file_path.suffix.lower() == ".xlsx":
wb = openpyxl.load_workbook(file_path, read_only=True, data_only=True)
ws = wb.active
# 获取表头(第一行)
headers = [cell.value for cell in ws[1]]
# 获取样例数据(前5行,不含表头)
sample_rows = []
for row_idx, row in enumerate(ws.iter_rows(min_row=2, max_row=6, values_only=True), start=2):
row_data = dict(zip(headers, row))
sample_rows.append(row_data)
# 获取总行数
total_rows = ws.max_row - 1 # 减去表头行
wb.close()
return {
"headers": headers,
"sample_rows": sample_rows,
"total_rows": total_rows,
}
# 使用 pandas 解析其他格式
else:
df = pd.read_excel(file_path)
return {
"headers": df.columns.tolist(),
"sample_rows": df.head(5).to_dict(orient="records"),
"total_rows": len(df),
}
@staticmethod
def parse_csv(file_path: str | Path) -> dict[str, Any]:
"""
解析 CSV 文件
Args:
file_path: 文件路径
Returns:
解析结果
"""
file_path = Path(file_path)
# 自动检测编码
encodings = ["utf-8", "gbk", "gb2312", "utf-8-sig"]
df = None
for encoding in encodings:
try:
df = pd.read_csv(file_path, encoding=encoding)
break
except (UnicodeDecodeError, Exception):
continue
if df is None:
raise ValueError("无法解析CSV文件,编码格式不支持")
return {
"headers": df.columns.tolist(),
"sample_rows": df.head(5).to_dict(orient="records"),
"total_rows": len(df),
}
@staticmethod
def detect_file_type(file_content: bytes) -> str:
"""
检测文件类型
Args:
file_content: 文件内容
Returns:
文件类型
"""
# 简单的文件类型检测
if file_content[:2] == b"PK":
return "xlsx"
elif file_content[:8] == b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1":
return "xls"
else:
return "csv"
# 单例实例
file_parser_service = FileParserService()
+87
View File
@@ -0,0 +1,87 @@
import os
import uuid
from pathlib import Path
from fastapi import UploadFile
from app.core.config import get_settings
settings = get_settings()
class FileStorageService:
"""文件存储服务"""
@staticmethod
def get_upload_dir() -> Path:
"""获取上传目录"""
upload_dir = Path(settings.upload_dir)
upload_dir.mkdir(parents=True, exist_ok=True)
return upload_dir
@staticmethod
async def save_file(file: UploadFile, company_id: int) -> tuple[str, int]:
"""
保存上传的文件
Args:
file: 上传的文件
company_id: 企业ID
Returns:
(存储文件名, 文件大小)
"""
# 创建企业专属目录
company_dir = FileStorageService.get_upload_dir() / str(company_id)
company_dir.mkdir(parents=True, exist_ok=True)
# 生成唯一文件名
file_ext = Path(file.filename or "file").suffix
stored_filename = f"{uuid.uuid4().hex}{file_ext}"
file_path = company_dir / stored_filename
# 保存文件
content = await file.read()
file_size = len(content)
with open(file_path, "wb") as f:
f.write(content)
return f"{company_id}/{stored_filename}", file_size
@staticmethod
def get_file_path(stored_filename: str) -> Path:
"""
获取文件完整路径
Args:
stored_filename: 存储文件名(格式: company_id/filename
Returns:
文件路径
"""
return FileStorageService.get_upload_dir() / stored_filename
@staticmethod
def delete_file(stored_filename: str) -> bool:
"""
删除文件
Args:
stored_filename: 存储文件名
Returns:
是否删除成功
"""
try:
file_path = FileStorageService.get_file_path(stored_filename)
if file_path.exists():
file_path.unlink()
return True
return False
except Exception:
return False
# 单例实例
file_storage_service = FileStorageService()
+314
View File
@@ -0,0 +1,314 @@
"""
字段映射服务
管理字段映射的创建、确认和规则沉淀
"""
from datetime import datetime
from typing import List, Optional, Dict
from sqlalchemy import select, and_, or_
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.models.field_mapping import FieldMapping
from app.models.company_rule import CompanyRule, RuleType, RuleStatus
from app.models.uploaded_file import UploadedFile
from app.services.ai_recognizer import recognize_fields_with_ai
class MappingService:
"""字段映射服务"""
def __init__(self, db: AsyncSession):
self.db = db
async def recognize_and_save(
self,
company_id: int,
file_id: int,
file_type: str = "工资表"
) -> List[FieldMapping]:
"""
识别并保存字段映射
Args:
company_id: 企业ID
file_id: 文件ID
file_type: 文件类型
Returns:
字段映射列表
"""
# 1. 获取文件信息
file = await self.db.get(UploadedFile, file_id)
if not file:
raise ValueError(f"文件不存在: {file_id}")
# 2. 解析文件获取表头和样例数据
# TODO: 调用文件解析服务获取实际数据
# 暂时使用空数据
headers = []
sample_data = []
# 3. 调用 AI 识别
mappings_data = await recognize_fields_with_ai(
db=self.db,
company_id=company_id,
headers=headers,
sample_data=sample_data,
file_type=file_type
)
# 4. 保存映射
mappings = []
for data in mappings_data:
mapping = FieldMapping(
company_id=company_id,
file_id=file_id,
source_field=data["source_field"],
standard_field=data["standard_field"],
confidence=data["confidence"],
reasoning=data.get("reasoning"),
sample_values=data.get("sample_values"),
)
self.db.add(mapping)
mappings.append(mapping)
await self.db.commit()
for mapping in mappings:
await self.db.refresh(mapping)
return mappings
async def get_mappings_by_file(self, file_id: int) -> List[FieldMapping]:
"""获取文件的所有字段映射"""
result = await self.db.execute(
select(FieldMapping)
.where(FieldMapping.file_id == file_id)
.order_by(FieldMapping.id)
)
return list(result.scalars().all())
async def get_mappings_by_task(self, task_id: int, company_id: int) -> Dict[int, List[FieldMapping]]:
"""获取任务的所有字段映射(按文件分组)"""
result = await self.db.execute(
select(FieldMapping)
.where(FieldMapping.company_id == company_id)
.options(selectinload(FieldMapping.file))
.order_by(FieldMapping.file_id, FieldMapping.id)
)
mappings = list(result.scalars().all())
# 按文件ID分组
grouped: Dict[int, List[FieldMapping]] = {}
for mapping in mappings:
if mapping.file_id not in grouped:
grouped[mapping.file_id] = []
grouped[mapping.file_id].append(mapping)
return grouped
async def update_mapping(
self,
mapping_id: int,
standard_field: Optional[str] = None,
is_skipped: Optional[bool] = None
) -> Optional[FieldMapping]:
"""更新字段映射"""
mapping = await self.db.get(FieldMapping, mapping_id)
if not mapping:
return None
if standard_field is not None:
mapping.standard_field = standard_field
# 用户手动修改,重置置信度为 1.0
mapping.confidence = 1.0
if is_skipped is not None:
mapping.is_skipped = is_skipped
await self.db.commit()
await self.db.refresh(mapping)
return mapping
async def confirm_mapping(
self,
mapping_id: int,
user_id: int
) -> Optional[FieldMapping]:
"""确认字段映射"""
mapping = await self.db.get(FieldMapping, mapping_id)
if not mapping:
return None
mapping.confirmed = True
mapping.confirmed_by = user_id
mapping.confirmed_at = datetime.utcnow()
await self.db.commit()
await self.db.refresh(mapping)
return mapping
async def confirm_mappings(
self,
mapping_ids: List[int],
user_id: int
) -> List[FieldMapping]:
"""批量确认字段映射"""
confirmed = []
for mapping_id in mapping_ids:
mapping = await self.confirm_mapping(mapping_id, user_id)
if mapping:
confirmed.append(mapping)
return confirmed
async def save_as_rule(
self,
mapping: FieldMapping,
user_id: Optional[int] = None
) -> CompanyRule:
"""
将字段映射保存为企业规则
Args:
mapping: 字段映射
user_id: 用户ID
Returns:
创建的规则
"""
rule = CompanyRule(
company_id=mapping.company_id,
rule_type=RuleType.FIELD_MAPPING.value,
match_condition={
"source_field": mapping.source_field,
"file_type": mapping.standard_field.split("_")[0] if "_" in mapping.standard_field else "",
},
target_value=mapping.standard_field,
priority=0,
status=RuleStatus.ACTIVE.value,
description=f"字段映射规则:'{mapping.source_field}' -> '{mapping.standard_field}'",
created_by=user_id,
)
self.db.add(rule)
await self.db.commit()
await self.db.refresh(rule)
return rule
async def apply_rules(
self,
company_id: int,
headers: List[str]
) -> List[Dict]:
"""
应用企业规则进行字段匹配
Args:
company_id: 企业ID
headers: 表头列表
Returns:
匹配的字段映射列表
"""
# 1. 获取企业的所有字段映射规则
result = await self.db.execute(
select(CompanyRule)
.where(
and_(
CompanyRule.company_id == company_id,
CompanyRule.rule_type == RuleType.FIELD_MAPPING.value,
CompanyRule.status == RuleStatus.ACTIVE.value
)
)
.order_by(CompanyRule.priority.desc())
)
rules = list(result.scalars().all())
# 2. 构建规则索引
field_rules: Dict[str, CompanyRule] = {}
for rule in rules:
source_field = rule.match_condition.get("source_field", "")
if source_field:
field_rules[source_field] = rule
# 3. 匹配规则
mappings = []
for header in headers:
matched_rule = None
confidence = 0.0
# 精确匹配
if header in field_rules:
matched_rule = field_rules[header]
confidence = 1.0
# 模糊匹配
if not matched_rule:
for source_field, rule in field_rules.items():
if source_field in header or header in source_field:
if confidence < 0.9:
matched_rule = rule
confidence = 0.9
break
if matched_rule:
mappings.append({
"source_field": header,
"standard_field": matched_rule.target_value,
"confidence": confidence,
"reasoning": "规则命中" if confidence == 1.0 else "规则模糊匹配",
"is_rule_based": True,
})
else:
mappings.append({
"source_field": header,
"standard_field": "",
"confidence": 0.0,
"reasoning": "无匹配规则",
"is_rule_based": False,
})
return mappings
async def get_company_rules(
self,
company_id: int,
rule_type: Optional[str] = None
) -> List[CompanyRule]:
"""获取企业的规则列表"""
query = select(CompanyRule).where(CompanyRule.company_id == company_id)
if rule_type:
query = query.where(CompanyRule.rule_type == rule_type)
query = query.order_by(CompanyRule.priority.desc(), CompanyRule.created_at.desc())
result = await self.db.execute(query)
return list(result.scalars().all())
async def update_rule_status(
self,
rule_id: int,
status: str
) -> Optional[CompanyRule]:
"""更新规则状态"""
rule = await self.db.get(CompanyRule, rule_id)
if not rule:
return None
rule.status = status
await self.db.commit()
await self.db.refresh(rule)
return rule
async def delete_rule(self, rule_id: int) -> bool:
"""删除规则"""
rule = await self.db.get(CompanyRule, rule_id)
if not rule:
return False
await self.db.delete(rule)
await self.db.commit()
return True
@@ -0,0 +1,335 @@
"""
对账引擎
执行对账逻辑,协调各个规则
"""
import time
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.models.exception_item import ExceptionItem, ExceptionStatus
from app.services.reconciliation.rules import (
RuleContext,
RuleResult,
RuleFactory,
ReconciliationRule,
)
@dataclass
class ReconciliationResult:
"""对账结果"""
task_id: int
period: str
total_employees: int
matched_employees: int
exception_count: int
# 统计
exceptions_by_type: Dict[str, int] = field(default_factory=dict)
exceptions_by_severity: Dict[str, int] = field(default_factory=dict)
# 详细结果
matched_employees_list: List[Dict[str, Any]] = field(default_factory=list)
exception_items: List[Dict[str, Any]] = field(default_factory=list)
# 性能指标
execution_time_ms: float = 0
rules_executed: int = 0
# 时间戳
completed_at: str = ""
class ReconciliationEngine:
"""
对账引擎
协调数据加载、规则执行、结果存储
"""
def __init__(
self,
db: AsyncSession,
company_id: int,
task_id: int,
period: str,
enable_bank_rules: bool = False,
):
self.db = db
self.company_id = company_id
self.task_id = task_id
self.period = period
self.enable_bank_rules = enable_bank_rules
# 创建规则
self.rules = RuleFactory.create_all_rules(enable_bank_rules)
# 数据存储
self.salary_data: Dict[str, Dict[str, Any]] = {}
self.social_security_data: Dict[str, Dict[str, Any]] = {}
self.tax_data: Dict[str, Dict[str, Any]] = {}
self.bank_data: Optional[Dict[str, Dict[str, Any]]] = None
# 结果
self.exceptions: List[ExceptionItem] = []
self.matched_count = 0
self.exception_count = 0
def load_data(
self,
salary_records: List[Dict[str, Any]],
social_security_records: List[Dict[str, Any]],
tax_records: List[Dict[str, Any]],
bank_records: Optional[List[Dict[str, Any]]] = None,
employee_id_field: str = "employee_id",
employee_name_field: str = "employee_name",
):
"""
加载数据
Args:
salary_records: 工资表数据
social_security_records: 社保表数据
tax_records: 个税表数据
bank_records: 银行数据(可选)
employee_id_field: 员工ID字段名
employee_name_field: 员工姓名字段名
"""
# 加载工资数据
for record in salary_records:
emp_id = str(record.get(employee_id_field, ""))
if emp_id:
self.salary_data[emp_id] = record
# 加载社保数据
for record in social_security_records:
emp_id = str(record.get(employee_id_field, ""))
if emp_id:
self.social_security_data[emp_id] = record
# 加载个税数据
for record in tax_records:
emp_id = str(record.get(employee_id_field, ""))
if emp_id:
self.tax_data[emp_id] = record
# 加载银行数据
if bank_records:
self.bank_data = {}
for record in bank_records:
emp_id = str(record.get(employee_id_field, ""))
if emp_id:
self.bank_data[emp_id] = record
async def execute(self) -> ReconciliationResult:
"""
执行对账
Returns:
对账结果
"""
start_time = time.time()
# 获取所有员工ID(合并三个表)
all_employee_ids = set()
all_employee_ids.update(self.salary_data.keys())
all_employee_ids.update(self.social_security_data.keys())
all_employee_ids.update(self.tax_data.keys())
if self.bank_data:
all_employee_ids.update(self.bank_data.keys())
total_employees = len(all_employee_ids)
matched_employees = 0
exception_items: List[Dict[str, Any]] = []
# 统计
exceptions_by_type: Dict[str, int] = {}
exceptions_by_severity: Dict[str, int] = {}
matched_list: List[Dict[str, Any]] = []
# 重置需要状态的规则
for rule in self.rules:
if hasattr(rule, 'reset'):
rule.reset()
# 遍历每个员工
for employee_id in all_employee_ids:
# 获取员工姓名
employee_name = (
self.salary_data.get(employee_id, {}).get("employee_name") or
self.social_security_data.get(employee_id, {}).get("employee_name") or
self.tax_data.get(employee_id, {}).get("employee_name") or
employee_id
)
# 构建规则上下文
context = RuleContext(
company_id=self.company_id,
task_id=self.task_id,
period=self.period,
employee_id=employee_id,
employee_name=employee_name,
salary_data=self.salary_data,
social_security_data=self.social_security_data,
tax_data=self.tax_data,
bank_data=self.bank_data,
)
# 执行所有规则
employee_exceptions = []
for rule in self.rules:
if not rule.enabled:
continue
try:
result = rule.check(context)
if result.is_exception:
employee_exceptions.append((rule, result))
except Exception as e:
# 规则执行出错,记录但不中断
pass
# 处理该员工的异常
if employee_exceptions:
for rule, result in employee_exceptions:
# 保存异常到数据库
exception_item = await self._save_exception(rule, result, context)
self.exceptions.append(exception_item)
exception_items.append({
"id": exception_item.id,
"type": result.exception_type.value if result.exception_type else rule.exception_type.value,
"severity": result.severity.value,
"description": result.description,
"employee_id": employee_id,
"employee_name": employee_name,
})
# 统计
type_key = result.exception_type.value if result.exception_type else rule.exception_type.value
exceptions_by_type[type_key] = exceptions_by_type.get(type_key, 0) + 1
exceptions_by_severity[result.severity.value] = (
exceptions_by_severity.get(result.severity.value, 0) + 1
)
else:
matched_employees += 1
matched_list.append({
"employee_id": employee_id,
"employee_name": employee_name,
})
# 更新任务统计
await self._update_task_stats(matched_employees, len(exception_items))
execution_time = (time.time() - start_time) * 1000
return ReconciliationResult(
task_id=self.task_id,
period=self.period,
total_employees=total_employees,
matched_employees=matched_employees,
exception_count=len(exception_items),
exceptions_by_type=exceptions_by_type,
exceptions_by_severity=exceptions_by_severity,
matched_employees_list=matched_list,
exception_items=exception_items,
execution_time_ms=execution_time,
rules_executed=len([r for r in self.rules if r.enabled]),
completed_at=datetime.utcnow().isoformat(),
)
async def _save_exception(
self,
rule: ReconciliationRule,
result: RuleResult,
context: RuleContext,
) -> ExceptionItem:
"""保存异常到数据库"""
exception_item = ExceptionItem(
company_id=self.company_id,
task_id=self.task_id,
exception_type=result.exception_type.value if result.exception_type else rule.exception_type.value,
severity=result.severity.value,
status=ExceptionStatus.PENDING.value,
employee_id=context.employee_id,
employee_name=context.employee_name,
description=result.description,
detail=result.detail,
salary_amount=result.salary_amount,
social_security_amount=result.social_security_amount,
tax_amount=result.tax_amount,
bank_amount=result.bank_amount,
difference_amount=result.difference_amount,
suggested_action=result.suggested_action,
)
self.db.add(exception_item)
await self.db.commit()
await self.db.refresh(exception_item)
return exception_item
async def _update_task_stats(self, matched: int, exceptions: int):
"""更新任务统计"""
from app.models.reconciliation_task import ReconciliationTask
task = await self.db.get(ReconciliationTask, self.task_id)
if task:
task.matched_count = matched
task.exception_count = exceptions
task.total_employees = matched + exceptions
task.status = "COMPLETED"
await self.db.commit()
# 便捷函数
async def run_reconciliation(
db: AsyncSession,
company_id: int,
task_id: int,
period: str,
salary_records: List[Dict[str, Any]],
social_security_records: List[Dict[str, Any]],
tax_records: List[Dict[str, Any]],
bank_records: Optional[List[Dict[str, Any]]] = None,
enable_bank_rules: bool = False,
) -> ReconciliationResult:
"""
运行对账
Args:
db: 数据库会话
company_id: 企业ID
task_id: 任务ID
period: 对账期间
salary_records: 工资表数据
social_security_records: 社保表数据
tax_records: 个税表数据
bank_records: 银行数据(可选)
enable_bank_rules: 是否启用银行规则
Returns:
对账结果
"""
engine = ReconciliationEngine(
db=db,
company_id=company_id,
task_id=task_id,
period=period,
enable_bank_rules=enable_bank_rules,
)
engine.load_data(
salary_records=salary_records,
social_security_records=social_security_records,
tax_records=tax_records,
bank_records=bank_records,
)
return await engine.execute()
@@ -0,0 +1,459 @@
"""
对账规则定义
实现 7 类异常检测规则(第一阶段)+ 预留银行实发对账规则(第二阶段)
"""
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional, Tuple
from app.models.exception_item import ExceptionType, ExceptionSeverity
@dataclass
class RuleContext:
"""规则上下文"""
company_id: int
task_id: int
period: str
employee_id: str
employee_name: str
salary_data: Dict[str, Any]
social_security_data: Dict[str, Any]
tax_data: Dict[str, Any]
bank_data: Optional[Dict[str, Any]] = None
@dataclass
class RuleResult:
"""规则检测结果"""
is_exception: bool
exception_type: Optional[ExceptionType] = None
severity: ExceptionSeverity = ExceptionSeverity.MEDIUM
description: str = ""
detail: Dict[str, Any] = field(default_factory=dict)
salary_amount: Optional[float] = None
social_security_amount: Optional[float] = None
tax_amount: Optional[float] = None
bank_amount: Optional[float] = None
difference_amount: Optional[float] = None
suggested_action: str = ""
class ReconciliationRule(ABC):
"""对账规则基类"""
def __init__(self, enabled: bool = True):
self.enabled = enabled
@property
@abstractmethod
def name(self) -> str:
"""规则名称"""
pass
@property
@abstractmethod
def exception_type(self) -> ExceptionType:
"""异常类型"""
pass
@property
def severity(self) -> ExceptionSeverity:
"""默认严重程度"""
return ExceptionSeverity.MEDIUM
@abstractmethod
def check(self, context: RuleContext) -> RuleResult:
"""执行规则检查"""
pass
class MissingEmployeeRule(ReconciliationRule):
"""员工缺失规则"""
@property
def name(self) -> str:
return "员工缺失检测"
@property
def exception_type(self) -> ExceptionType:
return ExceptionType.MISSING_EMPLOYEE
def check(self, context: RuleContext) -> RuleResult:
"""检测员工是否在所有相关表中都存在"""
has_salary = bool(context.employee_id in context.salary_data)
has_social = bool(context.employee_id in context.social_security_data)
has_tax = bool(context.employee_id in context.tax_data)
# 至少需要在两个表中出现
present_count = sum([has_salary, has_social, has_tax])
if present_count == 0:
return RuleResult(
is_exception=False, # 不在任何一个表中,可能是新增员工
description="员工不在任何表中"
)
if present_count < 3:
missing_tables = []
if not has_salary:
missing_tables.append("工资表")
if not has_social:
missing_tables.append("社保表")
if not has_tax:
missing_tables.append("个税表")
return RuleResult(
is_exception=True,
exception_type=self.exception_type,
severity=ExceptionSeverity.HIGH,
description=f"员工在 {', '.join(missing_tables)} 中缺失",
detail={
"has_salary": has_salary,
"has_social_security": has_social,
"has_tax": has_tax,
},
suggested_action="确认该员工是否应该存在于此期间"
)
return RuleResult(is_exception=False)
class AmountMismatchRule(ReconciliationRule):
"""金额不匹配规则"""
@property
def name(self) -> str:
return "金额不匹配检测"
@property
def exception_type(self) -> ExceptionType:
return ExceptionType.AMOUNT_MISMATCH
def check(self, context: RuleContext) -> RuleResult:
"""检测工资、社保、个税之间的金额一致性"""
salary_record = context.salary_data.get(context.employee_id, {})
social_record = context.social_security_data.get(context.employee_id, {})
tax_record = context.tax_data.get(context.employee_id, {})
salary_net = salary_record.get("实发工资", 0) or salary_record.get("net_salary", 0)
tax_amount = tax_record.get("应缴个税", 0) or tax_record.get("tax", 0)
social_total = self._calc_social_total(social_record)
# 应发工资 - 个税 - 社保 = 实发工资(理论上)
salary_gross = salary_record.get("应发工资", 0) or salary_record.get("gross_salary", 0)
expected_net = salary_gross - tax_amount - social_total
# 允许一定误差(0.01元)
tolerance = 0.01
diff = abs(salary_net - expected_net)
if diff > tolerance:
return RuleResult(
is_exception=True,
exception_type=self.exception_type,
severity=ExceptionSeverity.HIGH,
description=f"实发工资与计算值不一致(差异: {diff:.2f}元)",
detail={
"salary_net": salary_net,
"expected_net": expected_net,
"salary_gross": salary_gross,
"tax_amount": tax_amount,
"social_total": social_total,
},
difference_amount=diff,
salary_amount=salary_net,
tax_amount=tax_amount,
social_security_amount=social_total,
suggested_action="检查工资表、社保表、个税表数据是否正确"
)
return RuleResult(is_exception=False)
def _calc_social_total(self, record: Dict) -> float:
"""计算社保合计"""
keys = ["养老保险", "医疗保险", "失业保险", "公积金", "社保合计"]
for key in keys:
if key in record:
return float(record[key] or 0)
# 如果没有合计,手动计算
total = 0
for key in ["养老保险", "医疗保险", "失业保险", "公积金"]:
total += float(record.get(key, 0) or 0)
return total
class ZeroAmountRule(ReconciliationRule):
"""零金额规则"""
@property
def name(self) -> str:
return "零金额检测"
@property
def exception_type(self) -> ExceptionType:
return ExceptionType.ZERO_AMOUNT
def check(self, context: RuleContext) -> RuleResult:
"""检测实发工资为零的情况"""
salary_record = context.salary_data.get(context.employee_id, {})
net_salary = salary_record.get("实发工资", 0) or salary_record.get("net_salary", 0)
if net_salary == 0:
return RuleResult(
is_exception=True,
exception_type=self.exception_type,
severity=ExceptionSeverity.MEDIUM,
description="实发工资为零",
detail={"net_salary": 0},
salary_amount=0,
suggested_action="确认员工是否离职或暂停发放"
)
return RuleResult(is_exception=False)
class NegativeAmountRule(ReconciliationRule):
"""负数金额规则"""
@property
def name(self) -> str:
return "负数金额检测"
@property
def exception_type(self) -> ExceptionType:
return ExceptionType.NEGATIVE_AMOUNT
def check(self, context: RuleContext) -> RuleResult:
"""检测负数金额"""
salary_record = context.salary_data.get(context.employee_id, {})
negative_fields = []
for field_name in ["实发工资", "应发工资", "基本工资", "奖金", "补贴"]:
value = salary_record.get(field_name, 0) or 0
if value < 0:
negative_fields.append(f"{field_name}: {value}")
if negative_fields:
return RuleResult(
is_exception=True,
exception_type=self.exception_type,
severity=ExceptionSeverity.CRITICAL,
description=f"发现负数金额: {', '.join(negative_fields)}",
detail={"negative_fields": negative_fields},
suggested_action="检查数据录入是否有误"
)
return RuleResult(is_exception=False)
class UnusualAmountRule(ReconciliationRule):
"""金额异常规则"""
def __init__(self, max_salary: float = 1000000, min_salary: float = 0):
super().__init__()
self.max_salary = max_salary
self.min_salary = min_salary
@property
def name(self) -> str:
return "金额异常检测"
@property
def exception_type(self) -> ExceptionType:
return ExceptionType.UNUSUAL_AMOUNT
def check(self, context: RuleContext) -> RuleResult:
"""检测金额异常(过大或过小)"""
salary_record = context.salary_data.get(context.employee_id, {})
net_salary = salary_record.get("实发工资", 0) or salary_record.get("net_salary", 0)
if net_salary > self.max_salary:
return RuleResult(
is_exception=True,
exception_type=self.exception_type,
severity=ExceptionSeverity.HIGH,
description=f"实发工资金额异常偏高: {net_salary:.2f}",
detail={"net_salary": net_salary, "max_allowed": self.max_salary},
salary_amount=net_salary,
suggested_action="确认是否为高管或特殊人员"
)
if 0 < net_salary < self.min_salary:
return RuleResult(
is_exception=True,
exception_type=self.exception_type,
severity=ExceptionSeverity.LOW,
description=f"实发工资金额异常偏低: {net_salary:.2f}",
detail={"net_salary": net_salary, "min_expected": self.min_salary},
salary_amount=net_salary,
suggested_action="确认是否为基础工资人员"
)
return RuleResult(is_exception=False)
class DuplicateEmployeeRule(ReconciliationRule):
"""重复员工规则"""
def __init__(self):
super().__init__()
self._seen_employees: Dict[str, List[str]] = {} # employee_id -> [task_ids]
def reset(self):
"""重置状态"""
self._seen_employees = {}
@property
def name(self) -> str:
return "重复员工检测"
@property
def exception_type(self) -> ExceptionType:
return ExceptionType.DUPLICATE_EMPLOYEE
def check(self, context: RuleContext) -> RuleResult:
"""检测同一任务中是否有重复员工"""
employee_key = f"{context.task_id}:{context.employee_id}"
if employee_key in self._seen_employees:
return RuleResult(
is_exception=True,
exception_type=self.exception_type,
severity=ExceptionSeverity.CRITICAL,
description=f"员工 {context.employee_name} (ID: {context.employee_id}) 在本任务中重复出现",
detail={"occurrences": len(self._seen_employees[employee_key]) + 1},
suggested_action="检查并删除重复记录"
)
self._seen_employees[employee_key] = [context.task_id]
return RuleResult(is_exception=False)
# 第二阶段预留规则
class BankMismatchRule(ReconciliationRule):
"""银行实发不匹配规则"""
def __init__(self, enabled: bool = False):
super().__init__(enabled=enabled)
@property
def name(self) -> str:
return "银行实发不匹配检测"
@property
def exception_type(self) -> ExceptionType:
return ExceptionType.BANK_MISMATCH
def check(self, context: RuleContext) -> RuleResult:
"""检测银行实发与工资表实发是否一致"""
if not context.bank_data or context.employee_id not in context.bank_data:
return RuleResult(
is_exception=False,
description="无银行数据或员工不在银行记录中"
)
salary_record = context.salary_data.get(context.employee_id, {})
bank_record = context.bank_data.get(context.employee_id, {})
salary_net = salary_record.get("实发工资", 0) or salary_record.get("net_salary", 0)
bank_net = bank_record.get("实发金额", 0) or bank_record.get("bank_amount", 0)
diff = abs(salary_net - bank_net)
tolerance = 0.01
if diff > tolerance:
return RuleResult(
is_exception=True,
exception_type=self.exception_type,
severity=ExceptionSeverity.HIGH,
description=f"银行实发与工资表实发不一致(差异: {diff:.2f}元)",
detail={
"salary_net": salary_net,
"bank_net": bank_net,
},
salary_amount=salary_net,
bank_amount=bank_net,
difference_amount=diff,
suggested_action="联系银行确认交易状态"
)
return RuleResult(is_exception=False)
class BankMissingRule(ReconciliationRule):
"""银行记录缺失规则"""
def __init__(self, enabled: bool = False):
super().__init__(enabled=enabled)
@property
def name(self) -> str:
return "银行记录缺失检测"
@property
def exception_type(self) -> ExceptionType:
return ExceptionType.BANK_MISSING
def check(self, context: RuleContext) -> RuleResult:
"""检测有工资但无银行记录的员工"""
if not context.bank_data:
return RuleResult(
is_exception=False,
description="无银行数据"
)
has_salary = context.employee_id in context.salary_data
has_bank = context.employee_id in context.bank_data
if has_salary and not has_bank:
return RuleResult(
is_exception=True,
exception_type=self.exception_type,
severity=ExceptionSeverity.HIGH,
description="工资表有记录但银行无记录",
detail={"has_salary": True, "has_bank": False},
suggested_action="确认是否已发放或银行信息有误"
)
return RuleResult(is_exception=False)
# 规则工厂
class RuleFactory:
"""规则工厂"""
@staticmethod
def create_all_rules(enable_bank_rules: bool = False) -> List[ReconciliationRule]:
"""创建所有规则"""
rules = [
DuplicateEmployeeRule(), # 需要先检测重复
ZeroAmountRule(),
NegativeAmountRule(),
MissingEmployeeRule(),
AmountMismatchRule(),
UnusualAmountRule(),
]
if enable_bank_rules:
rules.extend([
BankMismatchRule(enabled=True),
BankMissingRule(enabled=True),
])
return rules
@staticmethod
def create_mvp_rules() -> List[ReconciliationRule]:
"""创建 MVP 阶段的规则(第一阶段 7 类异常检测)"""
return [
DuplicateEmployeeRule(),
ZeroAmountRule(),
NegativeAmountRule(),
MissingEmployeeRule(),
AmountMismatchRule(),
UnusualAmountRule(),
]
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+95
View File
@@ -0,0 +1,95 @@
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# 导入配置和模型
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from app.core.config import get_settings
from app.core.database import Base
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# 从环境变量设置数据库 URL
settings = get_settings()
config.set_main_option("sqlalchemy.url", settings.database_url)
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
"""Execute migrations with the given connection."""
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""Create async engine and run migrations."""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode (async)."""
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+26
View File
@@ -0,0 +1,26 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
@@ -0,0 +1,30 @@
"""添加文件上传模型
Revision ID: 251fa1f5d435
Revises: 2a96c11aa55c
Create Date: 2026-07-06 22:49:36.283202
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '251fa1f5d435'
down_revision: Union[str, None] = '2a96c11aa55c'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
@@ -0,0 +1,30 @@
"""添加用户模型
Revision ID: 2a96c11aa55c
Revises: f6e668e45bff
Create Date: 2026-07-06 22:48:55.249510
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '2a96c11aa55c'
down_revision: Union[str, None] = 'f6e668e45bff'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
@@ -0,0 +1,30 @@
"""添加字段映射、规则和任务模型
Revision ID: 52067074731d
Revises: 251fa1f5d435
Create Date: 2026-07-06 23:08:48.885971
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '52067074731d'
down_revision: Union[str, None] = '251fa1f5d435'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
@@ -0,0 +1,30 @@
"""初始化数据库模型
Revision ID: f6e668e45bff
Revises:
Create Date: 2026-07-06 22:40:04.073613
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'f6e668e45bff'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
+1
View File
@@ -13,6 +13,7 @@ pandas==2.2.0
openai==1.10.0
python-dotenv==1.0.0
structlog==24.1.0
python-dateutil==2.8.2
pytest==7.4.4
pytest-asyncio==0.23.4
httpx==0.26.0
+556
View File
@@ -0,0 +1,556 @@
"""
示例数据初始化脚本
创建一套完整的真实业务场景示例数据:
- 企业:深圳星辰科技有限公司
- 用户:admin 管理员
- 3个月工资对账数据(2026年4月、5月、6月)
- 包含各类业务异常场景
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from datetime import datetime, date
from decimal import Decimal
import random
from app.core.database import async_session_maker as AsyncSessionLocal
from app.core.security import hash_password
# 导入所有模型以初始化 SQLAlchemy 关系
from app.models.company import Company, CompanyPlan, CompanyStatus
from app.models.user import User, UserRole, UserStatus
from app.models.uploaded_file import UploadedFile, FileType, ParseStatus
from app.models.reconciliation_task import ReconciliationTask, TaskStatus
from app.models.exception_item import ExceptionItem, ExceptionType, ExceptionStatus, ExceptionSeverity
from app.models.field_mapping import FieldMapping
from app.models.company_rule import CompanyRule
from app.models.standard_field import StandardField
# ========== 基础数据定义 ==========
# 公司信息
COMPANY_DATA = {
"name": "深圳星辰科技有限公司",
"plan": CompanyPlan.PROFESSIONAL.value,
"status": CompanyStatus.ACTIVE.value,
"data_retention_months": 12,
"max_users": 20,
"is_trial": False,
}
# 用户列表
USERS_DATA = [
{
"email": "admin@xingchen.com",
"password": "admin123",
"full_name": "张明华",
"role": UserRole.ADMIN.value,
},
{
"email": "finance@xingchen.com",
"password": "finance123",
"full_name": "李晓燕",
"role": UserRole.FINANCE_MANAGER.value,
},
{
"email": "accountant@xingchen.com",
"password": "account123",
"full_name": "王建国",
"role": UserRole.ACCOUNTANT.value,
},
]
# 员工数据(25名员工)
EMPLOYEES = [
# 管理层
{"id": "EMP001", "name": "张明华", "department": "管理层", "position": "总经理", "base_salary": 35000},
{"id": "EMP002", "name": "李晓燕", "department": "财务部", "position": "财务总监", "base_salary": 28000},
{"id": "EMP003", "name": "王建国", "department": "技术部", "position": "技术总监", "base_salary": 30000},
# 技术部
{"id": "EMP004", "name": "刘伟强", "department": "技术部", "position": "高级工程师", "base_salary": 22000},
{"id": "EMP005", "name": "陈志明", "department": "技术部", "position": "工程师", "base_salary": 18000},
{"id": "EMP006", "name": "周建军", "department": "技术部", "position": "工程师", "base_salary": 17000},
{"id": "EMP007", "name": "吴海涛", "department": "技术部", "position": "初级工程师", "base_salary": 12000},
{"id": "EMP008", "name": "郑晓峰", "department": "技术部", "position": "测试工程师", "base_salary": 15000},
# 产品部
{"id": "EMP009", "name": "孙丽娜", "department": "产品部", "position": "产品经理", "base_salary": 22000},
{"id": "EMP010", "name": "马俊杰", "department": "产品部", "position": "产品专员", "base_salary": 14000},
{"id": "EMP011", "name": "朱婷婷", "department": "产品部", "position": "UI设计师", "base_salary": 16000},
# 运营部
{"id": "EMP012", "name": "胡文静", "department": "运营部", "position": "运营总监", "base_salary": 25000},
{"id": "EMP013", "name": "林浩然", "department": "运营部", "position": "运营专员", "base_salary": 13000},
{"id": "EMP014", "name": "何雨晴", "department": "运营部", "position": "客服主管", "base_salary": 12000},
{"id": "EMP015", "name": "高建峰", "department": "运营部", "position": "客服专员", "base_salary": 9000},
# 市场部
{"id": "EMP016", "name": "罗晓东", "department": "市场部", "position": "市场总监", "base_salary": 26000},
{"id": "EMP017", "name": "宋志远", "department": "市场部", "position": "市场专员", "base_salary": 11000},
{"id": "EMP018", "name": "唐思远", "department": "市场部", "position": "销售经理", "base_salary": 15000},
{"id": "EMP019", "name": "韩冰冰", "department": "市场部", "position": "销售代表", "base_salary": 8000},
# 行政部
{"id": "EMP020", "name": "冯婉君", "department": "行政部", "position": "行政经理", "base_salary": 14000},
{"id": "EMP021", "name": "许志刚", "department": "行政部", "position": "行政专员", "base_salary": 8000},
{"id": "EMP022", "name": "邓小丽", "department": "行政部", "position": "前台接待", "base_salary": 6000},
# 人事部
{"id": "EMP023", "name": "曹丽华", "department": "人事部", "position": "人事经理", "base_salary": 15000},
{"id": "EMP024", "name": "彭海燕", "department": "人事部", "position": "招聘专员", "base_salary": 9000},
{"id": "EMP025", "name": "曾敏仪", "department": "人事部", "position": "薪酬专员", "base_salary": 8500},
]
def calculate_salary(employee: dict, month: int, year: int, has_bonus: bool = True) -> dict:
"""计算员工月工资"""
base = employee["base_salary"]
# 绩效工资(基本工资的10%-30%)
performance = base * random.uniform(0.1, 0.3)
# 奖金(部分员工有)
bonus = base * random.uniform(0.5, 1.5) if has_bonus and random.random() > 0.3 else 0
# 加班费(随机)
overtime = random.choice([0, 500, 1000, 1500, 2000])
# 应发工资
gross_salary = base + performance + bonus + overtime
# 社保个人部分(基本工资的10.5%)
social_security = base * 0.105
# 公积金(基本工资的12%
housing_fund = base * 0.12
# 个税专项附加扣除
tax_deduction = 2000 # 子女教育 + 继续教育 + 住房租金 等
# 应税工资
taxable = gross_salary - social_security - housing_fund - tax_deduction
# 个税(简化计算)
if taxable <= 3000:
tax = taxable * 0.03
elif taxable <= 12000:
tax = taxable * 0.10 - 210
elif taxable <= 25000:
tax = taxable * 0.20 - 1410
elif taxable <= 35000:
tax = taxable * 0.25 - 2660
elif taxable <= 55000:
tax = taxable * 0.30 - 4410
elif taxable <= 80000:
tax = taxable * 0.35 - 7160
else:
tax = taxable * 0.45 - 15160
tax = max(0, tax)
# 实发工资
net_salary = gross_salary - social_security - housing_fund - tax
return {
"employee_id": employee["id"],
"employee_name": employee["name"],
"department": employee["department"],
"base_salary": round(base, 2),
"performance_salary": round(performance, 2),
"bonus": round(bonus, 2),
"overtime_pay": round(overtime, 2),
"gross_salary": round(gross_salary, 2),
"social_security": round(social_security, 2),
"housing_fund": round(housing_fund, 2),
"personal_income_tax": round(tax, 2),
"net_salary": round(net_salary, 2),
}
def calculate_social_security(employee: dict) -> dict:
"""计算社保"""
base = employee["base_salary"]
# 养老保险(个人8%
pension = base * 0.08
# 医疗保险(个人2%
medical = base * 0.02
# 失业保险(个人0.5%
unemployment = base * 0.005
# 工伤保险(个人0%
work_injury = 0
# 生育保险(个人0%
maternity = 0
total = pension + medical + unemployment
return {
"employee_id": employee["id"],
"employee_name": employee["name"],
"department": employee["department"],
"pension": round(pension, 2),
"medical": round(medical, 2),
"unemployment": round(unemployment, 2),
"work_injury": round(work_injury, 2),
"maternity": round(maternity, 2),
"total": round(total, 2),
}
def calculate_tax(employee: dict, gross_salary: float) -> dict:
"""计算个税"""
base = employee["base_salary"]
# 社保个人部分
social = base * 0.105
# 公积金
housing = base * 0.12
# 专项附加扣除
deduction = 2000
# 应税所得
taxable = gross_salary - social - housing - deduction - 5000 # 起征点
if taxable <= 0:
tax = 0
tax_rate = 0
quick_deduction = 0
elif taxable <= 3000:
tax = taxable * 0.03
tax_rate = 0.03
quick_deduction = 0
elif taxable <= 12000:
tax = taxable * 0.10 - 210
tax_rate = 0.10
quick_deduction = 210
elif taxable <= 25000:
tax = taxable * 0.20 - 1410
tax_rate = 0.20
quick_deduction = 1410
elif taxable <= 35000:
tax = taxable * 0.25 - 2660
tax_rate = 0.25
quick_deduction = 2660
elif taxable <= 55000:
tax = taxable * 0.30 - 4410
tax_rate = 0.30
quick_deduction = 4410
elif taxable <= 80000:
tax = taxable * 0.35 - 7160
tax_rate = 0.35
quick_deduction = 7160
else:
tax = taxable * 0.45 - 15160
tax_rate = 0.45
quick_deduction = 15160
tax = max(0, tax)
return {
"employee_id": employee["id"],
"employee_name": employee["name"],
"department": employee["department"],
"gross_salary": round(gross_salary, 2),
"taxable_income": round(taxable, 2),
"tax_rate": tax_rate,
"quick_deduction": quick_deduction,
"tax_amount": round(tax, 2),
}
async def init_sample_data():
"""初始化示例数据"""
async with AsyncSessionLocal() as db:
try:
# 1. 创建公司
print("创建公司...")
company = Company(**COMPANY_DATA)
db.add(company)
await db.flush()
# 2. 创建用户
print("创建用户...")
admin_user = None
for user_data in USERS_DATA:
user = User(
company_id=company.id,
email=user_data["email"],
hashed_password=hash_password(user_data["password"]),
full_name=user_data["full_name"],
role=user_data["role"],
status=UserStatus.ACTIVE.value,
)
db.add(user)
if user_data["role"] == UserRole.ADMIN.value:
admin_user = user
await db.flush()
# 3. 创建3个月的对账任务
print("创建对账任务...")
tasks = []
months = [
(2026, 4, "4月"),
(2026, 5, "5月"),
(2026, 6, "6月"),
]
for year, month, month_name in months:
task = ReconciliationTask(
company_id=company.id,
name=f"{year}{month_name}工资对账",
period=f"{year}-{month:02d}",
status=TaskStatus.COMPLETED.value,
created_by=admin_user.id,
total_employees=len(EMPLOYEES),
)
db.add(task)
await db.flush()
tasks.append((task, year, month))
# 4. 为每个月创建异常
print("创建异常数据...")
# 10月异常
task_10, year_10, month_10 = tasks[0]
task_10.matched_count = 23
task_10.exception_count = 2
# 异常1:新员工入职(工资表有,社保表无)
exc1 = ExceptionItem(
company_id=company.id,
task_id=task_10.id,
exception_type=ExceptionType.MISSING_EMPLOYEE.value,
severity=ExceptionSeverity.MEDIUM.value,
status=ExceptionStatus.PENDING.value,
employee_id="EMP026",
employee_name="新入职员工",
description="员工【新入职员工】在工资表中存在,但在社保表中未找到记录",
detail={"source": "工资表", "missing_in": "社保表"},
ai_suggestion="请确认该员工是否已完成社保增员,如已增员请重新上传社保表",
)
db.add(exc1)
# 异常2:金额不匹配
salary_12 = calculate_salary(EMPLOYEES[11], month_10, year_10) # 胡文静
tax_12 = calculate_tax(EMPLOYEES[11], salary_12["gross_salary"])
exc2 = ExceptionItem(
company_id=company.id,
task_id=task_10.id,
exception_type=ExceptionType.AMOUNT_MISMATCH.value,
severity=ExceptionSeverity.HIGH.value,
status=ExceptionStatus.PENDING.value,
employee_id=EMPLOYEES[11]["id"],
employee_name=EMPLOYEES[11]["name"],
description=f"员工【{EMPLOYEES[11]['name']}】工资表实发金额与个税表申报金额不一致",
detail={
"salary_net": salary_12["net_salary"],
"tax_declared": tax_12["tax_amount"],
"difference": abs(salary_12["net_salary"] - tax_12["tax_amount"]),
},
salary_amount=salary_12["net_salary"],
tax_amount=tax_12["tax_amount"],
difference_amount=abs(salary_12["net_salary"] - tax_12["tax_amount"]),
ai_suggestion="请核对工资表和个税申报表的数据,确认是计算错误还是申报错误",
)
db.add(exc2)
# 11月异常
task_11, year_11, month_11 = tasks[1]
task_11.matched_count = 24
task_11.exception_count = 1
# 异常3:离职员工(工资表无,社保表有)
exc3 = ExceptionItem(
company_id=company.id,
task_id=task_11.id,
exception_type=ExceptionType.MISSING_EMPLOYEE.value,
severity=ExceptionSeverity.MEDIUM.value,
status=ExceptionStatus.CONFIRMED.value,
employee_id="EMP007",
employee_name="吴海涛",
description="员工【吴海涛】在社保表中存在,但在本月工资表中未找到",
detail={"source": "社保表", "missing_in": "工资表"},
handled_by=admin_user.id,
handled_at=datetime.utcnow(),
handling_note="该员工已于11月15日离职,工资表中已处理",
ai_suggestion="确认员工离职日期,如已办理社保减员可忽略此异常",
)
db.add(exc3)
# 12月异常(更多异常场景)
task_12, year_12, month_12 = tasks[2]
task_12.matched_count = 22
task_12.exception_count = 3
# 异常4:重复员工
exc4 = ExceptionItem(
company_id=company.id,
task_id=task_12.id,
exception_type=ExceptionType.DUPLICATE_EMPLOYEE.value,
severity=ExceptionSeverity.CRITICAL.value,
status=ExceptionStatus.PENDING.value,
employee_id="EMP019",
employee_name="韩冰冰",
description="员工【韩冰冰】在工资表中出现重复记录,请核实",
detail={"count": 2, "amounts": [8250.00, 8250.00]},
salary_amount=16500.00,
ai_suggestion="请检查是否是系统重复录入或是实际有两笔工资发放",
)
db.add(exc4)
# 异常5:金额为零
exc5 = ExceptionItem(
company_id=company.id,
task_id=task_12.id,
exception_type=ExceptionType.ZERO_AMOUNT.value,
severity=ExceptionSeverity.MEDIUM.value,
status=ExceptionStatus.PENDING.value,
employee_id="EMP022",
employee_name="邓小丽",
description="员工【邓小丽】本月实发工资为零,可能存在异常",
detail={"expected_amount": 6000.00, "actual_amount": 0},
salary_amount=0,
ai_suggestion="请确认该员工是否已离职、停薪留职或工资发放被扣押",
)
db.add(exc5)
# 异常6:金额异常(过高)
salary_3 = calculate_salary(EMPLOYEES[2], month_12, year_12)
exc6 = ExceptionItem(
company_id=company.id,
task_id=task_12.id,
exception_type=ExceptionType.UNUSUAL_AMOUNT.value,
severity=ExceptionSeverity.HIGH.value,
status=ExceptionStatus.PENDING.value,
employee_id=EMPLOYEES[2]["id"],
employee_name=EMPLOYEES[2]["name"],
description=f"员工【{EMPLOYEES[2]['name']}】本月工资较上月有较大波动",
detail={
"current": salary_3["net_salary"],
"previous_avg": 42000.00,
"change_ratio": 0.25,
},
salary_amount=salary_3["net_salary"],
difference_amount=8500.00,
ai_suggestion="该员工工资增长超过20%,请确认是否有大额奖金或提成发放",
)
db.add(exc6)
# 5. 为每个月创建上传文件
print("创建上传文件...")
files = []
for task, year, month in tasks:
# 工资表
salary_file = UploadedFile(
company_id=company.id,
task_id=task.id,
file_type=FileType.SALARY.value,
original_filename=f"{year}{month:02d}月工资表.xlsx",
stored_filename=f"salary_{task.id}_{year}{month:02d}.xlsx",
file_size=102400,
mime_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
parse_status=ParseStatus.SUCCESS.value,
)
db.add(salary_file)
# 社保表
social_file = UploadedFile(
company_id=company.id,
task_id=task.id,
file_type=FileType.SOCIAL_SECURITY.value,
original_filename=f"{year}{month:02d}月社保表.xlsx",
stored_filename=f"social_{task.id}_{year}{month:02d}.xlsx",
file_size=92160,
mime_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
parse_status=ParseStatus.SUCCESS.value,
)
db.add(social_file)
# 个税表
tax_file = UploadedFile(
company_id=company.id,
task_id=task.id,
file_type=FileType.TAX.value,
original_filename=f"{year}{month:02d}月个税表.xlsx",
stored_filename=f"tax_{task.id}_{year}{month:02d}.xlsx",
file_size=81920,
mime_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
parse_status=ParseStatus.SUCCESS.value,
)
db.add(tax_file)
await db.flush()
files.append((salary_file.id, social_file.id, tax_file.id))
# 6. 创建字段映射规则(关联到第一个文件作为示例)
print("创建字段映射规则...")
first_file_id = files[0][0] # 使用10月工资表的文件ID
field_mappings = [
("员工编号", "employee_id", 0.98),
("工号", "employee_id", 0.95),
("姓名", "employee_name", 0.99),
("员工姓名", "employee_name", 0.99),
("部门", "department", 0.97),
("所属部门", "department", 0.95),
("岗位", "position", 0.90),
("职位", "position", 0.90),
("基本工资", "base_salary", 0.98),
("岗位工资", "base_salary", 0.92),
("应发工资", "gross_salary", 0.96),
("实发工资", "net_salary", 0.97),
("税前工资", "gross_salary", 0.93),
("养老保险", "pension", 0.95),
("医疗保险", "medical", 0.95),
("社保", "social_security", 0.90),
("公积金", "housing_fund", 0.95),
("个税", "personal_income_tax", 0.98),
("个人所得税", "personal_income_tax", 0.98),
]
for source, standard, confidence in field_mappings:
mapping = FieldMapping(
company_id=company.id,
file_id=first_file_id,
source_field=source,
standard_field=standard,
confidence=confidence,
confirmed=True,
confirmed_by=admin_user.id,
confirmed_at=datetime.utcnow(),
)
db.add(mapping)
await db.commit()
print("示例数据创建成功!")
print("\n" + "="*50)
print("登录信息:")
print("="*50)
for user_data in USERS_DATA:
print(f" 邮箱: {user_data['email']}")
print(f" 密码: {user_data['password']}")
print(f" 角色: {user_data['role']}")
print("-"*30)
print("\n包含 3 个月(4月、5月、6月)的对账数据")
print("共 25 名员工,多种异常场景")
except Exception as e:
await db.rollback()
print(f"创建示例数据失败: {e}")
raise
if __name__ == "__main__":
import asyncio
asyncio.run(init_sample_data())
+269
View File
@@ -0,0 +1,269 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { motion } from "motion/react";
import { Eye, EyeOff, Lock, Mail, AlertCircle, UserCircle } from "lucide-react";
import { useAuthStore } from "@/lib/stores/auth-store";
import { api } from "@/lib/api/client";
import ENDPOINTS from "@/lib/api/endpoints";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { cn } from "@/lib/utils";
const loginSchema = z.object({
email: z.string().email("请输入有效的邮箱地址"),
password: z.string().min(6, "密码至少6个字符"),
});
type LoginFormData = z.infer<typeof loginSchema>;
// 测试用户数据
const TEST_USERS = [
{ name: "管理员", email: "admin@xingchen.com", password: "admin123", role: "管理员" },
{ name: "财务主管", email: "finance@xingchen.com", password: "finance123", role: "财务主管" },
{ name: "会计", email: "accountant@xingchen.com", password: "account123", role: "会计" },
];
export default function LoginPage() {
const router = useRouter();
const { login } = useAuthStore();
const [error, setError] = useState<string>("");
const [loading, setLoading] = useState(false);
const [showPassword, setShowPassword] = useState(false);
// onSubmit 必须在 handleSubmit 之前定义
const onSubmit = async (data: LoginFormData) => {
setLoading(true);
setError("");
try {
const response = await api.post(ENDPOINTS.AUTH.LOGIN, data);
const { access_token, user } = response.data;
// 保存到 localStorage
login(user, access_token);
// 设置 cookie
document.cookie = `auth_token=${access_token}; path=/; max-age=86400; SameSite=Lax`;
document.cookie = `company_id=${user.company_id}; path=/; max-age=86400; SameSite=Lax`;
// 直接跳转
router.push("/dashboard");
} catch (err: unknown) {
const error = err as { message?: string };
setError(error.message || "登录失败,请检查邮箱和密码");
} finally {
setLoading(false);
}
};
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm<LoginFormData>({
resolver: zodResolver(loginSchema),
});
// 快速填充测试用户
const fillTestUser = (email: string, password: string) => {
setValue("email", email);
setValue("password", password);
setError("");
};
return (
<div className="min-h-screen flex items-center justify-center p-4 bg-gradient-to-br from-background via-background to-muted/30">
{/* Background decoration */}
<div className="fixed inset-0 overflow-hidden pointer-events-none">
<div className="absolute top-1/4 -left-1/4 w-1/2 h-1/2 bg-primary/5 rounded-full blur-3xl" />
<div className="absolute bottom-1/4 -right-1/4 w-1/2 h-1/2 bg-primary/3 rounded-full blur-3xl" />
</div>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, ease: [0.16, 1, 0.3, 1] as const }}
className="w-full max-w-md relative z-10"
>
{/* Logo & Title */}
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.1, ease: [0.16, 1, 0.3, 1] as const }}
className="text-center mb-8"
>
<div className="inline-flex items-center justify-center w-14 h-14 rounded-xl bg-primary/10 mb-4">
<Lock className="w-7 h-7 text-primary" />
</div>
<h1 className="text-heading-1 text-foreground mb-2">AI助手</h1>
<p className="text-muted-foreground">AI助手</p>
</motion.div>
<Card className="shadow-lg border-muted">
<CardContent className="p-8">
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3, delay: 0.2 }}
>
<h2 className="text-heading-2 text-foreground mb-6 text-center">
</h2>
</motion.div>
{/* 测试用户快捷登录 */}
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.25 }}
className="mb-6 p-4 rounded-lg bg-muted/30 border border-border"
>
<div className="flex items-center gap-2 mb-3">
<UserCircle className="w-4 h-4 text-muted-foreground" />
<span className="text-body-small text-muted-foreground"></span>
</div>
<div className="grid grid-cols-3 gap-2">
{TEST_USERS.map((user) => (
<button
key={user.email}
type="button"
onClick={() => fillTestUser(user.email, user.password)}
className="flex flex-col items-center p-2 rounded-lg bg-background hover:bg-primary/5 border border-border hover:border-primary/30 transition-all text-left"
>
<span className="text-body-small font-medium text-foreground">{user.name}</span>
<span className="text-caption text-muted-foreground truncate w-full text-center">{user.email}</span>
</button>
))}
</div>
</motion.div>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
{/* Error Alert */}
{error && (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
className="flex items-start gap-3 p-4 rounded-lg bg-destructive/10 border border-destructive/20"
>
<AlertCircle className="w-5 h-5 text-destructive shrink-0 mt-0.5" />
<p className="text-sm text-destructive">{error}</p>
</motion.div>
)}
{/* Email Field */}
<div className="space-y-2">
<label htmlFor="email" className="text-body-small font-medium text-foreground">
</label>
<div className="relative">
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
{...register("email")}
type="email"
id="email"
placeholder="your@email.com"
className={cn(
"pl-10 h-11 transition-all",
errors.email && "border-destructive focus:ring-destructive/20"
)}
/>
</div>
{errors.email && (
<p className="text-caption text-destructive">{errors.email.message}</p>
)}
</div>
{/* Password Field */}
<div className="space-y-2">
<label htmlFor="password" className="text-body-small font-medium text-foreground">
</label>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
{...register("password")}
type={showPassword ? "text" : "password"}
id="password"
placeholder="输入密码"
className={cn(
"pl-10 pr-10 h-11 transition-all",
errors.password && "border-destructive focus:ring-destructive/20"
)}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
>
{showPassword ? (
<EyeOff className="w-4 h-4" />
) : (
<Eye className="w-4 h-4" />
)}
</button>
</div>
{errors.password && (
<p className="text-caption text-destructive">{errors.password.message}</p>
)}
</div>
{/* Submit Button */}
<Button
type="submit"
disabled={loading}
className="w-full h-11 text-body font-medium btn-press"
>
{loading ? (
<span className="flex items-center gap-2">
<svg className="animate-spin w-4 h-4" viewBox="0 0 24 24">
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
fill="none"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
...
</span>
) : (
"登录"
)}
</Button>
</form>
{/* Footer */}
<p className="text-caption text-muted-foreground text-center mt-6">
</p>
</CardContent>
</Card>
{/* Help Text */}
<motion.p
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3, delay: 0.4 }}
className="text-caption text-muted-foreground text-center mt-6"
>
</motion.p>
</motion.div>
</div>
);
}
+397
View File
@@ -0,0 +1,397 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { motion } from "motion/react";
import {
FileText,
AlertTriangle,
CheckCircle,
TrendingUp,
Clock,
ArrowRight,
Loader2
} from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useRouter } from "next/navigation";
import { api } from "@/lib/api/client";
import ENDPOINTS from "@/lib/api/endpoints";
interface TaskStats {
monthly_tasks: number;
pending_exceptions: number;
completed_tasks: number;
match_rate: number;
current_period: string;
}
interface Task {
id: number;
period: string;
status: string;
total_employees: number;
matched_count: number;
exception_count: number;
created_at: string;
completed_at: string | null;
}
const statusLabels: Record<string, { label: string; color: string }> = {
PENDING: { label: "待处理", color: "bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300" },
PROCESSING: { label: "处理中", color: "bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300" },
MAPPING_COMPLETED: { label: "映射完成", color: "bg-amber-100 text-amber-700 dark:bg-amber-900/50 dark:text-amber-300" },
COMPLETED: { label: "已完成", color: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/50 dark:text-emerald-300" },
FAILED: { label: "失败", color: "bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300" },
};
const container = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: {
staggerChildren: 0.08,
delayChildren: 0.1,
},
},
};
const item = {
hidden: { opacity: 0, y: 12 },
show: {
opacity: 1,
y: 0,
transition: {
duration: 0.4,
ease: [0.16, 1, 0.3, 1] as const,
},
},
};
export default function DashboardPage() {
const router = useRouter();
const [stats, setStats] = useState<TaskStats | null>(null);
const [recentTasks, setRecentTasks] = useState<Task[]>([]);
const [loading, setLoading] = useState(true);
const loadDashboardData = useCallback(async () => {
setLoading(true);
try {
// 并行获取统计数据和任务列表
const [statsRes, tasksRes] = await Promise.all([
api.get<TaskStats>(ENDPOINTS.TASK.STATS),
api.get<Task[]>(ENDPOINTS.TASK.LIST, { params: { limit: 5 } }),
]);
setStats(statsRes.data);
setRecentTasks(tasksRes.data);
} catch (error) {
console.error("加载数据失败:", error);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
loadDashboardData();
}, [loadDashboardData]);
const formatPeriod = (period: string) => {
const [year, month] = period.split("-");
return `${year}${parseInt(month)}`;
};
return (
<div className="min-h-full p-6 lg:p-8 max-w-7xl mx-auto">
{/* Header */}
<motion.div
initial={{ opacity: 0, y: -8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] as const }}
className="mb-8"
>
<h1 className="text-heading-1 text-foreground mb-2"></h1>
<p className="text-muted-foreground text-body">
</p>
</motion.div>
{loading ? (
<div className="flex items-center justify-center py-20">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
</div>
) : (
<>
{/* Stats Grid */}
<motion.div
variants={container}
initial="hidden"
animate="show"
className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8"
>
<motion.div variants={item}>
<Card className="relative overflow-hidden hover-lift">
<CardContent className="p-5">
<div className="flex items-start justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide mb-1">
</p>
<p className="text-3xl font-semibold tracking-tight text-foreground">
{stats?.monthly_tasks ?? 0}
</p>
<div className="flex items-center gap-1 mt-2">
<Clock className="w-3 h-3 text-muted-foreground" />
<span className="text-caption text-muted-foreground">
{stats?.current_period ? formatPeriod(stats.current_period) : "-"}
</span>
</div>
</div>
<div className="p-2.5 rounded-lg bg-blue-50 dark:bg-blue-950/30">
<FileText className="w-5 h-5 text-blue-600" />
</div>
</div>
</CardContent>
<div className="absolute inset-x-0 bottom-0 h-0.5 bg-blue-50 dark:bg-blue-950/30 opacity-50" />
</Card>
</motion.div>
<motion.div variants={item}>
<Card className="relative overflow-hidden hover-lift">
<CardContent className="p-5">
<div className="flex items-start justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide mb-1">
</p>
<p className="text-3xl font-semibold tracking-tight text-foreground">
{stats?.pending_exceptions ?? 0}
</p>
<div className="flex items-center gap-1 mt-2">
<AlertTriangle className="w-3 h-3 text-amber-500" />
<span className="text-caption text-muted-foreground">
</span>
</div>
</div>
<div className="p-2.5 rounded-lg bg-amber-50 dark:bg-amber-950/30">
<AlertTriangle className="w-5 h-5 text-amber-600" />
</div>
</div>
</CardContent>
<div className="absolute inset-x-0 bottom-0 h-0.5 bg-amber-50 dark:bg-amber-950/30 opacity-50" />
</Card>
</motion.div>
<motion.div variants={item}>
<Card className="relative overflow-hidden hover-lift">
<CardContent className="p-5">
<div className="flex items-start justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide mb-1">
</p>
<p className="text-3xl font-semibold tracking-tight text-foreground">
{stats?.completed_tasks ?? 0}
</p>
<div className="flex items-center gap-1 mt-2">
<CheckCircle className="w-3 h-3 text-emerald-500" />
<span className="text-caption text-muted-foreground">
</span>
</div>
</div>
<div className="p-2.5 rounded-lg bg-emerald-50 dark:bg-emerald-950/30">
<CheckCircle className="w-5 h-5 text-emerald-600" />
</div>
</div>
</CardContent>
<div className="absolute inset-x-0 bottom-0 h-0.5 bg-emerald-50 dark:bg-emerald-950/30 opacity-50" />
</Card>
</motion.div>
<motion.div variants={item}>
<Card className="relative overflow-hidden hover-lift">
<CardContent className="p-5">
<div className="flex items-start justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide mb-1">
</p>
<p className="text-3xl font-semibold tracking-tight text-foreground">
{stats?.match_rate ?? 0}%
</p>
<div className="flex items-center gap-1 mt-2">
<TrendingUp className="w-3 h-3 text-violet-500" />
<span className="text-caption text-muted-foreground">
</span>
</div>
</div>
<div className="p-2.5 rounded-lg bg-violet-50 dark:bg-violet-950/30">
<TrendingUp className="w-5 h-5 text-violet-600" />
</div>
</div>
</CardContent>
<div className="absolute inset-x-0 bottom-0 h-0.5 bg-violet-50 dark:bg-violet-950/30 opacity-50" />
</Card>
</motion.div>
</motion.div>
{/* Recent Tasks */}
<motion.div
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay: 0.3, ease: [0.16, 1, 0.3, 1] as const }}
className="mb-8"
>
<div className="flex items-center justify-between mb-4">
<h2 className="text-heading-3 text-foreground"></h2>
<Button
variant="ghost"
size="sm"
onClick={() => router.push("/tasks")}
>
<ArrowRight className="w-4 h-4 ml-1" />
</Button>
</div>
{recentTasks.length === 0 ? (
<Card>
<CardContent className="p-8 text-center">
<div className="w-12 h-12 rounded-full bg-muted mx-auto mb-4 flex items-center justify-center">
<FileText className="w-6 h-6 text-muted-foreground" />
</div>
<p className="text-body text-muted-foreground mb-2">
</p>
<p className="text-caption text-muted-foreground">
使
</p>
<Button
className="mt-4 btn-press"
onClick={() => router.push("/tasks/new")}
>
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
</CardContent>
</Card>
) : (
<div className="space-y-3">
{recentTasks.map((task, index) => (
<motion.div
key={task.id}
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{
duration: 0.3,
delay: 0.1 + index * 0.05,
}}
>
<Card
className="cursor-pointer hover-lift transition-all"
onClick={() => router.push(`/tasks/${task.id}/result`)}
>
<CardContent className="p-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="p-2.5 rounded-lg bg-muted">
<FileText className="w-5 h-5 text-muted-foreground" />
</div>
<div>
<div className="flex items-center gap-2 mb-1">
<h3 className="font-medium text-foreground">
{formatPeriod(task.period)}
</h3>
<span className={`px-2 py-0.5 rounded text-xs font-medium ${statusLabels[task.status]?.color || statusLabels.PENDING.color}`}>
{statusLabels[task.status]?.label || task.status}
</span>
</div>
<p className="text-caption text-muted-foreground">
{task.total_employees} · {task.matched_count} · {task.exception_count}
</p>
</div>
</div>
<ArrowRight className="w-4 h-4 text-muted-foreground" />
</CardContent>
</Card>
</motion.div>
))}
</div>
)}
</motion.div>
{/* Quick Actions */}
<motion.div
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay: 0.4, ease: [0.16, 1, 0.3, 1] as const }}
>
<h2 className="text-heading-3 text-foreground mb-4"></h2>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card
className="group cursor-pointer hover-lift"
onClick={() => router.push("/tasks/new")}
>
<CardContent className="p-5 flex items-start gap-4">
<div className="p-2.5 rounded-lg bg-muted group-hover:bg-primary/10 transition-colors">
<FileText className="w-5 h-5 text-muted-foreground group-hover:text-primary transition-colors" />
</div>
<div className="flex-1 min-w-0">
<h3 className="font-medium text-foreground mb-1 group-hover:text-primary transition-colors">
</h3>
<p className="text-caption text-muted-foreground">
</p>
</div>
<ArrowRight className="w-4 h-4 text-muted-foreground group-hover:text-primary group-hover:translate-x-1 transition-all self-center" />
</CardContent>
</Card>
<Card
className="group cursor-pointer hover-lift"
onClick={() => router.push("/exceptions")}
>
<CardContent className="p-5 flex items-start gap-4">
<div className="p-2.5 rounded-lg bg-muted group-hover:bg-amber-500/10 transition-colors">
<AlertTriangle className="w-5 h-5 text-muted-foreground group-hover:text-amber-500 transition-colors" />
</div>
<div className="flex-1 min-w-0">
<h3 className="font-medium text-foreground mb-1 group-hover:text-amber-500 transition-colors">
</h3>
<p className="text-caption text-muted-foreground">
</p>
</div>
<ArrowRight className="w-4 h-4 text-muted-foreground group-hover:text-amber-500 group-hover:translate-x-1 transition-all self-center" />
</CardContent>
</Card>
<Card
className="group cursor-pointer hover-lift"
onClick={() => router.push("/settings/rules")}
>
<CardContent className="p-5 flex items-start gap-4">
<div className="p-2.5 rounded-lg bg-muted group-hover:bg-violet-500/10 transition-colors">
<TrendingUp className="w-5 h-5 text-muted-foreground group-hover:text-violet-500 transition-colors" />
</div>
<div className="flex-1 min-w-0">
<h3 className="font-medium text-foreground mb-1 group-hover:text-violet-500 transition-colors">
</h3>
<p className="text-caption text-muted-foreground">
</p>
</div>
<ArrowRight className="w-4 h-4 text-muted-foreground group-hover:text-violet-500 group-hover:translate-x-1 transition-all self-center" />
</CardContent>
</Card>
</div>
</motion.div>
</>
)}
</div>
);
}
@@ -0,0 +1,630 @@
"use client";
import { Suspense, useState, useEffect } from "react";
import { useSearchParams } from "next/navigation";
import { motion } from "motion/react";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
AlertTriangle,
CheckCircle,
Clock,
Eye,
Search,
XCircle,
} from "lucide-react";
import { api } from "@/lib/api/client";
interface ExceptionItem {
id: number;
task_id: number;
exception_type: string;
severity: "low" | "medium" | "high" | "critical";
status: "pending" | "processing" | "resolved" | "ignored";
employee_id: string;
employee_name: string;
description: string;
detail: string | null;
salary_amount: number | null;
social_security_amount: number | null;
tax_amount: number | null;
bank_amount: number | null;
difference_amount: number | null;
resolution: string | null;
handler: string | null;
note: string | null;
suggested_action: string | null;
created_at: string;
updated_at: string | null;
}
interface Summary {
by_status: Record<string, number>;
by_severity: Record<string, number>;
by_type: Record<string, number>;
}
const severityConfig = {
low: { label: "低", color: "bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300", icon: "bg-blue-500" },
medium: { label: "中", color: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/40 dark:text-yellow-300", icon: "bg-yellow-500" },
high: { label: "高", color: "bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300", icon: "bg-orange-500" },
critical: { label: "严重", color: "bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300", icon: "bg-red-500" },
};
const statusConfig = {
pending: { label: "待处理", color: "bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300" },
processing: { label: "处理中", color: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/40 dark:text-yellow-300" },
confirmed: { label: "已确认", color: "bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300" },
resolved: { label: "已解决", color: "bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300" },
ignored: { label: "已忽略", color: "bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-500" },
};
const typeLabels: Record<string, string> = {
amount_mismatch: "金额不一致",
missing_record: "记录缺失",
duplicate_record: "重复记录",
format_error: "格式错误",
logic_error: "逻辑错误",
};
const container = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: { staggerChildren: 0.06 },
},
};
const item = {
hidden: { opacity: 0, y: 8 },
show: { opacity: 1, y: 0, transition: { duration: 0.3, ease: [0.16, 1, 0.3, 1] as const } },
};
function ExceptionsContent() {
const searchParams = useSearchParams();
const [exceptions, setExceptions] = useState<ExceptionItem[]>([]);
const [summary, setSummary] = useState<Summary | null>(null);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [taskId, setTaskId] = useState(searchParams.get("task_id") || "");
const [status, setStatus] = useState(searchParams.get("status") || "");
const [severity, setSeverity] = useState(searchParams.get("severity") || "");
const [exceptionType, setExceptionType] = useState(searchParams.get("type") || "");
const [page, setPage] = useState(Number(searchParams.get("page")) || 1);
const [pageSize] = useState(20);
const [selectedException, setSelectedException] = useState<ExceptionItem | null>(null);
const [detailOpen, setDetailOpen] = useState(false);
useEffect(() => {
fetchExceptions();
fetchSummary();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [taskId, status, severity, exceptionType, page]);
async function fetchExceptions() {
setLoading(true);
try {
const res = await api.get<{ items: ExceptionItem[]; total: number }>("/api/exceptions/", {
params: {
task_id: taskId || undefined,
status: status || undefined,
severity: severity || undefined,
exception_type: exceptionType || undefined,
page,
page_size: pageSize,
},
});
setExceptions(res.data.items || []);
setTotal(res.data.total || 0);
} catch (error) {
console.error("加载异常列表失败", error);
} finally {
setLoading(false);
}
}
async function fetchSummary() {
try {
const res = await api.get<Summary>("/api/exceptions/summary", {
params: { task_id: taskId || undefined },
});
setSummary(res.data);
} catch (error) {
console.error("加载汇总失败", error);
}
}
function handleSearch() {
setPage(1);
fetchExceptions();
fetchSummary();
}
function viewDetail(exception: ExceptionItem) {
setSelectedException(exception);
setDetailOpen(true);
}
async function updateStatus(id: number, newStatus: string) {
try {
await api.patch(`/api/exceptions/${id}`, { status: newStatus });
fetchExceptions();
fetchSummary();
} catch (error) {
console.error("更新状态失败", error);
}
}
const totalPages = Math.ceil(total / pageSize);
return (
<div className="min-h-full p-6 lg:p-8 max-w-7xl mx-auto space-y-6">
{/* Header */}
<motion.div
initial={{ opacity: 0, y: -8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }}
className="flex items-center justify-between"
>
<div>
<h1 className="text-heading-1 text-foreground"></h1>
<p className="text-muted-foreground mt-1"></p>
</div>
</motion.div>
{/* Summary Cards */}
{summary && (
<motion.div
variants={container}
initial="hidden"
animate="show"
className="grid grid-cols-2 lg:grid-cols-4 gap-4"
>
<motion.div variants={item}>
<Card className="hover-lift">
<CardContent className="p-5">
<div className="flex items-center justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide"></p>
<p className="text-2xl font-semibold mt-1">{summary.by_status?.pending || 0}</p>
</div>
<div className="p-2.5 rounded-lg bg-gray-100 dark:bg-gray-800">
<Clock className="w-5 h-5 text-gray-600 dark:text-gray-400" />
</div>
</div>
</CardContent>
</Card>
</motion.div>
<motion.div variants={item}>
<Card className="hover-lift">
<CardContent className="p-5">
<div className="flex items-center justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide"></p>
<p className="text-2xl font-semibold mt-1 text-amber-600">{summary.by_status?.processing || 0}</p>
</div>
<div className="p-2.5 rounded-lg bg-amber-50 dark:bg-amber-950/30">
<AlertTriangle className="w-5 h-5 text-amber-600" />
</div>
</div>
</CardContent>
</Card>
</motion.div>
<motion.div variants={item}>
<Card className="hover-lift">
<CardContent className="p-5">
<div className="flex items-center justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide"></p>
<p className="text-2xl font-semibold mt-1 text-emerald-600">{summary.by_status?.resolved || 0}</p>
</div>
<div className="p-2.5 rounded-lg bg-emerald-50 dark:bg-emerald-950/30">
<CheckCircle className="w-5 h-5 text-emerald-600" />
</div>
</div>
</CardContent>
</Card>
</motion.div>
<motion.div variants={item}>
<Card className="hover-lift">
<CardContent className="p-5">
<div className="flex items-center justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide"></p>
<p className="text-2xl font-semibold mt-1 text-red-600">{summary.by_severity?.critical || 0}</p>
</div>
<div className="p-2.5 rounded-lg bg-red-50 dark:bg-red-950/30">
<XCircle className="w-5 h-5 text-red-600" />
</div>
</div>
</CardContent>
</Card>
</motion.div>
</motion.div>
)}
{/* Filter Card */}
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.2, ease: [0.16, 1, 0.3, 1] }}
>
<Card>
<CardContent className="p-4">
<div className="flex flex-wrap items-end gap-3">
<div className="flex-1 min-w-[180px]">
<label className="text-caption text-muted-foreground mb-1.5 block">ID</label>
<div className="relative">
<Input
placeholder="输入任务ID"
value={taskId}
onChange={(e) => setTaskId(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSearch()}
className="h-9"
/>
</div>
</div>
<div className="w-[150px]">
<label className="text-caption text-muted-foreground mb-1.5 block"></label>
<Select value={status} onValueChange={setStatus}>
<SelectTrigger className="h-9">
<SelectValue placeholder="全部状态" />
</SelectTrigger>
<SelectContent>
<SelectItem value=""></SelectItem>
<SelectItem value="pending"></SelectItem>
<SelectItem value="processing"></SelectItem>
<SelectItem value="resolved"></SelectItem>
<SelectItem value="ignored"></SelectItem>
</SelectContent>
</Select>
</div>
<div className="w-[150px]">
<label className="text-caption text-muted-foreground mb-1.5 block"></label>
<Select value={severity} onValueChange={setSeverity}>
<SelectTrigger className="h-9">
<SelectValue placeholder="全部程度" />
</SelectTrigger>
<SelectContent>
<SelectItem value=""></SelectItem>
<SelectItem value="low"></SelectItem>
<SelectItem value="medium"></SelectItem>
<SelectItem value="high"></SelectItem>
<SelectItem value="critical"></SelectItem>
</SelectContent>
</Select>
</div>
<div className="w-[180px]">
<label className="text-caption text-muted-foreground mb-1.5 block"></label>
<Select value={exceptionType} onValueChange={setExceptionType}>
<SelectTrigger className="h-9">
<SelectValue placeholder="全部类型" />
</SelectTrigger>
<SelectContent>
<SelectItem value=""></SelectItem>
<SelectItem value="amount_mismatch"></SelectItem>
<SelectItem value="missing_record"></SelectItem>
<SelectItem value="duplicate_record"></SelectItem>
<SelectItem value="format_error"></SelectItem>
<SelectItem value="logic_error"></SelectItem>
</SelectContent>
</Select>
</div>
<Button onClick={handleSearch} className="h-9 btn-press">
<Search className="w-4 h-4 mr-2" />
</Button>
</div>
</CardContent>
</Card>
</motion.div>
{/* Exceptions Table */}
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.3, ease: [0.16, 1, 0.3, 1] }}
>
<Card>
<CardHeader className="pb-4">
<div className="flex items-center justify-between">
<CardTitle className="text-lg font-medium"></CardTitle>
<Badge variant="secondary">{total} </Badge>
</div>
</CardHeader>
<CardContent className="p-0">
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent">
<TableHead className="w-[100px]"></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="text-right"></TableHead>
<TableHead className="w-[100px]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={7} className="text-center py-12">
<div className="flex items-center justify-center gap-2 text-muted-foreground">
<svg className="animate-spin w-5 h-5" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
...
</div>
</TableCell>
</TableRow>
) : exceptions.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center py-12">
<div className="w-12 h-12 rounded-full bg-muted mx-auto mb-3 flex items-center justify-center">
<CheckCircle className="w-6 h-6 text-muted-foreground" />
</div>
<p className="text-foreground font-medium"></p>
<p className="text-caption text-muted-foreground mt-1"></p>
</TableCell>
</TableRow>
) : (
exceptions.map((exception, index) => (
<motion.div
key={exception.id}
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, delay: index * 0.02 }}
>
<TableRow className="group">
<TableCell>
<Badge className={statusConfig[exception.status]?.color || "bg-gray-100 text-gray-700"}>
{statusConfig[exception.status]?.label || exception.status}
</Badge>
</TableCell>
<TableCell>
<div>
<div className="font-medium">{exception.employee_name}</div>
<div className="text-xs text-muted-foreground">{exception.employee_id}</div>
</div>
</TableCell>
<TableCell>
<Badge variant="outline" className="font-normal">
{typeLabels[exception.exception_type] || exception.exception_type}
</Badge>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<div className={`w-2 h-2 rounded-full ${severityConfig[exception.severity]?.icon || "bg-gray-500"}`} />
<Badge className={severityConfig[exception.severity]?.color || "bg-gray-100 text-gray-700"}>
{severityConfig[exception.severity]?.label || exception.severity}
</Badge>
</div>
</TableCell>
<TableCell className="max-w-[200px]">
<span className="truncate block">{exception.description}</span>
</TableCell>
<TableCell className="text-right">
{exception.difference_amount != null && (
<span className={exception.difference_amount > 0 ? "text-red-600" : "text-emerald-600"}>
{exception.difference_amount > 0 ? "+" : ""}
{exception.difference_amount.toFixed(2)}
</span>
)}
</TableCell>
<TableCell>
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<Button variant="ghost" size="sm" onClick={() => viewDetail(exception)} className="h-8 w-8 p-0">
<Eye className="h-4 w-4" />
</Button>
{exception.status === "pending" && (
<Button variant="ghost" size="sm" onClick={() => updateStatus(exception.id, "processing")} className="h-8 px-2">
</Button>
)}
{exception.status === "processing" && (
<Button variant="ghost" size="sm" onClick={() => updateStatus(exception.id, "resolved")} className="h-8 px-2">
</Button>
)}
</div>
</TableCell>
</TableRow>
</motion.div>
))
)}
</TableBody>
</Table>
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between px-6 py-4 border-t">
<p className="text-caption text-muted-foreground">
{page} {totalPages}
</p>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={page <= 1}
onClick={() => setPage(page - 1)}
className="btn-press"
>
</Button>
<Button
variant="outline"
size="sm"
disabled={page >= totalPages}
onClick={() => setPage(page + 1)}
className="btn-press"
>
</Button>
</div>
</div>
)}
</CardContent>
</Card>
</motion.div>
{/* Detail Dialog */}
<Dialog open={detailOpen} onOpenChange={setDetailOpen}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
{selectedException && (
<div className="space-y-6">
<div className="grid grid-cols-2 gap-4">
<div>
<p className="text-caption text-muted-foreground"></p>
<p className="font-medium">{selectedException.employee_name}</p>
</div>
<div>
<p className="text-caption text-muted-foreground">ID</p>
<p className="font-medium">{selectedException.employee_id}</p>
</div>
<div>
<p className="text-caption text-muted-foreground"></p>
<Badge variant="outline">{typeLabels[selectedException.exception_type] || selectedException.exception_type}</Badge>
</div>
<div>
<p className="text-caption text-muted-foreground"></p>
<div className="flex items-center gap-2">
<div className={`w-2 h-2 rounded-full ${severityConfig[selectedException.severity]?.icon || "bg-gray-500"}`} />
<Badge className={severityConfig[selectedException.severity]?.color || "bg-gray-100 text-gray-700"}>
{severityConfig[selectedException.severity]?.label || selectedException.severity}
</Badge>
</div>
</div>
</div>
<div className="border-t pt-4">
<h4 className="font-medium mb-3"></h4>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{selectedException.salary_amount != null && (
<div className="p-3 rounded-lg bg-muted/50">
<p className="text-caption text-muted-foreground"></p>
<p className="font-mono font-medium mt-1">{selectedException.salary_amount.toFixed(2)}</p>
</div>
)}
{selectedException.social_security_amount != null && (
<div className="p-3 rounded-lg bg-muted/50">
<p className="text-caption text-muted-foreground"></p>
<p className="font-mono font-medium mt-1">{selectedException.social_security_amount.toFixed(2)}</p>
</div>
)}
{selectedException.tax_amount != null && (
<div className="p-3 rounded-lg bg-muted/50">
<p className="text-caption text-muted-foreground"></p>
<p className="font-mono font-medium mt-1">{selectedException.tax_amount.toFixed(2)}</p>
</div>
)}
{selectedException.bank_amount != null && (
<div className="p-3 rounded-lg bg-muted/50">
<p className="text-caption text-muted-foreground"></p>
<p className="font-mono font-medium mt-1">{selectedException.bank_amount.toFixed(2)}</p>
</div>
)}
</div>
{selectedException.difference_amount != null && (
<div className="mt-4 p-4 rounded-lg bg-muted/50">
<p className="text-caption text-muted-foreground"></p>
<p className={`text-2xl font-mono font-semibold mt-1 ${selectedException.difference_amount > 0 ? "text-red-600" : "text-emerald-600"}`}>
{selectedException.difference_amount > 0 ? "+" : ""}
{selectedException.difference_amount.toFixed(2)}
</p>
</div>
)}
</div>
<div className="border-t pt-4">
<div className="space-y-3">
<div>
<p className="text-caption text-muted-foreground mb-1"></p>
<p>{selectedException.description}</p>
</div>
{selectedException.detail && (
<div>
<p className="text-caption text-muted-foreground mb-1"></p>
<pre className="text-xs bg-muted p-3 rounded-lg overflow-auto">
{JSON.stringify(JSON.parse(selectedException.detail), null, 2)}
</pre>
</div>
)}
{selectedException.suggested_action && (
<div>
<p className="text-caption text-muted-foreground mb-1"></p>
<p>{selectedException.suggested_action}</p>
</div>
)}
</div>
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
);
}
function LoadingFallback() {
return (
<div className="min-h-full p-6 lg:p-8 flex items-center justify-center">
<div className="flex items-center gap-2 text-muted-foreground">
<svg className="animate-spin w-5 h-5" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
...
</div>
</div>
);
}
export default function ExceptionsPage() {
return (
<Suspense fallback={<LoadingFallback />}>
<ExceptionsContent />
</Suspense>
);
}
+20
View File
@@ -0,0 +1,20 @@
import { Header } from "@/components/layout/Header";
import { Sidebar } from "@/components/layout/Sidebar";
export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="min-h-screen bg-background">
<Header />
<div className="flex">
<Sidebar />
<main className="flex-1 min-h-[calc(100vh-3.5rem)]">
{children}
</main>
</div>
</div>
);
}
@@ -0,0 +1,324 @@
"use client";
import { useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { ArrowLeft, Trash2, ToggleLeft, ToggleRight, Search } from "lucide-react";
import { api } from "@/lib/api/client";
import { ENDPOINTS } from "@/lib/api/endpoints";
import { useToast } from "@/lib/hooks/useToast";
import type { CompanyRuleResponse } from "@/lib/api/types";
// 模拟数据
const mockRules: CompanyRuleResponse[] = [
{
id: 1,
company_id: 1,
rule_type: "FIELD_MAPPING",
match_condition: { source_field: "员工姓名" },
target_value: "员工姓名",
priority: 0,
status: "ACTIVE",
description: "工资表员工姓名字段映射",
match_count: 15,
last_used_at: "2024-01-15T10:30:00Z",
created_at: "2024-01-01T00:00:00Z",
updated_at: "2024-01-15T10:30:00Z",
},
{
id: 2,
company_id: 1,
rule_type: "FIELD_MAPPING",
match_condition: { source_field: "基本薪资" },
target_value: "基本工资",
priority: 0,
status: "ACTIVE",
description: "工资表基本薪资字段映射",
match_count: 12,
last_used_at: "2024-01-15T10:30:00Z",
created_at: "2024-01-05T00:00:00Z",
updated_at: "2024-01-15T10:30:00Z",
},
{
id: 3,
company_id: 1,
rule_type: "FIELD_MAPPING",
match_condition: { source_field: "实发合计" },
target_value: "实发工资",
priority: 1,
status: "INACTIVE",
description: "工资表实发合计字段映射(已停用)",
match_count: 8,
last_used_at: "2024-01-10T00:00:00Z",
created_at: "2024-01-08T00:00:00Z",
updated_at: "2024-01-12T00:00:00Z",
},
];
const RULE_TYPE_LABELS: Record<string, string> = {
FIELD_MAPPING: "字段映射",
ACCOUNT_MAPPING: "科目映射",
DEPARTMENT_MAPPING: "部门映射",
};
export default function RulesPage() {
const router = useRouter();
const toast = useToast();
const [rules, setRules] = useState<CompanyRuleResponse[]>(mockRules);
const [searchQuery, setSearchQuery] = useState("");
const [typeFilter, setTypeFilter] = useState<string>("");
const [statusFilter, setStatusFilter] = useState<string>("");
// 过滤规则
const filteredRules = rules.filter((rule) => {
const matchesSearch =
!searchQuery ||
rule.match_condition.source_field?.toLowerCase().includes(searchQuery.toLowerCase()) ||
rule.target_value.toLowerCase().includes(searchQuery.toLowerCase()) ||
rule.description?.toLowerCase().includes(searchQuery.toLowerCase());
const matchesType = !typeFilter || rule.rule_type === typeFilter;
const matchesStatus = !statusFilter || rule.status === statusFilter;
return matchesSearch && matchesType && matchesStatus;
});
// 切换规则状态
const handleToggleStatus = useCallback(
async (ruleId: number, currentStatus: string) => {
const newStatus = currentStatus === "ACTIVE" ? "INACTIVE" : "ACTIVE";
try {
await api.patch(ENDPOINTS.MAPPING.RULE_STATUS(ruleId), {
status: newStatus,
});
setRules((prev) =>
prev.map((rule) =>
rule.id === ruleId ? { ...rule, status: newStatus } : rule
)
);
toast.success(`规则已${newStatus === "ACTIVE" ? "启用" : "停用"}`);
} catch {
toast.error("状态更新失败");
}
},
[toast]
);
// 删除规则
const handleDeleteRule = useCallback(
async (ruleId: number) => {
if (!confirm("确定要删除这条规则吗?")) return;
try {
await api.delete(ENDPOINTS.MAPPING.RULE_DELETE(ruleId));
setRules((prev) => prev.filter((rule) => rule.id !== ruleId));
toast.success("规则已删除");
} catch {
toast.error("删除失败");
}
},
[toast]
);
const activeCount = rules.filter((r) => r.status === "ACTIVE").length;
const inactiveCount = rules.filter((r) => r.status === "INACTIVE").length;
return (
<div className="p-6 max-w-7xl mx-auto">
{/* 页面头部 */}
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-4">
<button
onClick={() => router.push("/dashboard")}
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg"
>
<ArrowLeft className="w-5 h-5" />
</button>
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
</h1>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
</p>
</div>
</div>
</div>
{/* 统计卡片 */}
<div className="grid grid-cols-3 gap-4 mb-6">
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
<div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
{rules.length}
</div>
<div className="text-sm text-gray-500 dark:text-gray-400"></div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
<div className="text-2xl font-bold text-green-600">{activeCount}</div>
<div className="text-sm text-gray-500 dark:text-gray-400"></div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
<div className="text-2xl font-bold text-gray-400">{inactiveCount}</div>
<div className="text-sm text-gray-500 dark:text-gray-400"></div>
</div>
</div>
{/* 筛选栏 */}
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 mb-6">
<div className="flex items-center gap-4">
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<input
type="text"
placeholder="搜索规则..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-10 pr-4 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value)}
className="px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value=""></option>
<option value="FIELD_MAPPING"></option>
<option value="ACCOUNT_MAPPING"></option>
<option value="DEPARTMENT_MAPPING"></option>
</select>
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value=""></option>
<option value="ACTIVE"></option>
<option value="INACTIVE"></option>
</select>
</div>
</div>
{/* 规则列表 */}
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-gray-50 dark:bg-gray-900/50">
<tr>
<th className="px-4 py-3 text-left font-medium text-gray-600 dark:text-gray-400">
</th>
<th className="px-4 py-3 text-left font-medium text-gray-600 dark:text-gray-400">
</th>
<th className="px-4 py-3 text-left font-medium text-gray-600 dark:text-gray-400">
</th>
<th className="px-4 py-3 text-center font-medium text-gray-600 dark:text-gray-400">
</th>
<th className="px-4 py-3 text-center font-medium text-gray-600 dark:text-gray-400">
</th>
<th className="px-4 py-3 text-center font-medium text-gray-600 dark:text-gray-400">
使
</th>
<th className="px-4 py-3 text-right font-medium text-gray-600 dark:text-gray-400">
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
{filteredRules.map((rule) => (
<tr
key={rule.id}
className="hover:bg-gray-50 dark:hover:bg-gray-900/50 transition-colors"
>
<td className="px-4 py-3">
<span className="px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 rounded text-xs">
{RULE_TYPE_LABELS[rule.rule_type] || rule.rule_type}
</span>
</td>
<td className="px-4 py-3 font-medium text-gray-900 dark:text-gray-100">
{rule.match_condition.source_field || JSON.stringify(rule.match_condition)}
</td>
<td className="px-4 py-3 text-gray-700 dark:text-gray-300">
{rule.target_value}
</td>
<td className="px-4 py-3 text-center text-gray-500 dark:text-gray-400">
{rule.match_count}
</td>
<td className="px-4 py-3 text-center">
<span
className={`px-2 py-1 rounded text-xs ${
rule.status === "ACTIVE"
? "bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400"
: "bg-gray-100 dark:bg-gray-700 text-gray-500"
}`}
>
{rule.status === "ACTIVE" ? "启用" : "停用"}
</span>
</td>
<td className="px-4 py-3 text-center text-gray-500 dark:text-gray-400">
{rule.last_used_at
? new Date(rule.last_used_at).toLocaleDateString("zh-CN")
: "-"}
</td>
<td className="px-4 py-3 text-right">
<div className="flex items-center justify-end gap-2">
<button
onClick={() => handleToggleStatus(rule.id, rule.status)}
className={`p-1 rounded transition-colors ${
rule.status === "ACTIVE"
? "text-green-600 hover:bg-green-50 dark:hover:bg-green-900/30"
: "text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"
}`}
title={rule.status === "ACTIVE" ? "停用" : "启用"}
>
{rule.status === "ACTIVE" ? (
<ToggleRight className="w-5 h-5" />
) : (
<ToggleLeft className="w-5 h-5" />
)}
</button>
<button
onClick={() => handleDeleteRule(rule.id)}
className="p-1 text-red-500 hover:bg-red-50 dark:hover:bg-red-900/30 rounded transition-colors"
title="删除"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
{filteredRules.length === 0 && (
<div className="px-4 py-12 text-center text-gray-500 dark:text-gray-400">
</div>
)}
</div>
{/* 说明 */}
<div className="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
<h3 className="font-medium text-blue-800 dark:text-blue-300 mb-2">
</h3>
<ul className="text-sm text-blue-700 dark:text-blue-400 space-y-1">
<li> </li>
<li> </li>
<li> </li>
<li> </li>
</ul>
</div>
</div>
);
}
@@ -0,0 +1,624 @@
"use client";
import { useState, useCallback } from "react";
import { useParams, useRouter } from "next/navigation";
import { motion } from "motion/react";
import { ArrowLeft, CheckCircle, Loader2, FileSpreadsheet } from "lucide-react";
import { api } from "@/lib/api/client";
import { ENDPOINTS } from "@/lib/api/endpoints";
import { useToast } from "@/lib/hooks/useToast";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { FieldMappingTable } from "@/components/mapping/FieldMappingTable";
import { AISuggestionPanel } from "@/components/mapping/AISuggestionPanel";
import type { TaskMappingOverview } from "@/lib/api/types";
// 模拟数据(实际应从 API 获取)
const mockMappingData: TaskMappingOverview = {
task_id: 1,
total_files: 3,
total_fields: 18,
confirmed_fields: 5,
needs_review: true,
files: [
{
file_id: 1,
file_type: "工资表",
file_name: "2024年1月工资表.xlsx",
total_fields: 6,
confirmed_fields: 2,
high_confidence: 4,
medium_confidence: 1,
low_confidence: 1,
mappings: [
{
id: 1,
company_id: 1,
file_id: 1,
source_field: "员工姓名",
standard_field: "员工姓名",
confidence: 1.0,
reasoning: "字段名完全匹配",
sample_values: ["张三", "李四", "王五"],
is_skipped: false,
confirmed: true,
confirmed_by: 1,
confirmed_at: new Date().toISOString(),
},
{
id: 2,
company_id: 1,
file_id: 1,
source_field: "工号",
standard_field: "工号",
confidence: 1.0,
reasoning: "字段名完全匹配",
sample_values: ["EMP001", "EMP002"],
is_skipped: false,
confirmed: true,
confirmed_by: 1,
confirmed_at: new Date().toISOString(),
},
{
id: 3,
company_id: 1,
file_id: 1,
source_field: "基本薪资",
standard_field: "基本工资",
confidence: 0.85,
reasoning: "字段名相似,样例值验证为数值类型",
sample_values: [8000, 10000, 12000],
is_skipped: false,
confirmed: false,
},
{
id: 4,
company_id: 1,
file_id: 1,
source_field: "岗位津贴",
standard_field: "补贴",
confidence: 0.75,
reasoning: "字段名包含关键词:'津贴'",
sample_values: [500, 800, 1000],
is_skipped: false,
confirmed: false,
},
{
id: 5,
company_id: 1,
file_id: 1,
source_field: "实发合计",
standard_field: "实发工资",
confidence: 0.6,
reasoning: "字段名部分匹配,需要确认",
sample_values: [8500, 10800, 13000],
is_skipped: false,
confirmed: false,
},
{
id: 6,
company_id: 1,
file_id: 1,
source_field: "备注",
standard_field: "",
confidence: 0.0,
reasoning: "无法识别字段类型",
sample_values: ["正常", "补发"],
is_skipped: false,
confirmed: false,
},
],
},
{
file_id: 2,
file_type: "社保表",
file_name: "2024年1月社保表.xlsx",
total_fields: 6,
confirmed_fields: 2,
high_confidence: 3,
medium_confidence: 2,
low_confidence: 1,
mappings: [
{
id: 7,
company_id: 1,
file_id: 2,
source_field: "姓名",
standard_field: "员工姓名",
confidence: 0.95,
reasoning: "字段名包含关键词:'姓名'",
sample_values: ["张三", "李四"],
is_skipped: false,
confirmed: true,
},
{
id: 8,
company_id: 1,
file_id: 2,
source_field: "养老保险",
standard_field: "养老保险",
confidence: 1.0,
reasoning: "字段名完全匹配",
sample_values: [800, 960, 1200],
is_skipped: false,
confirmed: true,
},
{
id: 9,
company_id: 1,
file_id: 2,
source_field: "医疗",
standard_field: "医疗保险",
confidence: 0.8,
reasoning: "字段名部分匹配",
sample_values: [200, 240, 300],
is_skipped: false,
confirmed: false,
},
{
id: 10,
company_id: 1,
file_id: 2,
source_field: "失业",
standard_field: "失业保险",
confidence: 0.75,
reasoning: "字段名相似",
sample_values: [50, 60, 75],
is_skipped: false,
confirmed: false,
},
{
id: 11,
company_id: 1,
file_id: 2,
source_field: "公积金",
standard_field: "公积金",
confidence: 0.5,
reasoning: "需要确认具体含义",
sample_values: [500, 600, 750],
is_skipped: false,
confirmed: false,
},
{
id: 12,
company_id: 1,
file_id: 2,
source_field: "合计",
standard_field: "社保合计",
confidence: 0.6,
reasoning: "可能是合计字段",
sample_values: [1550, 1800, 2325],
is_skipped: false,
confirmed: false,
},
],
},
{
file_id: 3,
file_type: "个税表",
file_name: "2024年1月个税表.xlsx",
total_fields: 6,
confirmed_fields: 1,
high_confidence: 2,
medium_confidence: 3,
low_confidence: 1,
mappings: [
{
id: 13,
company_id: 1,
file_id: 3,
source_field: "姓名",
standard_field: "员工姓名",
confidence: 0.95,
reasoning: "字段名包含关键词:'姓名'",
sample_values: ["张三", "李四"],
is_skipped: false,
confirmed: true,
},
{
id: 14,
company_id: 1,
file_id: 3,
source_field: "应税工资",
standard_field: "应税收入",
confidence: 0.9,
reasoning: "字段名包含关键词:'应税'",
sample_values: [8000, 10000],
is_skipped: false,
confirmed: false,
},
{
id: 15,
company_id: 1,
file_id: 3,
source_field: "专项扣除",
standard_field: "税前扣除",
confidence: 0.8,
reasoning: "可能为税前扣除项",
sample_values: [1000, 1500],
is_skipped: false,
confirmed: false,
},
{
id: 16,
company_id: 1,
file_id: 3,
source_field: "个税",
standard_field: "应缴个税",
confidence: 0.7,
reasoning: "可能为个税字段",
sample_values: [200, 300],
is_skipped: false,
confirmed: false,
},
{
id: 17,
company_id: 1,
file_id: 3,
source_field: "税后工资",
standard_field: "税后收入",
confidence: 0.85,
reasoning: "字段名相似",
sample_values: [6800, 8500],
is_skipped: false,
confirmed: false,
},
{
id: 18,
company_id: 1,
file_id: 3,
source_field: "银行账号",
standard_field: "银行账号",
confidence: 1.0,
reasoning: "字段名完全匹配",
sample_values: ["6222021234567890"],
is_skipped: false,
confirmed: false,
},
],
},
],
};
const container = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: { staggerChildren: 0.08 },
},
};
const item = {
hidden: { opacity: 0, y: 12 },
show: { opacity: 1, y: 0, transition: { duration: 0.4, ease: [0.16, 1, 0.3, 1] as const } },
};
export default function MappingPage() {
const params = useParams();
const router = useRouter();
const toast = useToast();
const taskId = params.id as string;
const [data, setData] = useState<TaskMappingOverview | null>(mockMappingData);
const [loading, setLoading] = useState(false);
const [activeFile, setActiveFile] = useState<number>(mockMappingData?.files[0]?.file_id || 1);
// 统计
const totalHigh = data?.files.reduce((acc, f) => acc + f.high_confidence, 0) || 0;
const totalMedium = data?.files.reduce((acc, f) => acc + f.medium_confidence, 0) || 0;
const totalLow = data?.files.reduce((acc, f) => acc + f.low_confidence, 0) || 0;
// 更新映射
const handleUpdateMapping = useCallback(
async (mappingId: number, standardField: string) => {
try {
await api.put(ENDPOINTS.MAPPING.UPDATE(mappingId), {
standard_field: standardField,
});
setData((prev) => {
if (!prev) return prev;
const newFiles = prev.files.map((file) => ({
...file,
mappings: file.mappings.map((m) =>
m.id === mappingId ? { ...m, standard_field: standardField, confidence: 1.0 } : m
),
}));
return { ...prev, files: newFiles };
});
toast.success("字段已更新");
} catch {
toast.error("更新失败");
}
},
[toast]
);
// 跳过映射
const handleSkipMapping = useCallback(
async (mappingId: number) => {
try {
await api.put(ENDPOINTS.MAPPING.UPDATE(mappingId), {
is_skipped: true,
});
setData((prev) => {
if (!prev) return prev;
const newFiles = prev.files.map((file) => ({
...file,
mappings: file.mappings.map((m) =>
m.id === mappingId ? { ...m, is_skipped: true } : m
),
}));
return { ...prev, files: newFiles };
});
toast.success("字段已跳过");
} catch {
toast.error("操作失败");
}
},
[toast]
);
// 确认单个映射
const handleConfirmMapping = useCallback(
async (mappingId: number) => {
try {
await api.post(ENDPOINTS.MAPPING.CONFIRM, {
mapping_ids: [mappingId],
});
setData((prev) => {
if (!prev) return prev;
const newFiles = prev.files.map((file) => ({
...file,
mappings: file.mappings.map((m) =>
m.id === mappingId
? { ...m, confirmed: true, confirmed_at: new Date().toISOString() }
: m
),
confirmed_fields: file.mappings.filter(
(m) => m.id === mappingId || m.confirmed
).length,
}));
const totalConfirmed = newFiles.reduce((acc, f) => acc + f.confirmed_fields, 0);
return { ...prev, files: newFiles, confirmed_fields: totalConfirmed };
});
toast.success("字段已确认");
} catch {
toast.error("确认失败");
}
},
[toast]
);
// 批量确认
const handleConfirmAll = useCallback(
async (mappingIds: number[]) => {
if (mappingIds.length === 0) return;
try {
setLoading(true);
await api.post(ENDPOINTS.MAPPING.CONFIRM, {
mapping_ids: mappingIds,
});
setData((prev) => {
if (!prev) return prev;
const newFiles = prev.files.map((file) => {
const fileIds = file.mappings.map((m) => m.id);
const confirmedIds = mappingIds.filter((id) => fileIds.includes(id));
return {
...file,
mappings: file.mappings.map((m) =>
confirmedIds.includes(m.id)
? { ...m, confirmed: true, confirmed_at: new Date().toISOString() }
: m
),
confirmed_fields: file.mappings.filter(
(m) => m.confirmed || confirmedIds.includes(m.id)
).length,
};
});
const totalConfirmed = newFiles.reduce((acc, f) => acc + f.confirmed_fields, 0);
return { ...prev, files: newFiles, confirmed_fields: totalConfirmed };
});
toast.success(`已确认 ${mappingIds.length} 个字段`);
} catch {
toast.error("批量确认失败");
} finally {
setLoading(false);
}
},
[toast]
);
// 确认并进入下一步
const handleConfirmAndNext = useCallback(async () => {
try {
setLoading(true);
toast.success("字段映射已确认,正在进入对账...");
router.push(`/tasks/${taskId}/reconciliation`);
} catch {
toast.error("操作失败");
} finally {
setLoading(false);
}
}, [taskId, router, toast]);
const currentFile = data?.files.find((f) => f.file_id === activeFile);
if (!data) {
return (
<div className="min-h-full flex items-center justify-center">
<div className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="h-5 w-5 animate-spin" />
...
</div>
</div>
);
}
return (
<div className="min-h-full p-6 lg:p-8 max-w-7xl mx-auto space-y-6">
{/* 页面头部 */}
<motion.div
initial={{ opacity: 0, y: -8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }}
className="flex items-center justify-between"
>
<div className="flex items-center gap-4">
<Button variant="ghost" size="icon" onClick={() => router.push("/dashboard")} className="hover:bg-muted">
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<h1 className="text-heading-1 text-foreground"></h1>
<p className="text-muted-foreground mt-1">
#{taskId} - AI
</p>
</div>
</div>
<Button onClick={handleConfirmAndNext} disabled={loading} className="btn-press">
{loading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<CheckCircle className="h-4 w-4" />
)}
</Button>
</motion.div>
{/* AI 建议面板 */}
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.1, ease: [0.16, 1, 0.3, 1] }}
>
<AISuggestionPanel
totalFields={data.total_fields}
highConfidence={totalHigh}
mediumConfidence={totalMedium}
lowConfidence={totalLow}
confirmedCount={data.confirmed_fields}
onAutoConfirm={() => {
const ids = data.files
.flatMap((f) => f.mappings)
.filter((m) => !m.confirmed && !m.is_skipped && m.standard_field)
.map((m) => m.id);
handleConfirmAll(ids);
}}
/>
</motion.div>
{/* 文件标签页 */}
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.2, ease: [0.16, 1, 0.3, 1] }}
>
<div className="flex gap-2 border-b border-border overflow-x-auto">
{data.files.map((file) => (
<button
key={file.file_id}
onClick={() => setActiveFile(file.file_id)}
className={`flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 -mb-px whitespace-nowrap transition-colors ${
activeFile === file.file_id
? "border-primary text-primary"
: "border-transparent text-muted-foreground hover:text-foreground"
}`}
>
<FileSpreadsheet className="w-4 h-4" />
{file.file_type}
<Badge variant={activeFile === file.file_id ? "default" : "secondary"} className="ml-1 text-xs">
{file.confirmed_fields}/{file.total_fields}
</Badge>
</button>
))}
</div>
</motion.div>
{/* 字段映射表格 */}
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.3, ease: [0.16, 1, 0.3, 1] }}
>
{currentFile && (
<FieldMappingTable
mappings={currentFile.mappings}
fileName={currentFile.file_name}
fileType={currentFile.file_type}
onUpdate={handleUpdateMapping}
onSkip={handleSkipMapping}
onConfirm={handleConfirmMapping}
onConfirmAll={handleConfirmAll}
/>
)}
</motion.div>
{/* 文件概览卡片 */}
<motion.div
variants={container}
initial="hidden"
animate="show"
className="grid grid-cols-1 md:grid-cols-3 gap-4"
>
{data.files.map((file) => (
<motion.div key={file.file_id} variants={item}>
<Card
className={`cursor-pointer transition-all hover-lift ${
activeFile === file.file_id
? "ring-2 ring-primary"
: ""
}`}
onClick={() => setActiveFile(file.file_id)}
>
<CardContent className="p-5">
<div className="flex items-center gap-3 mb-3">
<div className="p-2 rounded-lg bg-muted">
<FileSpreadsheet className="w-5 h-5 text-muted-foreground" />
</div>
<div className="flex-1 min-w-0">
<h3 className="font-medium text-foreground truncate">
{file.file_type}
</h3>
<p className="text-caption text-muted-foreground truncate">
{file.file_name}
</p>
</div>
</div>
<div className="flex items-center justify-between">
<span className="text-caption text-muted-foreground">
{file.confirmed_fields}/{file.total_fields}
</span>
{file.low_confidence > 0 && (
<Badge variant="destructive" className="text-xs">
{file.low_confidence}
</Badge>
)}
</div>
{/* 置信度进度条 */}
<div className="mt-3 h-1.5 bg-muted rounded-full overflow-hidden">
<motion.div
initial={{ width: 0 }}
animate={{ width: `${(file.confirmed_fields / file.total_fields) * 100}%` }}
transition={{ duration: 0.6, ease: [0.16, 1, 0.3, 1] }}
className="h-full bg-primary rounded-full"
/>
</div>
</CardContent>
</Card>
</motion.div>
))}
</motion.div>
</div>
);
}
@@ -0,0 +1,548 @@
"use client";
import { useState, useEffect, use, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import { motion } from "motion/react";
import { api } from "@/lib/api/client";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
Tabs,
TabsContent,
TabsList,
TabsTrigger,
} from "@/components/ui/tabs";
import {
CheckCircle,
FileText,
Download,
RefreshCw,
ArrowLeft,
TrendingUp,
Users,
AlertOctagon,
} from "lucide-react";
interface TaskDetail {
id: number;
name: string;
period: string;
status: string;
total_employees: number;
matched_count: number;
exception_count: number;
created_at: string;
completed_at: string | null;
}
interface ReconciliationResult {
task_id: number;
period: string;
total_employees: number;
matched_employees: number;
exception_count: number;
exceptions_by_type: Record<string, number>;
exceptions_by_severity: Record<string, number>;
execution_time_ms: number;
completed_at: string;
}
interface ExceptionItem {
id: number;
exception_type: string;
severity: "low" | "medium" | "high" | "critical";
status: string;
employee_id: string;
employee_name: string;
description: string;
salary_amount: number | null;
social_security_amount: number | null;
tax_amount: number | null;
bank_amount: number | null;
difference_amount: number | null;
}
const severityConfig = {
low: { label: "低", bg: "bg-blue-100 dark:bg-blue-900/40", text: "text-blue-700 dark:text-blue-300" },
medium: { label: "中", bg: "bg-yellow-100 dark:bg-yellow-900/40", text: "text-yellow-700 dark:text-yellow-300" },
high: { label: "高", bg: "bg-orange-100 dark:bg-orange-900/40", text: "text-orange-700 dark:text-orange-300" },
critical: { label: "严重", bg: "bg-red-100 dark:bg-red-900/40", text: "text-red-700 dark:text-red-300" },
};
const typeLabels: Record<string, string> = {
amount_mismatch: "金额不一致",
missing_record: "记录缺失",
duplicate_record: "重复记录",
format_error: "格式错误",
logic_error: "逻辑错误",
rule_violation: "规则违规",
threshold_exceeded: "阈值超限",
};
export default function TaskResultPage({ params }: { params: Promise<{ id: string }> }) {
const { id: taskId } = use(params);
const router = useRouter();
const [task, setTask] = useState<TaskDetail | null>(null);
const [result, setResult] = useState<ReconciliationResult | null>(null);
const [exceptions, setExceptions] = useState<ExceptionItem[]>([]);
const [loading, setLoading] = useState(true);
const fetchResultRef = useRef<() => Promise<void>>();
const fetchTaskDetail = useCallback(async () => {
try {
const res = await api.get<TaskDetail>(`/api/tasks/${taskId}`);
setTask(res.data);
if (res.data.status === "COMPLETED" && fetchResultRef.current) {
fetchResultRef.current();
}
} catch (error) {
console.error("获取任务详情失败", error);
} finally {
setLoading(false);
}
}, [taskId]);
const fetchResult = useCallback(async () => {
try {
const res = await api.get<ReconciliationResult>(`/api/reconciliation/result/${taskId}`);
setResult(res.data);
} catch (error) {
console.error("获取对账结果失败", error);
}
}, [taskId]);
// Store fetchResult in ref to avoid circular dependency
useEffect(() => {
fetchResultRef.current = fetchResult;
}, [fetchResult]);
const fetchExceptions = useCallback(async () => {
try {
const res = await api.get<{ items: ExceptionItem[] }>(`/api/exceptions/`, {
params: { task_id: taskId, page_size: 100 },
});
setExceptions(res.data.items || []);
} catch (error) {
console.error("获取异常列表失败", error);
}
}, [taskId]);
useEffect(() => {
if (taskId) {
fetchTaskDetail();
fetchExceptions();
}
}, [taskId, fetchTaskDetail, fetchExceptions]);
async function handleExport() {
try {
const res = await api.get<Blob>(`/api/exports/task/${taskId}`, {
responseType: "blob",
});
const url = window.URL.createObjectURL(res.data);
const a = document.createElement("a");
a.href = url;
a.download = `对账结果_${task?.period || taskId}.xlsx`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (error) {
console.error("导出失败", error);
}
}
async function handleExportKingdee() {
try {
const res = await api.get<Blob>(`/api/exports/kingdee/${taskId}`, {
responseType: "blob",
});
const url = window.URL.createObjectURL(res.data);
const a = document.createElement("a");
a.href = url;
a.download = `金蝶凭证_${task?.period || taskId}.xlsx`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (error) {
console.error("导出金蝶凭证失败", error);
}
}
if (loading) {
return (
<div className="min-h-full flex items-center justify-center">
<div className="flex items-center gap-2 text-muted-foreground">
<RefreshCw className="h-5 w-5 animate-spin" />
...
</div>
</div>
);
}
if (!task) {
return (
<div className="min-h-full flex items-center justify-center">
<Card className="max-w-md">
<CardContent className="py-12 text-center">
<p className="text-muted-foreground"></p>
<Button className="mt-4 btn-press" onClick={() => router.back()}>
</Button>
</CardContent>
</Card>
</div>
);
}
const matchRate = task.total_employees > 0
? ((task.matched_count / task.total_employees) * 100).toFixed(1)
: "0.0";
const container = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: { staggerChildren: 0.06 },
},
};
const item = {
hidden: { opacity: 0, y: 8 },
show: { opacity: 1, y: 0, transition: { duration: 0.3, ease: [0.16, 1, 0.3, 1] as const } },
};
return (
<div className="min-h-full p-6 lg:p-8 max-w-7xl mx-auto space-y-6">
{/* Header */}
<motion.div
initial={{ opacity: 0, y: -8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }}
className="flex items-center justify-between"
>
<div className="flex items-center gap-4">
<Button variant="ghost" size="icon" onClick={() => router.back()} className="hover:bg-muted">
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<h1 className="text-heading-1 text-foreground">{task.name}</h1>
<p className="text-muted-foreground mt-1">
: {task.period}
</p>
</div>
</div>
<div className="flex items-center gap-3">
<Button variant="outline" onClick={handleExport} className="btn-press">
<Download className="h-4 w-4 mr-2" />
</Button>
<Button variant="outline" onClick={handleExportKingdee} className="btn-press">
<FileText className="h-4 w-4 mr-2" />
</Button>
</div>
</motion.div>
{/* Stats Cards */}
<motion.div
variants={container}
initial="hidden"
animate="show"
className="grid grid-cols-2 lg:grid-cols-4 gap-4"
>
<motion.div variants={item}>
<Card className="hover-lift">
<CardContent className="p-5">
<div className="flex items-center justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide"></p>
<p className="text-3xl font-semibold mt-1">{task.total_employees}</p>
</div>
<div className="p-2.5 rounded-lg bg-blue-50 dark:bg-blue-950/30">
<Users className="w-5 h-5 text-blue-600" />
</div>
</div>
</CardContent>
</Card>
</motion.div>
<motion.div variants={item}>
<Card className="hover-lift">
<CardContent className="p-5">
<div className="flex items-center justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide"></p>
<p className="text-3xl font-semibold mt-1 text-emerald-600">{task.matched_count}</p>
</div>
<div className="p-2.5 rounded-lg bg-emerald-50 dark:bg-emerald-950/30">
<CheckCircle className="w-5 h-5 text-emerald-600" />
</div>
</div>
</CardContent>
</Card>
</motion.div>
<motion.div variants={item}>
<Card className="hover-lift">
<CardContent className="p-5">
<div className="flex items-center justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide"></p>
<p className="text-3xl font-semibold mt-1 text-red-600">{task.exception_count}</p>
</div>
<div className="p-2.5 rounded-lg bg-red-50 dark:bg-red-950/30">
<AlertOctagon className="w-5 h-5 text-red-600" />
</div>
</div>
</CardContent>
</Card>
</motion.div>
<motion.div variants={item}>
<Card className="hover-lift">
<CardContent className="p-5">
<div className="flex items-center justify-between">
<div>
<p className="text-caption text-muted-foreground uppercase tracking-wide"></p>
<p className="text-3xl font-semibold mt-1">{matchRate}%</p>
</div>
<div className="p-2.5 rounded-lg bg-violet-50 dark:bg-violet-950/30">
<TrendingUp className="w-5 h-5 text-violet-600" />
</div>
</div>
{/* Progress bar */}
<div className="mt-3 h-2 bg-muted rounded-full overflow-hidden">
<motion.div
initial={{ width: 0 }}
animate={{ width: `${matchRate}%` }}
transition={{ duration: 0.8, delay: 0.3, ease: [0.16, 1, 0.3, 1] }}
className="h-full bg-gradient-to-r from-emerald-500 to-emerald-400"
/>
</div>
</CardContent>
</Card>
</motion.div>
</motion.div>
{/* Tabs */}
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.2, ease: [0.16, 1, 0.3, 1] }}
>
<Tabs defaultValue="overview" className="space-y-4">
<TabsList className="bg-muted/50">
<TabsTrigger value="overview" className="data-[state=active]:bg-background"></TabsTrigger>
<TabsTrigger value="exceptions" className="data-[state=active]:bg-background">
{task.exception_count > 0 && (
<Badge variant="destructive" className="ml-2">
{task.exception_count}
</Badge>
)}
</TabsTrigger>
<TabsTrigger value="matched" className="data-[state=active]:bg-background"></TabsTrigger>
</TabsList>
{/* Overview Tab */}
<TabsContent value="overview" className="space-y-4">
<div className="grid lg:grid-cols-2 gap-4">
{/* Exception Types */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base font-medium"></CardTitle>
</CardHeader>
<CardContent>
{result?.exceptions_by_type && Object.keys(result.exceptions_by_type).length > 0 ? (
<div className="space-y-3">
{Object.entries(result.exceptions_by_type).map(([type, count]) => (
<div key={type} className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">
{typeLabels[type] || type}
</span>
<Badge variant="secondary">{count}</Badge>
</div>
))}
</div>
) : (
<p className="text-sm text-muted-foreground"></p>
)}
</CardContent>
</Card>
{/* Severity Distribution */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base font-medium"></CardTitle>
</CardHeader>
<CardContent>
{result?.exceptions_by_severity && Object.keys(result.exceptions_by_severity).length > 0 ? (
<div className="flex flex-wrap gap-3">
{["critical", "high", "medium", "low"].map((severity) => {
const count = result.exceptions_by_severity[severity] || 0;
const config = severityConfig[severity as keyof typeof severityConfig];
return (
<div key={severity} className={`flex items-center gap-2 px-3 py-1.5 rounded-full ${config.bg}`}>
<div className={`w-2 h-2 rounded-full bg-current ${config.text}`} />
<span className={`text-sm font-medium ${config.text}`}>
{config.label}: {count}
</span>
</div>
);
})}
</div>
) : (
<p className="text-sm text-muted-foreground"></p>
)}
</CardContent>
</Card>
</div>
{/* Execution Info */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base font-medium"></CardTitle>
</CardHeader>
<CardContent>
<div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
<div>
<p className="text-caption text-muted-foreground"></p>
<p className="text-sm font-medium mt-1">{new Date(task.created_at).toLocaleString()}</p>
</div>
<div>
<p className="text-caption text-muted-foreground"></p>
<p className="text-sm font-medium mt-1">
{task.completed_at ? new Date(task.completed_at).toLocaleString() : "-"}
</p>
</div>
{result && (
<>
<div>
<p className="text-caption text-muted-foreground"></p>
<p className="text-sm font-medium mt-1">{result.execution_time_ms?.toFixed(0) || '-'}ms</p>
</div>
<div>
<p className="text-caption text-muted-foreground"></p>
<p className="text-sm font-medium mt-1">
{result.completed_at ? new Date(result.completed_at).toLocaleString() : "-"}
</p>
</div>
</>
)}
</div>
</CardContent>
</Card>
</TabsContent>
{/* Exceptions Tab */}
<TabsContent value="exceptions">
<Card>
<CardHeader className="pb-4">
<div className="flex items-center justify-between">
<CardTitle className="text-base font-medium"></CardTitle>
<Badge variant="secondary">{exceptions.length} </Badge>
</div>
</CardHeader>
<CardContent className="p-0">
{exceptions.length === 0 ? (
<div className="py-16 text-center">
<div className="w-16 h-16 rounded-full bg-emerald-50 dark:bg-emerald-950/30 mx-auto mb-4 flex items-center justify-center">
<CheckCircle className="w-8 h-8 text-emerald-500" />
</div>
<p className="text-lg font-medium text-foreground">!</p>
<p className="text-sm text-muted-foreground mt-1"></p>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{exceptions.map((exc) => (
<TableRow key={exc.id}>
<TableCell>
<div>
<div className="font-medium">{exc.employee_name}</div>
<div className="text-xs text-muted-foreground">{exc.employee_id}</div>
</div>
</TableCell>
<TableCell>
<Badge variant="outline" className="font-normal">
{typeLabels[exc.exception_type] || exc.exception_type}
</Badge>
</TableCell>
<TableCell>
<Badge className={`${severityConfig[exc.severity].bg} ${severityConfig[exc.severity].text}`}>
{severityConfig[exc.severity].label}
</Badge>
</TableCell>
<TableCell className="max-w-[250px]">
<span className="truncate block">{exc.description}</span>
</TableCell>
<TableCell className="text-right">
{exc.difference_amount != null && (
<span className={exc.difference_amount > 0 ? "text-red-600" : "text-emerald-600"}>
{exc.difference_amount > 0 ? "+" : ""}
{exc.difference_amount.toFixed(2)}
</span>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</TabsContent>
{/* Matched Tab */}
<TabsContent value="matched">
<Card>
<CardHeader className="pb-4">
<div className="flex items-center justify-between">
<CardTitle className="text-base font-medium"></CardTitle>
<Badge variant="secondary">{task.matched_count} </Badge>
</div>
</CardHeader>
<CardContent className="py-16 text-center">
<div className="w-16 h-16 rounded-full bg-emerald-50 dark:bg-emerald-950/30 mx-auto mb-4 flex items-center justify-center">
<CheckCircle className="w-8 h-8 text-emerald-500" />
</div>
<p className="text-lg font-medium text-foreground">!</p>
<p className="text-sm text-muted-foreground mt-1">
{task.matched_count}
</p>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</motion.div>
</div>
);
}
+257
View File
@@ -0,0 +1,257 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { motion } from "motion/react";
import {
FileText,
Filter,
ArrowRight,
Loader2,
ChevronLeft,
ChevronRight
} from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useRouter } from "next/navigation";
import { api } from "@/lib/api/client";
import ENDPOINTS from "@/lib/api/endpoints";
interface Task {
id: number;
period: string;
status: string;
total_employees: number;
matched_count: number;
exception_count: number;
created_at: string;
completed_at: string | null;
}
const statusLabels: Record<string, { label: string; color: string; bgColor: string }> = {
PENDING: { label: "待处理", color: "text-gray-700 dark:text-gray-300", bgColor: "bg-gray-100 dark:bg-gray-800" },
PROCESSING: { label: "处理中", color: "text-blue-700 dark:text-blue-300", bgColor: "bg-blue-100 dark:bg-blue-900/50" },
MAPPING_COMPLETED: { label: "映射完成", color: "text-amber-700 dark:text-amber-300", bgColor: "bg-amber-100 dark:bg-amber-900/50" },
COMPLETED: { label: "已完成", color: "text-emerald-700 dark:text-emerald-300", bgColor: "bg-emerald-100 dark:bg-emerald-900/50" },
FAILED: { label: "失败", color: "text-red-700 dark:text-red-300", bgColor: "bg-red-100 dark:bg-red-900/50" },
};
// 生成可选月份列表(近12个月)
const getAvailablePeriods = () => {
const periods = [];
const now = new Date();
for (let i = 0; i < 12; i++) {
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
periods.push(`${year}-${month}`);
}
return periods;
};
const formatPeriod = (period: string) => {
const [year, month] = period.split("-");
return `${year}${parseInt(month)}`;
};
export default function TasksPage() {
const router = useRouter();
const [tasks, setTasks] = useState<Task[]>([]);
const [loading, setLoading] = useState(true);
const [selectedPeriod, setSelectedPeriod] = useState<string>("");
const [availablePeriods] = useState(getAvailablePeriods);
const loadTasks = useCallback(async () => {
try {
setLoading(true);
const params = selectedPeriod ? { period: selectedPeriod } : {};
const res = await api.get<Task[]>(ENDPOINTS.TASK.LIST, { params });
setTasks(res.data);
} catch (error) {
console.error("加载任务列表失败:", error);
} finally {
setLoading(false);
}
}, [selectedPeriod]);
useEffect(() => {
loadTasks();
}, [loadTasks]);
const getMatchRate = (task: Task) => {
if (task.total_employees === 0) return "0%";
const rate = Math.round((task.matched_count / task.total_employees) * 100);
return `${rate}%`;
};
return (
<div className="min-h-full p-6 lg:p-8 max-w-6xl mx-auto">
{/* Header */}
<motion.div
initial={{ opacity: 0, y: -8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] as const }}
className="mb-8"
>
<h1 className="text-heading-1 text-foreground mb-2"></h1>
<p className="text-muted-foreground text-body">
</p>
</motion.div>
{/* Filter Bar */}
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.1 }}
className="mb-6 flex items-center gap-4 flex-wrap"
>
<div className="flex items-center gap-2">
<Filter className="w-4 h-4 text-muted-foreground" />
<span className="text-body-small text-muted-foreground"></span>
</div>
<div className="flex items-center gap-2 flex-wrap">
<Button
variant={selectedPeriod === "" ? "default" : "outline"}
size="sm"
onClick={() => setSelectedPeriod("")}
className="text-body-small"
>
</Button>
{availablePeriods.slice(0, 6).map((period) => (
<Button
key={period}
variant={selectedPeriod === period ? "default" : "outline"}
size="sm"
onClick={() => setSelectedPeriod(period)}
className="text-body-small"
>
{formatPeriod(period)}
</Button>
))}
</div>
{selectedPeriod && (
<Button
variant="ghost"
size="sm"
onClick={() => setSelectedPeriod("")}
className="text-caption"
>
</Button>
)}
</motion.div>
{/* Tasks List */}
{loading ? (
<div className="flex items-center justify-center py-20">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
</div>
) : tasks.length === 0 ? (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
>
<Card>
<CardContent className="p-12 text-center">
<div className="w-16 h-16 rounded-full bg-muted mx-auto mb-4 flex items-center justify-center">
<FileText className="w-8 h-8 text-muted-foreground" />
</div>
<h3 className="text-heading-3 text-foreground mb-2"></h3>
<p className="text-body text-muted-foreground mb-6">
{selectedPeriod
? `没有 ${formatPeriod(selectedPeriod)} 的对账任务`
: "当前没有任何对账任务"
}
</p>
<Button onClick={() => router.push("/tasks/new")}>
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
</CardContent>
</Card>
</motion.div>
) : (
<div className="space-y-4">
{tasks.map((task, index) => (
<motion.div
key={task.id}
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{
duration: 0.3,
delay: index * 0.05,
}}
>
<Card
className="cursor-pointer hover-lift transition-all group"
onClick={() => router.push(`/tasks/${task.id}/result`)}
>
<CardContent className="p-5">
<div className="flex items-start justify-between">
<div className="flex items-start gap-4">
<div className="p-3 rounded-lg bg-primary/10 group-hover:bg-primary/20 transition-colors">
<FileText className="w-6 h-6 text-primary" />
</div>
<div>
<div className="flex items-center gap-3 mb-2">
<h3 className="text-heading-3 text-foreground">
{formatPeriod(task.period)}
</h3>
<span className={`px-2.5 py-1 rounded-full text-xs font-medium ${statusLabels[task.status]?.bgColor} ${statusLabels[task.status]?.color}`}>
{statusLabels[task.status]?.label || task.status}
</span>
</div>
<div className="flex items-center gap-6 text-body-small text-muted-foreground">
<span className="flex items-center gap-1.5">
<span className="font-medium text-foreground">{task.total_employees}</span>
</span>
<span className="flex items-center gap-1.5">
<span className="font-medium text-emerald-600">{task.matched_count}</span>
</span>
<span className="flex items-center gap-1.5">
<span className={`font-medium ${task.exception_count > 0 ? "text-amber-600" : "text-muted-foreground"}`}>
{task.exception_count}
</span>
</span>
<span className="flex items-center gap-1.5">
: <span className="font-medium text-foreground">{getMatchRate(task)}</span>
</span>
</div>
</div>
</div>
<div className="flex items-center gap-4">
<span className="text-caption text-muted-foreground">
{task.completed_at
? new Date(task.completed_at).toLocaleDateString("zh-CN")
: new Date(task.created_at).toLocaleDateString("zh-CN")
}
</span>
<ArrowRight className="w-5 h-5 text-muted-foreground group-hover:text-primary group-hover:translate-x-1 transition-all" />
</div>
</div>
</CardContent>
</Card>
</motion.div>
))}
</div>
)}
{/* Pagination hint */}
{tasks.length > 0 && (
<div className="mt-6 flex items-center justify-center gap-2 text-caption text-muted-foreground">
<ChevronLeft className="w-4 h-4" />
<span> 50 </span>
<ChevronRight className="w-4 h-4" />
</div>
)}
</div>
);
}
+147
View File
@@ -0,0 +1,147 @@
import { NextRequest, NextResponse } from 'next/server';
/**
* 通用的 API 代理路由
*/
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
) {
const { path } = await params;
const targetPath = path.join('/');
const searchParams = request.nextUrl.search;
const targetUrl = `http://localhost:8000/api/${targetPath}${searchParams}`;
const headers: Record<string, string> = {};
request.headers.forEach((value, key) => {
if (key.toLowerCase() !== 'host') {
headers[key] = value;
}
});
try {
const response = await fetch(targetUrl, { headers });
const data = await response.json();
return NextResponse.json(data, { status: response.status });
} catch (error) {
return NextResponse.json({ detail: 'Proxy error' }, { status: 502 });
}
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
) {
const { path } = await params;
const targetPath = path.join('/');
const searchParams = request.nextUrl.search;
const targetUrl = `http://localhost:8000/api/${targetPath}${searchParams}`;
const body = await request.text();
const headers: Record<string, string> = {};
request.headers.forEach((value, key) => {
if (key.toLowerCase() !== 'host') {
headers[key] = value;
}
});
try {
const response = await fetch(targetUrl, {
method: 'POST',
headers,
body,
});
const data = await response.json();
return NextResponse.json(data, { status: response.status });
} catch (error) {
return NextResponse.json({ detail: 'Proxy error' }, { status: 502 });
}
}
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
) {
const { path } = await params;
const targetPath = path.join('/');
const searchParams = request.nextUrl.search;
const targetUrl = `http://localhost:8000/api/${targetPath}${searchParams}`;
const body = await request.text();
const headers: Record<string, string> = {};
request.headers.forEach((value, key) => {
if (key.toLowerCase() !== 'host') {
headers[key] = value;
}
});
try {
const response = await fetch(targetUrl, {
method: 'PUT',
headers,
body,
});
const data = await response.json();
return NextResponse.json(data, { status: response.status });
} catch (error) {
return NextResponse.json({ detail: 'Proxy error' }, { status: 502 });
}
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
) {
const { path } = await params;
const targetPath = path.join('/');
const searchParams = request.nextUrl.search;
const targetUrl = `http://localhost:8000/api/${targetPath}${searchParams}`;
const body = await request.text();
const headers: Record<string, string> = {};
request.headers.forEach((value, key) => {
if (key.toLowerCase() !== 'host') {
headers[key] = value;
}
});
try {
const response = await fetch(targetUrl, {
method: 'PATCH',
headers,
body,
});
const data = await response.json();
return NextResponse.json(data, { status: response.status });
} catch (error) {
return NextResponse.json({ detail: 'Proxy error' }, { status: 502 });
}
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
) {
const { path } = await params;
const targetPath = path.join('/');
const searchParams = request.nextUrl.search;
const targetUrl = `http://localhost:8000/api/${targetPath}${searchParams}`;
const headers: Record<string, string> = {};
request.headers.forEach((value, key) => {
if (key.toLowerCase() !== 'host') {
headers[key] = value;
}
});
try {
const response = await fetch(targetUrl, {
method: 'DELETE',
headers,
});
const data = await response.json();
return NextResponse.json(data, { status: response.status });
} catch (error) {
return NextResponse.json({ detail: 'Proxy error' }, { status: 502 });
}
}
+306 -15
View File
@@ -1,26 +1,317 @@
@import "tailwindcss";
@import "@fontsource/geist/400.css";
@import "@fontsource/geist/500.css";
@import "@fontsource/geist/600.css";
@import "@fontsource/geist/700.css";
@import "@fontsource/ibm-plex-sans/400.css";
@import "@fontsource/ibm-plex-sans/500.css";
@import "@fontsource/ibm-plex-sans/600.css";
@custom-variant dark (&:is(.dark *));
/* Design System Tokens */
:root {
--background: #ffffff;
--foreground: #171717;
/* Colors - Professional Blue-Gray Palette */
--background: 0 0% 100%;
--foreground: 220 14% 18%;
--card: 0 0% 100%;
--card-foreground: 220 14% 18%;
--popover: 0 0% 100%;
--popover-foreground: 220 14% 18%;
/* Primary - Professional Blue */
--primary: 221 83% 53%;
--primary-foreground: 0 0% 100%;
/* Secondary - Cool Gray */
--secondary: 220 13% 95%;
--secondary-foreground: 220 14% 18%;
/* Muted */
--muted: 220 13% 95%;
--muted-foreground: 220 9% 46%;
/* Accent */
--accent: 220 13% 95%;
--accent-foreground: 220 14% 18%;
/* Destructive */
--destructive: 0 84% 60%;
--destructive-foreground: 0 0% 100%;
/* Borders & Inputs */
--border: 220 13% 91%;
--input: 220 13% 91%;
--ring: 221 83% 53%;
/* Radius */
--radius: 0.5rem;
/* Shadows */
--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.03);
--shadow: 0 1px 3px 0 rgb(0 0 0 / 0.06), 0 1px 2px -1px rgb(0 0 0 / 0.04);
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.06), 0 2px 4px -2px rgb(0 0 0 / 0.04);
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.06), 0 4px 6px -4px rgb(0 0 0 / 0.04);
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
/* Dark Mode - Professional Dark */
.dark {
--background: 220 17% 10%;
--foreground: 210 17% 95%;
--card: 220 17% 12%;
--card-foreground: 210 17% 95%;
--popover: 220 17% 12%;
--popover-foreground: 210 17% 95%;
--primary: 217 91% 60%;
--primary-foreground: 220 17% 10%;
--secondary: 217 33% 17%;
--secondary-foreground: 210 17% 95%;
--muted: 217 33% 17%;
--muted-foreground: 215 20% 65%;
--accent: 217 33% 17%;
--accent-foreground: 210 17% 95%;
--destructive: 0 63% 31%;
--destructive-foreground: 210 17% 95%;
--border: 217 33% 17%;
--input: 217 33% 17%;
--ring: 224 76% 48%;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
/* Base Styles */
* {
border-color: hsl(var(--border));
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
font-family: "Geist", "IBM Plex Sans", system-ui, sans-serif;
background: hsl(var(--background));
color: hsl(var(--foreground));
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
/* Smooth Scrolling */
html {
scroll-behavior: smooth;
}
/* Selection */
::selection {
background: hsl(var(--primary) / 0.2);
color: hsl(var(--foreground));
}
/* Focus Visible */
:focus-visible {
outline: 2px solid hsl(var(--ring));
outline-offset: 2px;
}
/* Scrollbar Styling */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: hsl(var(--muted));
border-radius: 4px;
}
::-webkit-scrollbar-thumb {
background: hsl(var(--muted-foreground) / 0.3);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: hsl(var(--muted-foreground) / 0.5);
}
/* Animation Utilities */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes scaleIn {
from {
opacity: 0;
transform: scale(0.95);
}
to {
opacity: 1;
transform: scale(1);
}
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
/* Animation Classes */
.animate-fade-in {
animation: fadeIn 0.3s ease-out forwards;
}
.animate-slide-up {
animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.animate-slide-down {
animation: slideDown 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.animate-scale-in {
animation: scaleIn 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.animate-pulse {
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
.animate-spin {
animation: spin 1s linear infinite;
}
/* Staggered Animation Delays */
.stagger-1 { animation-delay: 50ms; }
.stagger-2 { animation-delay: 100ms; }
.stagger-3 { animation-delay: 150ms; }
.stagger-4 { animation-delay: 200ms; }
.stagger-5 { animation-delay: 250ms; }
/* Transition Utilities */
.transition-base {
transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}
.transition-smooth {
transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}
.transition-bounce {
transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
}
/* Hover Effects */
.hover-lift {
transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1),
box-shadow 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}
.hover-lift:hover {
transform: translateY(-2px);
box-shadow: var(--shadow-md);
}
.hover-scale {
transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}
.hover-scale:hover {
transform: scale(1.02);
}
/* Button Active Effect */
.btn-press:active {
transform: scale(0.97);
}
/* Glass Effect */
.glass {
background: hsl(var(--background) / 0.8);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
/* Reduced Motion */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
/* Typography Scale */
.text-display {
font-size: 3rem;
line-height: 1.1;
letter-spacing: -0.025em;
font-weight: 700;
}
.text-heading-1 {
font-size: 2.25rem;
line-height: 1.2;
letter-spacing: -0.02em;
font-weight: 600;
}
.text-heading-2 {
font-size: 1.5rem;
line-height: 1.3;
letter-spacing: -0.015em;
font-weight: 600;
}
.text-heading-3 {
font-size: 1.25rem;
line-height: 1.4;
letter-spacing: -0.01em;
font-weight: 600;
}
.text-body {
font-size: 1rem;
line-height: 1.6;
}
.text-body-small {
font-size: 0.875rem;
line-height: 1.5;
}
.text-caption {
font-size: 0.75rem;
line-height: 1.4;
letter-spacing: 0.01em;
}
+10 -19
View File
@@ -1,20 +1,10 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { ThemeProvider } from "@/components/theme-provider";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: "财务AI助手",
description: "AI 驱动的工资对账系统",
};
export default function RootLayout({
@@ -23,11 +13,12 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">{children}</body>
<html lang="zh-CN" suppressHydrationWarning>
<body className="min-h-screen antialiased font-sans">
<ThemeProvider>
{children}
</ThemeProvider>
</body>
</html>
);
}
}
+3 -63
View File
@@ -1,65 +1,5 @@
import Image from "next/image";
import { redirect } from 'next/navigation';
export default function Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
}
redirect('/dashboard');
}
@@ -0,0 +1,39 @@
'use client';
import { useAuthStore } from '@/lib/stores/auth-store';
interface PermissionGateProps {
children: React.ReactNode;
permission?: string;
role?: string;
fallback?: React.ReactNode;
}
/**
* 权限门控组件
* 根据权限码或角色控制组件显示
*/
export function PermissionGate({
children,
permission,
role,
fallback = null,
}: PermissionGateProps) {
const { user } = useAuthStore();
if (!user) {
return <>{fallback}</>;
}
// 检查权限
if (permission && !user.permissions?.includes(permission)) {
return <>{fallback}</>;
}
// 检查角色
if (role && user.role !== role) {
return <>{fallback}</>;
}
return <>{children}</>;
}
@@ -0,0 +1,31 @@
'use client';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { useAuthStore } from '@/lib/stores/auth-store';
interface ProtectedRouteProps {
children: React.ReactNode;
}
/**
* 受保护路由组件
* 检查用户登录状态,未登录则重定向到登录页
*/
export function ProtectedRoute({ children }: ProtectedRouteProps) {
const router = useRouter();
const { isAuthenticated, user } = useAuthStore();
useEffect(() => {
if (!isAuthenticated || !user) {
router.push('/login');
}
}, [isAuthenticated, user, router]);
if (!isAuthenticated || !user) {
return null;
}
return <>{children}</>;
}
+82
View File
@@ -0,0 +1,82 @@
"use client";
import { useRouter } from "next/navigation";
import { LogOut, User } from "lucide-react";
import { useAuthStore } from "@/lib/stores/auth-store";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/api/client";
import ENDPOINTS from "@/lib/api/endpoints";
export function Header() {
const router = useRouter();
const { user, logout } = useAuthStore();
const handleLogout = async () => {
try {
// 调用后端登出接口
await api.post(ENDPOINTS.AUTH.LOGOUT);
} catch {
// 即使后端失败也清除本地状态
}
// 清除本地状态
logout();
// 跳转到登录页
router.push("/login");
};
if (!user) return null;
return (
<header className="sticky top-0 z-50 w-full border-b border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="flex h-14 items-center justify-between px-6">
{/* 左侧 - Logo 和系统名称 */}
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="lucide lucide-shield w-4 h-4 text-primary"
aria-hidden="true"
>
<path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"></path>
</svg>
</div>
<span className="font-semibold text-foreground">AI助手</span>
</div>
{/* 右侧 - 用户信息和登出 */}
<div className="flex items-center gap-4">
{/* 用户信息 */}
<div className="flex items-center gap-3 text-sm">
<div className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-muted/50">
<User className="w-4 h-4 text-muted-foreground" />
<span className="font-medium text-foreground">{user.full_name}</span>
<span className="text-muted-foreground">·</span>
<span className="text-muted-foreground">{user.role}</span>
</div>
</div>
{/* 登出按钮 */}
<Button
variant="ghost"
size="sm"
onClick={handleLogout}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<LogOut className="w-4 h-4" />
<span></span>
</Button>
</div>
</div>
</header>
);
}
+105
View File
@@ -0,0 +1,105 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { motion } from "motion/react";
import {
LayoutDashboard,
FileText,
AlertTriangle,
Settings,
ChevronLeft,
ChevronRight
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useState } from "react";
const navItems = [
{
label: "工作台",
href: "/dashboard",
icon: LayoutDashboard
},
{
label: "对账任务",
href: "/tasks",
icon: FileText
},
{
label: "异常处理",
href: "/exceptions",
icon: AlertTriangle
},
{
label: "规则设置",
href: "/settings/rules",
icon: Settings
},
];
export function Sidebar() {
const pathname = usePathname();
const [collapsed, setCollapsed] = useState(false);
return (
<aside
className={cn(
"sticky top-14 h-[calc(100vh-3.5rem)] border-r border-border bg-background transition-all duration-300 flex flex-col",
collapsed ? "w-16" : "w-56"
)}
>
{/* Navigation */}
<nav className="flex-1 p-3 space-y-1">
{navItems.map((item) => {
const isActive = pathname === item.href || pathname.startsWith(item.href + "/");
const Icon = item.icon;
return (
<Link
key={item.href}
href={item.href}
className={cn(
"flex items-center gap-3 px-3 py-2.5 rounded-lg transition-all relative group",
isActive
? "bg-primary/10 text-primary"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
collapsed && "justify-center px-0"
)}
>
{isActive && (
<motion.div
layoutId="activeNav"
className="absolute inset-0 bg-primary/10 rounded-lg -z-10"
transition={{ type: "spring", bounce: 0.2, duration: 0.4 }}
/>
)}
<Icon className={cn("w-5 h-5 shrink-0", isActive && "text-primary")} />
{!collapsed && (
<span className="text-body font-medium">{item.label}</span>
)}
{/* Tooltip for collapsed state */}
{collapsed && (
<div className="absolute left-full ml-2 px-2 py-1 bg-foreground text-background text-xs rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all whitespace-nowrap z-50">
{item.label}
</div>
)}
</Link>
);
})}
</nav>
{/* Collapse toggle */}
<button
onClick={() => setCollapsed(!collapsed)}
className="flex items-center justify-center h-10 border-t border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
>
{collapsed ? (
<ChevronRight className="w-4 h-4" />
) : (
<ChevronLeft className="w-4 h-4" />
)}
</button>
</aside>
);
}
@@ -0,0 +1,213 @@
"use client";
import { motion } from "motion/react";
import { AlertTriangle, CheckCircle, Info, Sparkles } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
interface AISuggestionPanelProps {
totalFields: number;
highConfidence: number;
mediumConfidence: number;
lowConfidence: number;
confirmedCount: number;
onAutoConfirm?: () => void;
className?: string;
}
const config = {
success: {
bg: "bg-emerald-50 dark:bg-emerald-950/30",
border: "border-emerald-200 dark:border-emerald-800",
iconBg: "bg-emerald-100 dark:bg-emerald-900/50",
iconColor: "text-emerald-600 dark:text-emerald-400",
titleColor: "text-emerald-800 dark:text-emerald-300",
descColor: "text-emerald-700 dark:text-emerald-400",
buttonBg: "bg-emerald-600 hover:bg-emerald-700",
progressBg: "bg-emerald-500",
},
warning: {
bg: "bg-amber-50 dark:bg-amber-950/30",
border: "border-amber-200 dark:border-amber-800",
iconBg: "bg-amber-100 dark:bg-amber-900/50",
iconColor: "text-amber-600 dark:text-amber-400",
titleColor: "text-amber-800 dark:text-amber-300",
descColor: "text-amber-700 dark:text-amber-400",
buttonBg: "bg-amber-600 hover:bg-amber-700",
progressBg: "bg-amber-500",
},
info: {
bg: "bg-blue-50 dark:bg-blue-950/30",
border: "border-blue-200 dark:border-blue-800",
iconBg: "bg-blue-100 dark:bg-blue-900/50",
iconColor: "text-blue-600 dark:text-blue-400",
titleColor: "text-blue-800 dark:text-blue-300",
descColor: "text-blue-700 dark:text-blue-400",
buttonBg: "bg-blue-600 hover:bg-blue-700",
progressBg: "bg-blue-500",
},
};
export function AISuggestionPanel({
totalFields,
highConfidence,
mediumConfidence,
lowConfidence,
confirmedCount,
onAutoConfirm,
className,
}: AISuggestionPanelProps) {
const pendingCount = totalFields - confirmedCount;
const allConfirmed = pendingCount === 0;
const progressPercent = totalFields > 0 ? (confirmedCount / totalFields) * 100 : 0;
const getSuggestion = () => {
if (allConfirmed) {
return {
type: "success" as const,
icon: CheckCircle,
title: "所有字段已确认",
description: "字段映射已完成,可以进入下一步",
action: null,
};
}
if (lowConfidence > 0) {
return {
type: "warning" as const,
icon: AlertTriangle,
title: "建议检查低置信度字段",
description: `${lowConfidence} 个字段置信度较低(<70%),建议人工确认`,
action: "检查低置信度字段",
};
}
if (mediumConfidence > 0) {
return {
type: "info" as const,
icon: Info,
title: "存在中等置信度字段",
description: `${mediumConfidence} 个字段置信度为中等(70%-90%),建议确认`,
action: "批量确认",
};
}
return {
type: "success" as const,
icon: Sparkles,
title: "可直接确认",
description: "所有字段置信度较高,可以批量确认",
action: "批量确认",
};
};
const suggestion = getSuggestion();
const Icon = suggestion.icon;
const style = config[suggestion.type];
return (
<motion.div
initial={{ opacity: 0, scale: 0.98 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] as const }}
>
<Card className={cn(style.bg, style.border, className)}>
<CardContent className="p-5">
<div className="flex items-start gap-4">
{/* Icon */}
<motion.div
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ delay: 0.1, type: "spring", stiffness: 200 }}
className={cn("p-2.5 rounded-xl", style.iconBg)}
>
<Icon className={cn("w-5 h-5", style.iconColor)} />
</motion.div>
{/* Content */}
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-4">
<div>
<h3 className={cn("font-semibold text-base", style.titleColor)}>
{suggestion.title}
</h3>
<p className={cn("text-sm mt-1", style.descColor)}>
{suggestion.description}
</p>
{suggestion.action && !allConfirmed && onAutoConfirm && (
<Button
onClick={onAutoConfirm}
size="sm"
className={cn("mt-3 text-white btn-press", style.buttonBg)}
>
{suggestion.action}
</Button>
)}
</div>
{/* Progress Stats */}
<div className="text-right shrink-0">
<motion.div
initial={{ opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
className="text-3xl font-bold text-foreground"
>
{confirmedCount}
<span className="text-lg text-muted-foreground">/{totalFields}</span>
</motion.div>
<p className="text-caption text-muted-foreground"></p>
</div>
</div>
{/* Progress Bar */}
<div className="mt-5">
<div className="flex justify-between text-caption text-muted-foreground mb-1.5">
<span></span>
<span>{Math.round(progressPercent)}%</span>
</div>
<div className="h-2 bg-muted rounded-full overflow-hidden">
<motion.div
initial={{ width: 0 }}
animate={{ width: `${progressPercent}%` }}
transition={{ duration: 0.6, delay: 0.3, ease: [0.16, 1, 0.3, 1] as const }}
className={cn("h-full rounded-full", style.progressBg)}
/>
</div>
</div>
{/* Confidence Distribution */}
<div className="mt-5 pt-4 border-t border-border/50">
<p className="text-caption text-muted-foreground mb-3"></p>
<div className="flex flex-wrap gap-4">
<div className="flex items-center gap-2">
<span className="w-2.5 h-2.5 rounded-full bg-emerald-500" />
<span className="text-sm text-muted-foreground">
: <span className="font-semibold text-foreground">{highConfidence}</span>
</span>
</div>
<div className="flex items-center gap-2">
<span className="w-2.5 h-2.5 rounded-full bg-amber-500" />
<span className="text-sm text-muted-foreground">
: <span className="font-semibold text-foreground">{mediumConfidence}</span>
</span>
</div>
<div className="flex items-center gap-2">
<span className="w-2.5 h-2.5 rounded-full bg-red-500" />
<span className="text-sm text-muted-foreground">
: <span className="font-semibold text-foreground">{lowConfidence}</span>
</span>
</div>
</div>
</div>
</div>
</div>
</CardContent>
</Card>
</motion.div>
);
}
export default AISuggestionPanel;
@@ -0,0 +1,46 @@
"use client";
import { cn } from "@/lib/utils";
interface ConfidenceBadgeProps {
confidence: number;
showLabel?: boolean;
className?: string;
}
export function ConfidenceBadge({
confidence,
showLabel = true,
className,
}: ConfidenceBadgeProps) {
const getLevel = (value: number) => {
if (value > 0.9) return "high";
if (value >= 0.7) return "medium";
return "low";
};
const getLabel = (value: number) => {
if (value > 0.9) return "高";
if (value >= 0.7) return "中";
return "低";
};
const level = getLevel(confidence);
const label = getLabel(confidence);
return (
<span
className={cn(
"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium",
level === "high" && "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300",
level === "medium" && "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300",
level === "low" && "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300",
className
)}
>
{showLabel ? label : `${(confidence * 100).toFixed(0)}%`}
</span>
);
}
export default ConfidenceBadge;
@@ -0,0 +1,316 @@
"use client";
import { useState } from "react";
import { motion, AnimatePresence } from "motion/react";
import { ChevronDown, ChevronRight, Eye, Check } from "lucide-react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { ConfidenceBadge } from "./ConfidenceBadge";
import type { FieldMappingResponse } from "@/lib/api/types";
interface FieldMappingTableProps {
mappings: FieldMappingResponse[];
fileName: string;
fileType: string;
onUpdate?: (mappingId: number, standardField: string) => void;
onSkip?: (mappingId: number) => void;
onConfirm?: (mappingId: number) => void;
onConfirmAll?: (mappingIds: number[]) => void;
readOnly?: boolean;
}
const STANDARD_FIELDS = [
{ value: "员工姓名", label: "员工姓名" },
{ value: "工号", label: "工号" },
{ value: "部门", label: "部门" },
{ value: "岗位", label: "岗位" },
{ value: "基本工资", label: "基本工资" },
{ value: "奖金", label: "奖金" },
{ value: "补贴", label: "补贴" },
{ value: "加班费", label: "加班费" },
{ value: "扣款", label: "扣款" },
{ value: "应发工资", label: "应发工资" },
{ value: "实发工资", label: "实发工资" },
{ value: "银行账号", label: "银行账号" },
{ value: "身份证号", label: "身份证号" },
{ value: "社保基数", label: "社保基数" },
{ value: "养老保险", label: "养老保险" },
{ value: "医疗保险", label: "医疗保险" },
{ value: "失业保险", label: "失业保险" },
{ value: "公积金", label: "公积金" },
{ value: "个税", label: "个税" },
{ value: "应税收入", label: "应税收入" },
{ value: "税后收入", label: "税后收入" },
];
export function FieldMappingTable({
mappings,
fileName,
fileType,
onUpdate,
onSkip,
onConfirm,
onConfirmAll,
readOnly = false,
}: FieldMappingTableProps) {
const [expandedRows, setExpandedRows] = useState<Set<number>>(new Set());
const [editingId, setEditingId] = useState<number | null>(null);
const [editValue, setEditValue] = useState("");
const toggleExpand = (id: number) => {
const newExpanded = new Set(expandedRows);
if (newExpanded.has(id)) {
newExpanded.delete(id);
} else {
newExpanded.add(id);
}
setExpandedRows(newExpanded);
};
const startEdit = (id: number, currentValue: string) => {
setEditingId(id);
setEditValue(currentValue);
};
const saveEdit = (id: number) => {
if (onUpdate && editValue) {
onUpdate(id, editValue);
}
setEditingId(null);
setEditValue("");
};
const handleConfirmAll = () => {
if (onConfirmAll) {
const unconfirmedIds = mappings
.filter((m) => !m.confirmed && !m.is_skipped && m.standard_field)
.map((m) => m.id);
onConfirmAll(unconfirmedIds);
}
};
const confirmedCount = mappings.filter((m) => m.confirmed).length;
const unconfirmedCount = mappings.length - confirmedCount;
return (
<Card className="overflow-hidden">
{/* 表头 */}
<div className="bg-muted/50 px-5 py-4 border-b border-border">
<div className="flex items-center justify-between flex-wrap gap-3">
<div className="flex items-center gap-3">
<div className="text-sm font-medium text-foreground">{fileName}</div>
<Badge variant="secondary">{fileType}</Badge>
</div>
<div className="flex items-center gap-4 text-sm">
<span className="text-muted-foreground">
: <span className="font-semibold text-emerald-600">{confirmedCount}</span>
</span>
<span className="text-muted-foreground">
: <span className="font-semibold text-amber-600">{unconfirmedCount}</span>
</span>
{!readOnly && unconfirmedCount > 0 && (
<Button onClick={handleConfirmAll} size="sm" className="btn-press">
<Check className="w-4 h-4 mr-1" />
</Button>
)}
</div>
</div>
</div>
{/* 表格 */}
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border bg-muted/30">
<th className="px-4 py-3 text-left font-medium text-muted-foreground w-10" />
<th className="px-4 py-3 text-left font-medium text-muted-foreground">
</th>
<th className="px-4 py-3 text-left font-medium text-muted-foreground">
</th>
<th className="px-4 py-3 text-center font-medium text-muted-foreground w-24">
</th>
<th className="px-4 py-3 text-center font-medium text-muted-foreground w-20">
</th>
<th className="px-4 py-3 text-right font-medium text-muted-foreground w-36">
</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{mappings.map((mapping, index) => (
<motion.tr
key={mapping.id}
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, delay: index * 0.03 }}
className={cn(
"group hover:bg-muted/30 transition-colors",
mapping.is_skipped && "opacity-50",
mapping.confirmed && "bg-emerald-50/30 dark:bg-emerald-950/10"
)}
>
<td className="px-4 py-3">
<button
onClick={() => toggleExpand(mapping.id)}
className="p-1 hover:bg-muted rounded-md transition-colors"
>
{expandedRows.has(mapping.id) ? (
<ChevronDown className="w-4 h-4 text-muted-foreground" />
) : (
<ChevronRight className="w-4 h-4 text-muted-foreground" />
)}
</button>
</td>
<td className="px-4 py-3 font-medium text-foreground">
{mapping.source_field}
</td>
<td className="px-4 py-3">
{editingId === mapping.id ? (
<div className="flex items-center gap-2">
<select
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
className="flex-1 px-2 py-1.5 border border-input rounded-md text-sm bg-background focus:outline-none focus:ring-2 focus:ring-ring"
>
<option value=""></option>
{STANDARD_FIELDS.map((field) => (
<option key={field.value} value={field.value}>
{field.label}
</option>
))}
</select>
<Button
size="sm"
variant="ghost"
onClick={() => saveEdit(mapping.id)}
className="h-7 w-7 p-0 text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50 dark:hover:bg-emerald-950/30"
>
<Check className="w-4 h-4" />
</Button>
</div>
) : mapping.standard_field ? (
<span className="text-foreground">{mapping.standard_field}</span>
) : (
<span className="text-muted-foreground italic"></span>
)}
</td>
<td className="px-4 py-3 text-center">
<ConfidenceBadge confidence={mapping.confidence} />
</td>
<td className="px-4 py-3 text-center">
{mapping.is_skipped ? (
<Badge variant="secondary" className="text-xs"></Badge>
) : mapping.confirmed ? (
<Badge className="bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300 text-xs font-medium">
</Badge>
) : (
<Badge variant="outline" className="text-xs"></Badge>
)}
</td>
<td className="px-4 py-3">
{!readOnly && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="flex items-center justify-end gap-1"
>
{editingId !== mapping.id && (
<>
<Button
size="sm"
variant="ghost"
onClick={() => startEdit(mapping.id, mapping.standard_field)}
className="h-7 px-2 text-xs text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:hover:bg-blue-950/30"
>
</Button>
{!mapping.confirmed && (
<Button
size="sm"
variant="ghost"
onClick={() => onConfirm?.(mapping.id)}
className="h-7 px-2 text-xs text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50 dark:hover:bg-emerald-950/30"
>
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => onSkip?.(mapping.id)}
className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
>
</Button>
</>
)}
</motion.div>
)}
</td>
</motion.tr>
))}
</tbody>
</table>
{mappings.length === 0 && (
<div className="px-4 py-12 text-center">
<p className="text-muted-foreground"></p>
</div>
)}
</div>
{/* 展开详情 */}
<AnimatePresence>
{Array.from(expandedRows).map((id) => {
const mapping = mappings.find((m) => m.id === id);
if (!mapping || !mapping.sample_values) return null;
return (
<motion.div
key={`detail-${id}`}
initial={{ height: 0, opacity: 0 }}
animate={{ height: "auto", opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.2 }}
className="overflow-hidden"
>
<div className="px-4 py-4 bg-muted/30 border-t border-border">
<div className="space-y-3 max-w-2xl">
{mapping.reasoning && (
<div className="text-sm">
<span className="font-medium text-muted-foreground">: </span>
<span className="text-foreground">{mapping.reasoning}</span>
</div>
)}
<div>
<span className="text-sm font-medium text-muted-foreground">: </span>
<div className="mt-1.5 flex flex-wrap gap-2">
{(mapping.sample_values as unknown as string[]).slice(0, 5).map((value, idx) => (
<span
key={idx}
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-background border border-border rounded-md text-xs text-foreground"
>
<Eye className="w-3 h-3 text-muted-foreground" />
{String(value)}
</span>
))}
</div>
</div>
</div>
</div>
</motion.div>
);
})}
</AnimatePresence>
</Card>
);
}
export default FieldMappingTable;
+23
View File
@@ -0,0 +1,23 @@
'use client';
import { useEffect, useState } from 'react';
/**
* 主题提供者组件
* 由于 next-themes 在 React 19 下有兼容性问题,暂时使用简化的实现
* 仅传递 children,不进行主题切换
*/
export function ThemeProvider({ children, ..._props }: { children: React.ReactNode }) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
// SSR 时返回 children,避免 hydration mismatch
if (!mounted) {
return <>{children}</>;
}
return <>{children}</>;
}
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }
+56
View File
@@ -0,0 +1,56 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
+89
View File
@@ -0,0 +1,89 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const cardVariants = cva(
"rounded-lg border bg-card text-card-foreground shadow-sm",
{
variants: {
variant: {
default: "",
destructive: "border-red-200 bg-red-50",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof cardVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
className={cn(cardVariants({ variant }), className)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
+122
View File
@@ -0,0 +1,122 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}
+24
View File
@@ -0,0 +1,24 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export type InputProps = React.InputHTMLAttributes<HTMLInputElement>
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+160
View File
@@ -0,0 +1,160 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
}
+117
View File
@@ -0,0 +1,117 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}
+55
View File
@@ -0,0 +1,55 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }
+6
View File
@@ -5,6 +5,12 @@ import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
{
rules: {
// 禁用过度严格的 setState 规则,允许在 effect 中调用数据加载函数
"react-hooks/set-state-in-effect": "off",
},
},
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
+122
View File
@@ -0,0 +1,122 @@
import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import type { ApiError, ApiResponse } from './types';
// 创建 Axios 实例
const createApiClient = (): AxiosInstance => {
const baseURL = process.env.NEXT_PUBLIC_API_URL || '';
const instance = axios.create({
baseURL,
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
});
// 请求拦截器
instance.interceptors.request.use(
(config) => {
// 自动添加 JWT Token
if (typeof window !== 'undefined') {
const token = localStorage.getItem('auth_token');
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
// 添加企业 ID
const companyId = localStorage.getItem('company_id');
if (companyId && config.headers) {
config.headers['X-Company-ID'] = companyId;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 响应拦截器
instance.interceptors.response.use(
(response: AxiosResponse) => {
return response;
},
(error: AxiosError<ApiError>) => {
// 统一错误处理
const apiError: ApiError = {
code: 'UNKNOWN_ERROR',
message: '未知错误',
};
if (error.response) {
// 服务器返回错误
const { data, status } = error.response;
if (data && typeof data === 'object' && 'error' in data) {
const errorData = data as { error: { code: string; message: string; details?: unknown } };
apiError.code = errorData.error.code;
apiError.message = errorData.error.message;
apiError.details = errorData.error.details;
} else {
apiError.code = `HTTP_${status}`;
apiError.message = error.message;
}
// 401 未授权 - 跳转登录
if (status === 401) {
if (typeof window !== 'undefined') {
localStorage.removeItem('auth_token');
localStorage.removeItem('company_id');
window.location.href = '/login';
}
}
} else if (error.request) {
// 请求发送但无响应
apiError.code = 'NETWORK_ERROR';
apiError.message = '网络错误,请检查连接';
} else {
// 其他错误
apiError.message = error.message;
}
return Promise.reject(apiError);
}
);
return instance;
};
// API 客户端单例
export const apiClient = createApiClient();
// 通用请求方法封装
export const api = {
get: async <T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
const response = await apiClient.get<T>(url, config);
return { data: response.data, status: response.status };
},
post: async <T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
const response = await apiClient.post<T>(url, data, config);
return { data: response.data, status: response.status };
},
put: async <T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
const response = await apiClient.put<T>(url, data, config);
return { data: response.data, status: response.status };
},
patch: async <T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
const response = await apiClient.patch<T>(url, data, config);
return { data: response.data, status: response.status };
},
delete: async <T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
const response = await apiClient.delete<T>(url, config);
return { data: response.data, status: response.status };
},
};
export default apiClient;
+96
View File
@@ -0,0 +1,96 @@
/**
* API 端点常量
*/
export const ENDPOINTS = {
// 健康检查
HEALTH: '/api/health',
// 认证相关
AUTH: {
LOGIN: '/api/auth/login',
LOGOUT: '/api/auth/logout',
ME: '/api/auth/me',
REFRESH: '/api/auth/refresh',
},
// 企业相关
COMPANY: {
LIST: '/api/companies',
DETAIL: (id: number | string) => `/api/companies/${id}`,
CREATE: '/api/companies',
UPDATE: (id: number | string) => `/api/companies/${id}`,
DELETE: (id: number | string) => `/api/companies/${id}`,
},
// 用户相关
USER: {
LIST: '/api/users',
DETAIL: (id: number | string) => `/api/users/${id}`,
CREATE: '/api/users',
UPDATE: (id: number | string) => `/api/users/${id}`,
DELETE: (id: number | string) => `/api/users/${id}`,
UPDATE_ROLE: (id: number | string) => `/api/users/${id}/role`,
},
// 文件上传
FILE: {
UPLOAD: '/api/files/upload',
DOWNLOAD: (id: number | string) => `/api/files/${id}/download`,
DELETE: (id: number | string) => `/api/files/${id}`,
},
// 任务相关
TASK: {
LIST: '/api/tasks',
STATS: '/api/tasks/stats',
DETAIL: (id: number | string) => `/api/tasks/${id}`,
CREATE: '/api/tasks',
UPDATE: (id: number | string) => `/api/tasks/${id}`,
DELETE: (id: number | string) => `/api/tasks/${id}`,
RECONCILE: (id: number | string) => `/api/reconciliation/execute/${id}`,
RESULT: (id: number | string) => `/api/reconciliation/result/${id}`,
EXPORT: (id: number | string) => `/api/exports/task/${id}`,
},
// 异常相关
ANOMALY: {
LIST: '/api/anomalies',
DETAIL: (id: number | string) => `/api/anomalies/${id}`,
CONFIRM: (id: number | string) => `/api/anomalies/${id}/confirm`,
IGNORE: (id: number | string) => `/api/anomalies/${id}/ignore`,
},
// 分析相关
ANALYSIS: {
LABOR_COST: (taskId: number | string) => `/api/analysis/labor-cost/${taskId}`,
TREND: '/api/analysis/trend',
SUMMARY: '/api/analysis/summary',
},
// 凭证相关
VOUCHER: {
GENERATE: (taskId: number | string) => `/api/vouchers/generate/${taskId}`,
EXPORT: (taskId: number | string) => `/api/vouchers/export/${taskId}`,
},
// 审计日志
AUDIT: {
LIST: '/api/audit-logs',
},
// 字段映射
MAPPING: {
LIST: '/api/mappings',
TASK_MAPPINGS: (taskId: number | string) => `/api/mappings/task/${taskId}`,
RECOGNIZE: '/api/mappings/recognize',
CONFIRM: '/api/mappings/confirm',
DETAIL: (mappingId: number | string) => `/api/mappings/${mappingId}`,
UPDATE: (mappingId: number | string) => `/api/mappings/${mappingId}`,
SAVE_AS_RULE: (mappingId: number | string) => `/api/mappings/${mappingId}/save-as-rule`,
RULES_LIST: '/api/mappings/rules/list',
RULE_STATUS: (ruleId: number | string) => `/api/mappings/rules/${ruleId}/status`,
RULE_DELETE: (ruleId: number | string) => `/api/mappings/rules/${ruleId}`,
},
} as const;
export default ENDPOINTS;
+133
View File
@@ -0,0 +1,133 @@
/**
* API 响应类型
*/
export interface ApiResponse<T = unknown> {
data: T;
status: number;
}
/**
* API 错误类型
*/
export interface ApiError {
code: string;
message: string;
details?: unknown;
}
/**
* 分页响应类型
*/
export interface PaginatedResponse<T = unknown> {
items: T[];
total: number;
page: number;
page_size: number;
total_pages: number;
}
/**
* 分页请求参数
*/
export interface PaginationParams {
page?: number;
page_size?: number;
}
/**
* 通用 ID 参数
*/
export interface IdParams {
id: number | string;
}
// ===== 字段映射类型 =====
export interface FieldMappingResponse {
id: number;
company_id: number;
file_id: number;
source_field: string;
standard_field: string;
confidence: number;
reasoning?: string;
sample_values?: unknown[];
is_skipped: boolean;
confirmed: boolean;
confirmed_by?: number;
confirmed_at?: string;
}
export interface FileMappingSummary {
file_id: number;
file_type: string;
file_name: string;
total_fields: number;
confirmed_fields: number;
high_confidence: number;
medium_confidence: number;
low_confidence: number;
mappings: FieldMappingResponse[];
}
export interface TaskMappingOverview {
task_id: number;
total_files: number;
total_fields: number;
confirmed_fields: number;
needs_review: boolean;
files: FileMappingSummary[];
}
export interface CompanyRuleResponse {
id: number;
company_id: number;
rule_type: string;
match_condition: Record<string, unknown>;
target_value: string;
priority: number;
status: string;
description?: string;
match_count: number;
last_used_at?: string;
created_at: string;
updated_at: string;
}
export interface ConfirmMappingsRequest {
mapping_ids: number[];
}
export interface ConfirmMappingsResponse {
confirmed_count: number;
mappings: FieldMappingResponse[];
}
export interface SaveAsRuleResponse {
rule_id: number;
source_field: string;
target_field: string;
message: string;
}
// ===== 任务类型 =====
export interface ReconciliationTask {
id: number;
company_id: number;
name: string;
period: string;
status: string;
file_ids?: Record<string, number>;
mapping_completed: boolean;
mapping_confirmed_at?: string;
mapping_confirmed_by?: number;
total_employees?: number;
matched_count?: number;
exception_count?: number;
reconciliation_result?: unknown;
error_message?: string;
created_by?: number;
created_at: string;
updated_at: string;
}
+48
View File
@@ -0,0 +1,48 @@
import { useCallback, useState } from 'react';
/**
* 异步请求状态
*/
export interface AsyncState<T> {
data: T | null;
loading: boolean;
error: Error | null;
}
/**
* 异步请求 Hook
* 用于管理异步请求的加载状态、数据和错误
*/
export function useAsync<T = unknown>() {
const [state, setState] = useState<AsyncState<T>>({
data: null,
loading: false,
error: null,
});
const execute = useCallback(async (asyncFunction: () => Promise<T>) => {
setState({ data: null, loading: true, error: null });
try {
const result = await asyncFunction();
setState({ data: result, loading: false, error: null });
return result;
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
setState({ data: null, loading: false, error: err });
throw err;
}
}, []);
const reset = useCallback(() => {
setState({ data: null, loading: false, error: null });
}, []);
return {
...state,
execute,
reset,
};
}
export default useAsync;
+77
View File
@@ -0,0 +1,77 @@
'use client';
import { useCallback, useState } from 'react';
/**
* 确认对话框配置
*/
export interface ConfirmOptions {
title?: string;
message: string;
confirmText?: string;
cancelText?: string;
type?: 'info' | 'warning' | 'danger';
}
/**
* 确认对话框状态
*/
interface ConfirmState {
isOpen: boolean;
options: ConfirmOptions | null;
resolve: ((value: boolean) => void) | null;
}
/**
* 确认对话框 Hook
* 用于显示确认对话框并等待用户响应
*/
export function useConfirm() {
const [state, setState] = useState<ConfirmState>({
isOpen: false,
options: null,
resolve: null,
});
const confirm = useCallback((options: ConfirmOptions): Promise<boolean> => {
return new Promise((resolve) => {
setState({
isOpen: true,
options: {
title: '确认',
confirmText: '确定',
cancelText: '取消',
type: 'info',
...options,
},
resolve,
});
});
}, []);
const handleConfirm = useCallback(() => {
if (state.resolve) {
state.resolve(true);
}
setState({ isOpen: false, options: null, resolve: null });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state.resolve]);
const handleCancel = useCallback(() => {
if (state.resolve) {
state.resolve(false);
}
setState({ isOpen: false, options: null, resolve: null });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state.resolve]);
return {
confirm,
isOpen: state.isOpen,
options: state.options,
handleConfirm,
handleCancel,
};
}
export default useConfirm;
+69
View File
@@ -0,0 +1,69 @@
import { useCallback, useEffect, useRef, useState } from 'react';
/**
* 防抖 Hook
* 延迟执行函数,直到停止调用一段时间后才执行
*
* @param value - 要防抖的值
* @param delay - 延迟时间(毫秒)
* @returns 防抖后的值
*/
export function useDebounce<T>(value: T, delay: number = 500): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
/**
* 防抖回调 Hook
* 延迟执行回调函数
*
* @param callback - 要防抖的回调函数
* @param delay - 延迟时间(毫秒)
* @returns 防抖后的回调函数
*/
export function useDebouncedCallback<T extends (...args: unknown[]) => unknown>(
callback: T,
delay: number = 500
): (...args: Parameters<T>) => void {
const timeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
const callbackRef = useRef<T>(callback);
// 保持最新的 callback 引用
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return useCallback(
(...args: Parameters<T>) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callbackRef.current(...args);
}, delay);
},
[delay]
);
}
export default useDebounce;
+49
View File
@@ -0,0 +1,49 @@
import { useAuthStore } from '@/lib/stores/auth-store';
/**
* 权限检查 Hook
*/
export function usePermission() {
const { user } = useAuthStore();
/**
* 检查用户是否有指定权限
*/
const hasPermission = (permission: string): boolean => {
if (!user) return false;
return user.permissions?.includes(permission) ?? false;
};
/**
* 检查用户是否有指定角色
*/
const hasRole = (role: string): boolean => {
if (!user) return false;
return user.role === role;
};
/**
* 检查用户是否有任一权限
*/
const hasAnyPermission = (permissions: string[]): boolean => {
if (!user) return false;
return permissions.some((permission) => hasPermission(permission));
};
/**
* 检查用户是否拥有所有权限
*/
const hasAllPermissions = (permissions: string[]): boolean => {
if (!user) return false;
return permissions.every((permission) => hasPermission(permission));
};
return {
hasPermission,
hasRole,
hasAnyPermission,
hasAllPermissions,
};
}
export default usePermission;
+90
View File
@@ -0,0 +1,90 @@
'use client';
import { useCallback, useState } from 'react';
/**
* Toast 消息类型
*/
export type ToastType = 'success' | 'error' | 'info' | 'warning';
/**
* Toast 消息接口
*/
export interface Toast {
id: string;
type: ToastType;
message: string;
duration?: number;
}
/**
* Toast Hook
* 用于显示全局通知消息
*/
export function useToast() {
const [toasts, setToasts] = useState<Toast[]>([]);
const removeToast = useCallback((id: string) => {
setToasts((prev) => prev.filter((toast) => toast.id !== id));
}, []);
const addToast = useCallback((type: ToastType, message: string, duration: number = 3000) => {
const id = `toast-${Date.now()}-${Math.random()}`;
const toast: Toast = { id, type, message, duration };
setToasts((prev) => [...prev, toast]);
if (duration > 0) {
setTimeout(() => {
removeToast(id);
}, duration);
}
return id;
}, [removeToast]);
const success = useCallback(
(message: string, duration?: number) => {
return addToast('success', message, duration);
},
[addToast]
);
const error = useCallback(
(message: string, duration?: number) => {
return addToast('error', message, duration);
},
[addToast]
);
const info = useCallback(
(message: string, duration?: number) => {
return addToast('info', message, duration);
},
[addToast]
);
const warning = useCallback(
(message: string, duration?: number) => {
return addToast('warning', message, duration);
},
[addToast]
);
const clear = useCallback(() => {
setToasts([]);
}, []);
return {
toasts,
addToast,
removeToast,
success,
error,
info,
warning,
clear,
};
}
export default useToast;

Some files were not shown because too many files have changed in this diff Show More