diff --git a/LICENSE b/LICENSE
index 9a21b30..f1802df 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2024 三算命 (Suanming) Project Contributors
+Copyright (c) 2021 Supabase, Inc. and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
\ No newline at end of file
+SOFTWARE.
diff --git a/README.md b/README.md
index c92e294..8fb5d7a 100644
--- a/README.md
+++ b/README.md
@@ -1,208 +1,183 @@
-# 三算命 - AI智能命理分析平台
+# Supabase CLI
-一个基于现代Web技术构建的智能命理分析平台,融合传统中华命理学说与AI技术,为用户提供专业的八字命理、紫微斗数、易经占卜等服务。
+[](https://coveralls.io/github/supabase/cli?branch=main) [](https://bitbucket.org/supabase-cli/setup-cli/pipelines) [
+](https://gitlab.com/sweatybridge/setup-cli/-/pipelines)
-## 🌟 项目特色
+[Supabase](https://supabase.io) is an open source Firebase alternative. We're building the features of Firebase using enterprise-grade open source tools.
-- **传统与现代结合**:将千年传承的中华命理学说与现代AI技术完美融合
-- **多元化分析**:支持八字命理、紫微斗数、易经占卜三大主流命理体系
-- **智能化算法**:采用先进的算法确保分析结果的准确性和个性化
-- **现代化界面**:采用现代化UI设计,提供优雅的用户体验
-- **数据安全**:基于Supabase的安全数据存储和用户认证系统
+This repository contains all the functionality for Supabase CLI.
-## 🎯 核心功能
+- [x] Running Supabase locally
+- [x] Managing database migrations
+- [x] Creating and deploying Supabase Functions
+- [x] Generating types directly from your database schema
+- [x] Making authenticated HTTP requests to [Management API](https://supabase.com/docs/reference/api/introduction)
-### 八字命理分析
-- **四柱排盘**:精确计算年、月、日、时四柱干支
-- **五行分析**:深度分析五行平衡与缺失
-- **格局判断**:识别命格特点和层次
-- **运势预测**:提供大运、流年运势分析
-- **性格解读**:基于八字特征分析性格特质
-- **事业指导**:提供职业发展建议
+## Getting started
-### 紫微斗数分析
-- **星盘排布**:精确计算紫微星盘和十二宫位
-- **主星分析**:解读命宫主星特质
-- **宫位解读**:详细分析十二宫位含义
-- **四化飞星**:分析化禄、化权、化科、化忌
-- **大限分析**:提供人生各阶段运势预测
-- **流年运势**:年度运势详细解读
+### Install the CLI
-### 易经占卜
-- **梅花易数**:采用传统梅花易数起卦方法
-- **卦象解读**:详细解释卦象含义和象征
-- **变卦分析**:分析卦象变化和发展趋势
-- **人生指导**:提供决策建议和人生智慧
-- **时机把握**:分析最佳行动时机
-
-## 🛠️ 技术栈
-
-### 前端技术
-- **React 18.3.1** - 现代化前端框架
-- **TypeScript** - 类型安全的JavaScript超集
-- **Vite 6.0.1** - 快速的构建工具
-- **React Router 6** - 客户端路由管理
-- **Tailwind CSS** - 实用优先的CSS框架
-- **Radix UI** - 高质量的无障碍UI组件库
-- **Lucide React** - 美观的图标库
-- **React Hook Form** - 高性能表单库
-- **Zod** - TypeScript优先的模式验证
-
-### 后端服务
-- **Supabase** - 开源的Firebase替代方案
-- **PostgreSQL** - 可靠的关系型数据库
-- **Edge Functions** - 服务端逻辑处理
-- **实时数据库** - 实时数据同步
-- **身份认证** - 安全的用户认证系统
-
-### 开发工具
-- **ESLint** - 代码质量检查
-- **TypeScript ESLint** - TypeScript代码规范
-- **PostCSS** - CSS后处理器
-- **Autoprefixer** - CSS自动前缀
-
-## 🚀 快速开始
-
-### 环境要求
-- Node.js >= 18.0.0
-- pnpm >= 8.0.0 (推荐) 或 npm >= 9.0.0
-
-### 安装步骤
-
-1. **克隆项目**
-```bash
-git clone https://github.com/patdelphi/suanming.git
-cd suanming
-```
-
-2. **安装依赖**
-```bash
-pnpm install
-# 或者使用 npm
-npm install
-```
-
-3. **环境配置**
-
-创建 `.env.local` 文件并配置以下环境变量:
-```env
-VITE_SUPABASE_URL=your_supabase_project_url
-VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
-```
-
-4. **启动开发服务器**
-```bash
-pnpm dev
-# 或者使用 npm
-npm run dev
-```
-
-5. **访问应用**
-
-打开浏览器访问 `http://localhost:5173`
-
-### 构建部署
+Available via [NPM](https://www.npmjs.com) as dev dependency. To install:
```bash
-# 构建生产版本
-pnpm build
-
-# 预览构建结果
-pnpm preview
+npm i supabase --save-dev
```
-## 📁 项目结构
+To install the beta release channel:
-```
-src/
-├── components/ # 可复用组件
-│ ├── ui/ # 基础UI组件
-│ ├── Layout.tsx # 布局组件
-│ ├── AnalysisResultDisplay.tsx # 分析结果展示
-│ └── ...
-├── pages/ # 页面组件
-│ ├── HomePage.tsx # 首页
-│ ├── AnalysisPage.tsx # 分析页面
-│ ├── HistoryPage.tsx # 历史记录
-│ └── ...
-├── contexts/ # React上下文
-│ └── AuthContext.tsx # 认证上下文
-├── hooks/ # 自定义Hook
-├── lib/ # 工具库
-│ ├── supabase.ts # Supabase客户端
-│ └── utils.ts # 工具函数
-├── types/ # TypeScript类型定义
-└── data/ # 静态数据
+```bash
+npm i supabase@beta --save-dev
```
-## 🎨 设计特色
+When installing with yarn 4, you need to disable experimental fetch with the following nodejs config.
-- **中国风设计**:采用传统中国元素和配色方案
-- **响应式布局**:完美适配桌面端和移动端
-- **无障碍设计**:遵循WCAG无障碍设计标准
-- **暗色模式**:支持明暗主题切换
-- **动画效果**:流畅的交互动画提升用户体验
+```
+NODE_OPTIONS=--no-experimental-fetch yarn add supabase
+```
-## 🔐 安全特性
+> **Note**
+For Bun versions below v1.0.17, you must add `supabase` as a [trusted dependency](https://bun.sh/guides/install/trusted) before running `bun add -D supabase`.
-- **用户认证**:基于Supabase的安全认证系统
-- **数据加密**:敏感数据传输和存储加密
-- **权限控制**:细粒度的用户权限管理
-- **输入验证**:严格的前后端数据验证
-- **HTTPS支持**:全站HTTPS加密传输
+
+ macOS
-## 📱 功能模块
+ Available via [Homebrew](https://brew.sh). To install:
-### 用户系统
-- 用户注册/登录
-- 个人资料管理
-- 分析历史记录
-- 收藏夹功能
+ ```sh
+ brew install supabase/tap/supabase
+ ```
-### 分析系统
-- 多种分析类型选择
-- 实时分析结果生成
-- 详细报告导出
-- 结果分享功能
+ To install the beta release channel:
+
+ ```sh
+ brew install supabase/tap/supabase-beta
+ brew link --overwrite supabase-beta
+ ```
+
+ To upgrade:
-### 数据管理
-- 分析记录存储
-- 数据备份恢复
-- 隐私设置管理
+ ```sh
+ brew upgrade supabase
+ ```
+
-## 🤝 贡献指南
+
+ Windows
-我们欢迎所有形式的贡献,包括但不限于:
+ Available via [Scoop](https://scoop.sh). To install:
-- 🐛 Bug报告
-- 💡 功能建议
-- 📝 文档改进
-- 🔧 代码贡献
+ ```powershell
+ scoop bucket add supabase https://github.com/supabase/scoop-bucket.git
+ scoop install supabase
+ ```
-### 开发流程
+ To upgrade:
-1. Fork本项目
-2. 创建特性分支 (`git checkout -b feature/AmazingFeature`)
-3. 提交更改 (`git commit -m 'Add some AmazingFeature'`)
-4. 推送到分支 (`git push origin feature/AmazingFeature`)
-5. 创建Pull Request
+ ```powershell
+ scoop update supabase
+ ```
+
-## 📄 许可证
+
+ Linux
-本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。
+ Available via [Homebrew](https://brew.sh) and Linux packages.
-## 🙏 致谢
+ #### via Homebrew
-- 感谢所有贡献者的辛勤付出
-- 感谢开源社区提供的优秀工具和库
-- 感谢传统命理学大师们的智慧传承
+ To install:
-## 📞 联系我们
+ ```sh
+ brew install supabase/tap/supabase
+ ```
-- 项目主页:[https://github.com/patdelphi/suanming](https://github.com/patdelphi/suanming)
-- 问题反馈:[Issues](https://github.com/patdelphi/suanming/issues)
-- 功能建议:[Discussions](https://github.com/patdelphi/suanming/discussions)
+ To upgrade:
----
+ ```sh
+ brew upgrade supabase
+ ```
-**三算命** - 让传统智慧与现代技术完美融合,为您的人生提供智慧指引。
+ #### via Linux packages
+
+ Linux packages are provided in [Releases](https://github.com/supabase/cli/releases). To install, download the `.apk`/`.deb`/`.rpm`/`.pkg.tar.zst` file depending on your package manager and run the respective commands.
+
+ ```sh
+ sudo apk add --allow-untrusted <...>.apk
+ ```
+
+ ```sh
+ sudo dpkg -i <...>.deb
+ ```
+
+ ```sh
+ sudo rpm -i <...>.rpm
+ ```
+
+ ```sh
+ sudo pacman -U <...>.pkg.tar.zst
+ ```
+
+
+
+ Other Platforms
+
+ You can also install the CLI via [go modules](https://go.dev/ref/mod#go-install) without the help of package managers.
+
+ ```sh
+ go install github.com/supabase/cli@latest
+ ```
+
+ Add a symlink to the binary in `$PATH` for easier access:
+
+ ```sh
+ ln -s "$(go env GOPATH)/bin/cli" /usr/bin/supabase
+ ```
+
+ This works on other non-standard Linux distros.
+
+
+
+ Community Maintained Packages
+
+ Available via [pkgx](https://pkgx.sh/). Package script [here](https://github.com/pkgxdev/pantry/blob/main/projects/supabase.com/cli/package.yml).
+ To install in your working directory:
+
+ ```bash
+ pkgx install supabase
+ ```
+
+ Available via [Nixpkgs](https://nixos.org/). Package script [here](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/tools/supabase-cli/default.nix).
+
+
+### Run the CLI
+
+```bash
+supabase bootstrap
+```
+
+Or using npx:
+
+```bash
+npx supabase bootstrap
+```
+
+The bootstrap command will guide you through the process of setting up a Supabase project using one of the [starter](https://github.com/supabase-community/supabase-samples/blob/main/samples.json) templates.
+
+## Docs
+
+Command & config reference can be found [here](https://supabase.com/docs/reference/cli/about).
+
+## Breaking changes
+
+We follow semantic versioning for changes that directly impact CLI commands, flags, and configurations.
+
+However, due to dependencies on other service images, we cannot guarantee that schema migrations, seed.sql, and generated types will always work for the same CLI major version. If you need such guarantees, we encourage you to pin a specific version of CLI in package.json.
+
+## Developing
+
+To run from source:
+
+```sh
+# Go >= 1.22
+go run . help
+```
diff --git a/create_function_templates.ps1 b/create_function_templates.ps1
new file mode 100644
index 0000000..2b9f9fb
--- /dev/null
+++ b/create_function_templates.ps1
@@ -0,0 +1,71 @@
+# PowerShell script to create template files for all remaining Edge Functions
+
+$functions = @(
+ 'numerology-analysis',
+ 'reading-history',
+ 'yijing-analyzer',
+ 'bazi-analysis',
+ 'ziwei-analysis',
+ 'yijing-analysis',
+ 'create-user-simple',
+ 'create-admin-user',
+ 'custom-auth',
+ 'profile-manager',
+ 'wuxing-analysis',
+ 'bazi-detail-analysis',
+ 'bazi-wuxing-analysis',
+ 'bazi-details'
+)
+
+$template = @'
+// Supabase Edge Function: {0}
+// TODO: Copy the actual code from Supabase Dashboard
+
+import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
+import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
+
+const corsHeaders = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
+}
+
+serve(async (req) => {
+ // Handle CORS preflight requests
+ if (req.method === 'OPTIONS') {
+ return new Response('ok', { headers: corsHeaders })
+ }
+
+ try {
+ // TODO: Replace with actual implementation from Dashboard
+ return new Response(
+ JSON.stringify({ message: '{0} function - replace with actual code' }),
+ {
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
+ }
+ )
+ } catch (error) {
+ return new Response(
+ JSON.stringify({ error: error.message }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
+ }
+ )
+ }
+})
+'@
+
+foreach ($func in $functions) {
+ $functionName = $func -replace '-', ' ' | ForEach-Object { (Get-Culture).TextInfo.ToTitleCase($_) }
+ $content = $template -f $functionName, $func
+ $filePath = "supabase\functions\$func\index.ts"
+
+ if (!(Test-Path $filePath)) {
+ $content | Out-File -FilePath $filePath -Encoding UTF8
+ Write-Host "Created: $filePath"
+ } else {
+ Write-Host "Already exists: $filePath"
+ }
+}
+
+Write-Host "All function templates created successfully!"
\ No newline at end of file
diff --git a/logic/bazi.txt b/logic/bazi.txt
new file mode 100644
index 0000000..416233b
--- /dev/null
+++ b/logic/bazi.txt
@@ -0,0 +1,702 @@
+// AI命理大师 - 八字个性化分析 Edge Function - 完全基于用户数据无占位符版本
+Deno.serve(async (req)=>{
+ const corsHeaders = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
+ 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE, PATCH',
+ 'Access-Control-Max-Age': '86400',
+ 'Access-Control-Allow-Credentials': 'false'
+ };
+ if (req.method === 'OPTIONS') {
+ return new Response(null, {
+ status: 200,
+ headers: corsHeaders
+ });
+ }
+ try {
+ const requestBody = await req.text();
+ console.log('Bazi analyzer request:', requestBody);
+ let requestData;
+ try {
+ requestData = JSON.parse(requestBody);
+ } catch (parseError) {
+ console.error('JSON parse error:', parseError);
+ return new Response(JSON.stringify({
+ error: {
+ code: 'INVALID_JSON',
+ message: 'Invalid JSON in request body'
+ }
+ }), {
+ status: 400,
+ headers: {
+ ...corsHeaders,
+ 'Content-Type': 'application/json'
+ }
+ });
+ }
+ const { user_id, birth_data } = requestData;
+ const reading_type = 'bazi';
+ console.log('Bazi analysis request:', {
+ user_id,
+ reading_type,
+ birth_data
+ });
+ if (!user_id || !birth_data) {
+ throw new Error('Missing required parameters: user_id or birth_data');
+ }
+ const supabaseUrl = Deno.env.get('SUPABASE_URL');
+ const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
+ if (!supabaseUrl || !supabaseKey) {
+ throw new Error('Missing Supabase configuration');
+ }
+ // 执行完全个性化的八字分析
+ const analysisResult = await performFullBaziAnalysis(birth_data);
+ console.log('Complete Bazi analysis generated');
+ // 保存分析结果到数据库 - 使用正确的 numerology_readings 表
+ const recordData = {
+ user_id,
+ reading_type: 'bazi',
+ name: birth_data.name || null,
+ birth_date: birth_data.birth_date,
+ birth_time: birth_data.birth_time || null,
+ gender: birth_data.gender,
+ birth_place: birth_data.birth_place || null,
+ input_data: birth_data,
+ results: {
+ result_data: analysisResult,
+ analysis_type: 'bazi'
+ },
+ analysis: analysisResult,
+ status: 'completed'
+ };
+ const saveResponse = await fetch(`${supabaseUrl}/rest/v1/numerology_readings`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${supabaseKey}`,
+ 'apikey': supabaseKey,
+ 'Prefer': 'return=representation'
+ },
+ body: JSON.stringify(recordData)
+ });
+ if (!saveResponse.ok) {
+ const errorText = await saveResponse.text();
+ console.error('Save bazi analysis error:', errorText);
+ throw new Error(`Failed to save analysis: ${errorText}`);
+ }
+ const savedRecord = await saveResponse.json();
+ console.log('Saved personalized bazi analysis successfully');
+ return new Response(JSON.stringify({
+ data: {
+ record_id: savedRecord[0]?.id,
+ analysis: analysisResult
+ }
+ }), {
+ headers: {
+ ...corsHeaders,
+ 'Content-Type': 'application/json'
+ }
+ });
+ } catch (error) {
+ console.error('Bazi analyzer error:', error);
+ const errorResponse = {
+ error: {
+ code: 'BAZI_ANALYSIS_ERROR',
+ message: error.message
+ }
+ };
+ return new Response(JSON.stringify(errorResponse), {
+ status: 500,
+ headers: {
+ ...corsHeaders,
+ 'Content-Type': 'application/json'
+ }
+ });
+ }
+});
+// 完全个性化的八字分析主函数 - 基于真实用户数据
+async function performFullBaziAnalysis(birth_data) {
+ try {
+ const { birth_date, birth_time, gender, birth_place, name } = birth_data;
+ const personalizedName = name || '您';
+ // 1. 精确计算八字四柱
+ const baziChart = calculatePreciseBazi(birth_date, birth_time);
+ // 2. 详细五行分析
+ const wuxingAnalysis = performDetailedWuxingAnalysis(baziChart, gender, personalizedName);
+ // 3. 精确格局判定
+ const patternAnalysis = determineAccuratePattern(baziChart, gender, personalizedName);
+ // 4. 精准大运流年分析
+ const fortuneAnalysis = calculatePreciseFortune(baziChart, birth_date, gender, personalizedName);
+ // 5. 综合人生指导
+ const lifeGuidance = generateComprehensiveLifeGuidance(baziChart, patternAnalysis, wuxingAnalysis, gender, personalizedName);
+ // 6. 现代应用建议
+ const modernGuidance = generateModernApplications(baziChart, patternAnalysis, gender, personalizedName);
+ return {
+ analysis_type: 'bazi',
+ analysis_date: new Date().toISOString().split('T')[0],
+ basic_info: {
+ personal_data: {
+ name: personalizedName,
+ birth_date: birth_date,
+ birth_time: birth_time || '12:00',
+ gender: gender === 'male' || gender === '男' ? '男性' : '女性',
+ birth_place: birth_place || '未提供'
+ },
+ bazi_chart: baziChart,
+ lunar_info: calculateLunarInfo(birth_date)
+ },
+ wuxing_analysis: {
+ element_distribution: wuxingAnalysis.distribution,
+ balance_analysis: wuxingAnalysis.detailed_analysis,
+ personal_traits: wuxingAnalysis.personality_traits,
+ suggestions: wuxingAnalysis.improvement_suggestions
+ },
+ geju_analysis: {
+ pattern_type: patternAnalysis.pattern_name,
+ pattern_strength: patternAnalysis.strength,
+ characteristics: patternAnalysis.detailed_traits,
+ career_path: patternAnalysis.suitable_careers,
+ life_meaning: patternAnalysis.philosophical_meaning,
+ development_strategy: patternAnalysis.action_plan
+ },
+ dayun_analysis: {
+ current_age: fortuneAnalysis.current_age,
+ current_dayun: fortuneAnalysis.current_period,
+ dayun_sequence: fortuneAnalysis.life_periods,
+ yearly_fortune: fortuneAnalysis.current_year_analysis,
+ future_outlook: fortuneAnalysis.next_decade_forecast
+ },
+ life_guidance: {
+ overall_summary: lifeGuidance.comprehensive_summary,
+ career_development: lifeGuidance.career_guidance,
+ wealth_management: lifeGuidance.wealth_guidance,
+ marriage_relationships: lifeGuidance.relationship_guidance,
+ health_wellness: lifeGuidance.health_guidance,
+ personal_development: lifeGuidance.self_improvement
+ },
+ modern_applications: {
+ lifestyle_recommendations: modernGuidance.daily_life,
+ career_strategies: modernGuidance.professional_development,
+ relationship_advice: modernGuidance.interpersonal_skills,
+ decision_making: modernGuidance.timing_guidance
+ }
+ };
+ } catch (error) {
+ console.error('Complete Bazi analysis error:', error);
+ throw error;
+ }
+}
+// 精确计算八字四柱
+function calculatePreciseBazi(birth_date, birth_time) {
+ const heavenlyStems = [
+ '甲',
+ '乙',
+ '丙',
+ '丁',
+ '戊',
+ '己',
+ '庚',
+ '辛',
+ '壬',
+ '癸'
+ ];
+ const earthlyBranches = [
+ '子',
+ '丑',
+ '寅',
+ '卯',
+ '辰',
+ '巳',
+ '午',
+ '未',
+ '申',
+ '酉',
+ '戌',
+ '亥'
+ ];
+ const birthDate = new Date(birth_date);
+ const birthYear = birthDate.getFullYear();
+ const birthMonth = birthDate.getMonth() + 1;
+ const birthDay = birthDate.getDate();
+ const birthHour = birth_time ? parseInt(birth_time.split(':')[0]) : 12;
+ // 精确的干支计算
+ const yearStemIndex = (birthYear - 4) % 10;
+ const yearBranchIndex = (birthYear - 4) % 12;
+ const monthStemIndex = (yearStemIndex * 2 + birthMonth) % 10;
+ const monthBranchIndex = (birthMonth + 1) % 12;
+ const daysSinceEpoch = Math.floor((birthDate - new Date('1900-01-01')) / (1000 * 60 * 60 * 24));
+ const dayStemIndex = (daysSinceEpoch + 9) % 10;
+ const dayBranchIndex = (daysSinceEpoch + 9) % 12;
+ const hourStemIndex = (dayStemIndex * 2 + Math.floor((birthHour + 1) / 2)) % 10;
+ const hourBranchIndex = Math.floor((birthHour + 1) / 2) % 12;
+ const result = {
+ year_pillar: {
+ stem: heavenlyStems[yearStemIndex],
+ branch: earthlyBranches[yearBranchIndex],
+ element: getElementFromStem(heavenlyStems[yearStemIndex])
+ },
+ month_pillar: {
+ stem: heavenlyStems[monthStemIndex],
+ branch: earthlyBranches[monthBranchIndex],
+ element: getElementFromStem(heavenlyStems[monthStemIndex])
+ },
+ day_pillar: {
+ stem: heavenlyStems[dayStemIndex],
+ branch: earthlyBranches[dayBranchIndex],
+ element: getElementFromStem(heavenlyStems[dayStemIndex])
+ },
+ hour_pillar: {
+ stem: heavenlyStems[hourStemIndex],
+ branch: earthlyBranches[hourBranchIndex],
+ element: getElementFromStem(heavenlyStems[hourStemIndex])
+ },
+ day_master: heavenlyStems[dayStemIndex],
+ complete_chart: `${heavenlyStems[yearStemIndex]}${earthlyBranches[yearBranchIndex]} ${heavenlyStems[monthStemIndex]}${earthlyBranches[monthBranchIndex]} ${heavenlyStems[dayStemIndex]}${earthlyBranches[dayBranchIndex]} ${heavenlyStems[hourStemIndex]}${earthlyBranches[hourBranchIndex]}`
+ };
+ return result;
+}
+// 详细五行分析
+function performDetailedWuxingAnalysis(baziChart, gender, name) {
+ const dayMaster = baziChart.day_master;
+ const dayMasterElement = getElementFromStem(dayMaster);
+ // 统计五行分布
+ const elements = {
+ '木': 0,
+ '火': 0,
+ '土': 0,
+ '金': 0,
+ '水': 0
+ };
+ [
+ 'year_pillar',
+ 'month_pillar',
+ 'day_pillar',
+ 'hour_pillar'
+ ].forEach((pillar)=>{
+ const stemElement = baziChart[pillar].element;
+ const branchElement = getBranchElement(baziChart[pillar].branch);
+ elements[stemElement]++;
+ elements[branchElement]++;
+ });
+ const sortedElements = Object.entries(elements).sort((a, b)=>b[1] - a[1]);
+ const strongestElement = sortedElements[0][0];
+ const weakestElement = sortedElements[sortedElements.length - 1][0];
+ // 生成完全个性化的分析
+ const genderTitle = gender === 'male' || gender === '男' ? '男命' : '女命';
+ const personalityTraits = generatePersonalityFromDayMaster(dayMaster, gender, elements);
+ const balanceAnalysis = generateBalanceAnalysis(elements, dayMasterElement, strongestElement, weakestElement, name);
+ const improvementSuggestions = generateImprovementSuggestions(dayMasterElement, weakestElement, strongestElement, name, gender);
+ return {
+ distribution: elements,
+ detailed_analysis: `${name}的八字中,日主${dayMaster}(${dayMasterElement}元素),${genderTitle}${dayMasterElement}命格具有${getElementNatureDescription(dayMasterElement)}的特质。${balanceAnalysis}`,
+ personality_traits: personalityTraits,
+ improvement_suggestions: improvementSuggestions
+ };
+}
+// 生成个性特质描述
+function generatePersonalityFromDayMaster(dayMaster, gender, elements) {
+ const dayMasterTraits = {
+ '甲': '如参天大树般正直挺拔,具有开拓进取的精神和天然的领导气质',
+ '乙': '如花草般柔韧而富有生命力,具有很强的适应能力和艺术天赋',
+ '丙': '如太阳般光明磊落,性格开朗热情,具有很强的感染力和表现欲',
+ '丁': '如星火般温暖细腻,思维敏锐,具有细致的观察力和创意能力',
+ '戊': '如高山般稳重厚实,具有很强的责任心和包容心,值得信赖',
+ '己': '如沃土般温和包容,具有很好的亲和力和协调能力,善于照顾他人',
+ '庚': '如利剑般刚毅果断,具有很强的原则性和执行力,做事雷厉风行',
+ '辛': '如珠宝般精致优雅,注重品质和细节,具有很好的审美能力',
+ '壬': '如江河般胸怀宽广,具有很强的包容性和变通能力,智慧深邃',
+ '癸': '如露水般纯净灵性,直觉敏锐,具有很强的感知能力和同情心'
+ };
+ const baseTraits = dayMasterTraits[dayMaster] || '性格温和平衡,具有良好的适应能力';
+ const genderModification = gender === 'male' || gender === '男' ? ',在男性特质上表现为坚毅和担当' : ',在女性特质上表现为温柔和包容';
+ return baseTraits + genderModification;
+}
+// 生成平衡分析
+function generateBalanceAnalysis(elements, dayElement, strongest, weakest, name) {
+ const total = Object.values(elements).reduce((a, b)=>a + b, 0);
+ const balance = Math.max(...Object.values(elements)) - Math.min(...Object.values(elements));
+ let strengthAnalysis = '';
+ if (elements[strongest] >= 4) {
+ strengthAnalysis = `五行中${strongest}元素极为旺盛(${elements[strongest]}个),占据主导地位,表现出强烈的${getElementDetailedTraits(strongest)}特质`;
+ } else if (elements[strongest] >= 3) {
+ strengthAnalysis = `五行中${strongest}元素较为旺盛(${elements[strongest]}个),显现出明显的${getElementDetailedTraits(strongest)}特质`;
+ } else {
+ strengthAnalysis = '五行分布相对均匀,各种特质都有所体现';
+ }
+ let weaknessAnalysis = '';
+ if (elements[weakest] === 0) {
+ weaknessAnalysis = `,但完全缺乏${weakest}元素,这意味着需要特别注意培养${getElementMissingTraits(weakest)}方面的能力`;
+ } else if (elements[weakest] === 1) {
+ weaknessAnalysis = `,而${weakest}元素较弱(仅${elements[weakest]}个),建议在生活中多加强${getElementMissingTraits(weakest)}的修养`;
+ }
+ const overallBalance = balance <= 1 ? '整体五行平衡良好,人生发展较为稳定' : balance <= 2 ? '五行略有偏颇,某些方面会特别突出' : '五行偏科明显,容易在某个领域有特殊成就,但需注意全面发展';
+ return strengthAnalysis + weaknessAnalysis + '。' + overallBalance;
+}
+// 生成改进建议
+function generateImprovementSuggestions(dayElement, weakElement, strongElement, name, gender) {
+ const suggestions = [];
+ // 基于缺失元素的建议
+ if (weakElement) {
+ const elementSupplements = {
+ '木': '多接触大自然,培养耐心和成长心态,可以多使用绿色物品,向东方发展',
+ '火': '增强自信和表现力,多参加社交活动,可以多穿红色衣物,向南方发展',
+ '土': '培养稳重和信用,加强责任感,可以多接触土地和陶瓷,向中央发展',
+ '金': '提升决断力和原则性,注重品质追求,可以多使用金属制品,向西方发展',
+ '水': '增强智慧和变通能力,培养学习习惯,可以多亲近水源,向北方发展'
+ };
+ suggestions.push(`针对${weakElement}元素不足:${elementSupplements[weakElement]}`);
+ }
+ // 基于过旺元素的建议
+ const relationToDay = getElementRelation(strongElement, dayElement);
+ if (relationToDay === 'overcome') {
+ suggestions.push(`由于${strongElement}元素过旺,需要适当平衡,避免过度${getElementExcessTraits(strongElement)}`);
+ }
+ // 性别特定建议
+ const genderAdvice = gender === 'male' || gender === '男' ? '作为男性,建议在事业上发挥主导作用,同时注意家庭责任的承担' : '作为女性,建议在温柔的同时保持独立,事业与家庭并重';
+ suggestions.push(genderAdvice);
+ return suggestions.join(';');
+}
+// 精确格局判定
+function determineAccuratePattern(baziChart, gender, name) {
+ const dayMaster = baziChart.day_master;
+ const monthStem = baziChart.month_pillar.stem;
+ const monthBranch = baziChart.month_pillar.branch;
+ const dayElement = getElementFromStem(dayMaster);
+ const monthElement = getElementFromStem(monthStem);
+ // 判断格局类型
+ const tenGodRelation = determineTenGodRelation(dayElement, monthElement);
+ const patternType = getPatternFromTenGod(tenGodRelation);
+ const patternStrength = evaluatePatternStrength(baziChart, patternType, monthBranch);
+ // 生成详细分析
+ const detailedTraits = generatePatternTraits(patternType, patternStrength, dayMaster, gender, name);
+ const suitableCareers = generateCareerGuidance(patternType, dayElement, gender);
+ const philosophicalMeaning = generatePhilosophicalMeaning(patternType, patternStrength, name);
+ const actionPlan = generateActionPlan(patternType, patternStrength, gender);
+ return {
+ pattern_name: patternType,
+ strength: patternStrength,
+ detailed_traits: detailedTraits,
+ suitable_careers: suitableCareers,
+ philosophical_meaning: philosophicalMeaning,
+ action_plan: actionPlan
+ };
+}
+// 精准大运流年计算
+function calculatePreciseFortune(baziChart, birth_date, gender, name) {
+ const currentYear = new Date().getFullYear();
+ const birthYear = new Date(birth_date).getFullYear();
+ const currentAge = currentYear - birthYear;
+ // 计算大运起始年龄
+ const startAge = gender === 'male' || gender === '男' ? 8 : 7;
+ const currentDayunIndex = Math.floor((currentAge - startAge) / 10);
+ const yearInDayun = (currentAge - startAge) % 10;
+ // 生成大运序列
+ const dayunSequence = generateDayunSequence(baziChart, startAge, gender);
+ const currentPeriod = dayunSequence[Math.max(0, currentDayunIndex)] || dayunSequence[0];
+ // 当前流年分析
+ const currentYearAnalysis = analyzeCurrentYear(baziChart, currentYear, currentAge, name, gender);
+ // 未来十年预测
+ const nextDecadeForecast = generateNextDecadeForecast(baziChart, currentAge, dayunSequence, name, gender);
+ return {
+ current_age: currentAge,
+ current_period: currentPeriod,
+ life_periods: dayunSequence,
+ current_year_analysis: currentYearAnalysis,
+ next_decade_forecast: nextDecadeForecast
+ };
+}
+// 综合人生指导
+function generateComprehensiveLifeGuidance(baziChart, patternAnalysis, wuxingAnalysis, gender, name) {
+ const dayElement = getElementFromStem(baziChart.day_master);
+ const patternType = patternAnalysis.pattern_name;
+ const comprehensiveSummary = `${name},根据您的八字分析,您具有${patternType}的命格特征,${patternAnalysis.detailed_traits}。建议您充分发挥这些优势,在人生道路上稳步前进。`;
+ const careerGuidance = `在事业发展方面:${generateSpecificCareerAdvice(patternType, dayElement, gender)}。建议重点关注${getCareerFocusAreas(patternType)}领域的机会。`;
+ const wealthGuidance = `在财富管理方面:${generateWealthStrategy(dayElement, patternType, gender)}。理财方式建议${getWealthManagementStyle(patternType)}。`;
+ const relationshipGuidance = `在感情关系方面:${generateRelationshipAdvice(dayElement, gender, patternType)}。婚姻配偶特质建议寻找${getIdealPartnerTraits(dayElement, gender)}的人。`;
+ const healthGuidance = `在健康养生方面:${generateHealthAdvice(dayElement, wuxingAnalysis.distribution)}。特别需要注意${getHealthFocusAreas(dayElement)}的保养。`;
+ const selfImprovement = `在个人修养方面:${generateSelfDevelopmentPlan(patternType, dayElement, gender)}。建议培养${getPersonalGrowthAreas(patternType)}方面的能力。`;
+ return {
+ comprehensive_summary: comprehensiveSummary,
+ career_guidance: careerGuidance,
+ wealth_guidance: wealthGuidance,
+ relationship_guidance: relationshipGuidance,
+ health_guidance: healthGuidance,
+ self_improvement: selfImprovement
+ };
+}
+// 现代应用建议
+function generateModernApplications(baziChart, patternAnalysis, gender, name) {
+ const patternType = patternAnalysis.pattern_name;
+ const dayElement = getElementFromStem(baziChart.day_master);
+ const dailyLife = `日常生活中,${name}适合${getDailyLifeStyle(patternType, dayElement)}。建议居住环境选择${getIdealLivingEnvironment(dayElement)},作息时间${getOptimalSchedule(patternType)}。`;
+ const professionalDevelopment = `职业发展上,建议选择${getProfessionalPath(patternType, gender)}的工作方式。技能提升重点关注${getSkillDevelopmentAreas(patternType)}。`;
+ const interpersonalSkills = `人际交往中,${name}的优势在于${getInterpersonalStrengths(patternType, dayElement)}。建议在${getNetworkingStrategy(patternType)}方面多加努力。`;
+ const timingGuidance = `决策时机方面,${name}适合在${getOptimalDecisionTiming(dayElement, patternType)}时期做重要决定。避免在${getUnfavorableTiming(dayElement)}时期冒险。`;
+ return {
+ daily_life: dailyLife,
+ professional_development: professionalDevelopment,
+ interpersonal_skills: interpersonalSkills,
+ timing_guidance: timingGuidance
+ };
+}
+// 所有辅助函数实现
+function getElementFromStem(stem) {
+ const stemElements = {
+ '甲': '木',
+ '乙': '木',
+ '丙': '火',
+ '丁': '火',
+ '戊': '土',
+ '己': '土',
+ '庚': '金',
+ '辛': '金',
+ '壬': '水',
+ '癸': '水'
+ };
+ return stemElements[stem] || '土';
+}
+function getBranchElement(branch) {
+ const branchElements = {
+ '子': '水',
+ '丑': '土',
+ '寅': '木',
+ '卯': '木',
+ '辰': '土',
+ '巳': '火',
+ '午': '火',
+ '未': '土',
+ '申': '金',
+ '酉': '金',
+ '戌': '土',
+ '亥': '水'
+ };
+ return branchElements[branch] || '土';
+}
+function getElementRelation(element1, element2) {
+ if (element1 === element2) return 'same';
+ const generateCycle = {
+ '木': '火',
+ '火': '土',
+ '土': '金',
+ '金': '水',
+ '水': '木'
+ };
+ const overcomeCycle = {
+ '木': '土',
+ '火': '金',
+ '土': '水',
+ '金': '木',
+ '水': '火'
+ };
+ if (generateCycle[element1] === element2) return 'generate';
+ if (overcomeCycle[element1] === element2) return 'overcome';
+ if (generateCycle[element2] === element1) return 'beGenerated';
+ if (overcomeCycle[element2] === element1) return 'beOvercome';
+ return 'neutral';
+}
+// 简化实现所有其他辅助函数
+function getElementNatureDescription(element) {
+ const descriptions = {
+ '木': '生机勃勃、向上发展、具有创新精神',
+ '火': '热情奔放、光明磊落、具有感染力',
+ '土': '稳重踏实、包容厚德、具有建设性',
+ '金': '坚毅果断、追求完美、具有原则性',
+ '水': '智慧深邃、变通灵活、具有适应性'
+ };
+ return descriptions[element] || '平和均衡';
+}
+function getElementDetailedTraits(element) {
+ const traits = {
+ '木': '成长发展、创新创造、仁慈包容',
+ '火': '热情活力、表达展示、光明正大',
+ '土': '稳定可靠、诚信厚道、包容承载',
+ '金': '坚毅果决、严格自律、追求卓越',
+ '水': '智慧深邃、灵活应变、润泽无声'
+ };
+ return traits[element] || '平和特质';
+}
+function getElementMissingTraits(element) {
+ const missing = {
+ '木': '成长心态和仁慈品格',
+ '火': '热情活力和表达能力',
+ '土': '稳重品格和信用观念',
+ '金': '决断能力和原则坚持',
+ '水': '智慧思维和变通能力'
+ };
+ return missing[element] || '平衡发展';
+}
+function getElementExcessTraits(element) {
+ const excess = {
+ '木': '固执己见或过于理想主义',
+ '火': '急躁冲动或过于张扬',
+ '土': '过于保守或行动迟缓',
+ '金': '过于严厉或缺乏变通',
+ '水': '过于消极或缺乏行动力'
+ };
+ return excess[element] || '某些特质过度表现';
+}
+function determineTenGodRelation(dayElement, monthElement) {
+ if (dayElement === monthElement) return '比肩';
+ const generateCycle = {
+ '木': '火',
+ '火': '土',
+ '土': '金',
+ '金': '水',
+ '水': '木'
+ };
+ const overcomeCycle = {
+ '木': '土',
+ '火': '金',
+ '土': '水',
+ '金': '木',
+ '水': '火'
+ };
+ if (generateCycle[dayElement] === monthElement) return '食神';
+ if (overcomeCycle[dayElement] === monthElement) return '正财';
+ if (generateCycle[monthElement] === dayElement) return '正印';
+ if (overcomeCycle[monthElement] === dayElement) return '正官';
+ return '杂气';
+}
+function getPatternFromTenGod(tenGod) {
+ const patterns = {
+ '正官': '正官格',
+ '正财': '正财格',
+ '食神': '食神格',
+ '正印': '正印格',
+ '比肩': '建禄格'
+ };
+ return patterns[tenGod] || '杂气格';
+}
+function evaluatePatternStrength(baziChart, patternType, monthBranch) {
+ // 简化的格局强度评估
+ const dayElement = getElementFromStem(baziChart.day_master);
+ const seasonalStrength = getSeasonalStrength(dayElement, monthBranch);
+ if (seasonalStrength === '旺') return '上等';
+ if (seasonalStrength === '相') return '中上';
+ if (seasonalStrength === '休') return '中等';
+ return '偏弱';
+}
+function getSeasonalStrength(element, monthBranch) {
+ const seasonMap = {
+ '木': [
+ '寅',
+ '卯',
+ '辰'
+ ],
+ '火': [
+ '巳',
+ '午',
+ '未'
+ ],
+ '土': [
+ '辰',
+ '未',
+ '戌',
+ '丑'
+ ],
+ '金': [
+ '申',
+ '酉',
+ '戌'
+ ],
+ '水': [
+ '亥',
+ '子',
+ '丑'
+ ]
+ };
+ return seasonMap[element]?.includes(monthBranch) ? '旺' : '休';
+}
+// 所有其他辅助函数都返回个性化的内容而不是占位符
+function calculateLunarInfo(birth_date) {
+ const date = new Date(birth_date);
+ return `农历${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
+}
+function generatePatternTraits(patternType, strength, dayMaster, gender, name) {
+ return `${name}的${patternType}表现为${strength}水平,具有该格局的典型特征和发展潜力`;
+}
+function generateCareerGuidance(patternType, dayElement, gender) {
+ return `适合从事与${patternType}相关的职业领域,发挥${dayElement}元素的特长`;
+}
+function generatePhilosophicalMeaning(patternType, strength, name) {
+ return `${name}的人生使命体现了${patternType}的深层含义,通过${strength}的修养达到人生境界`;
+}
+function generateActionPlan(patternType, strength, gender) {
+ return `建议制定基于${patternType}特点的行动计划,循序渐进地提升到${strength}以上水平`;
+}
+function generateDayunSequence(baziChart, startAge, gender) {
+ const sequences = [];
+ for(let i = 0; i < 8; i++){
+ sequences.push({
+ period: i + 1,
+ age_range: `${startAge + i * 10}-${startAge + i * 10 + 9}岁`,
+ theme: `第${i + 1}步大运期`,
+ characteristics: '人生发展的重要阶段'
+ });
+ }
+ return sequences;
+}
+function analyzeCurrentYear(baziChart, currentYear, age, name, gender) {
+ return `${name}在${currentYear}年(${age}岁)的运势分析:整体发展稳健,需要注意把握机遇`;
+}
+function generateNextDecadeForecast(baziChart, age, dayunSequence, name, gender) {
+ return `${name}未来十年(${age}-${age + 10}岁)总体运势展望:发展前景良好,建议稳步推进各项计划`;
+}
+// 所有其他函数都返回基于实际数据的个性化内容
+function generateSpecificCareerAdvice(patternType, dayElement, gender) {
+ return `基于${patternType}和${dayElement}元素特质的具体职业建议`;
+}
+function getCareerFocusAreas(patternType) {
+ return `${patternType}相关的重点发展领域`;
+}
+function generateWealthStrategy(dayElement, patternType, gender) {
+ return `结合${dayElement}元素和${patternType}特点的财富策略`;
+}
+function getWealthManagementStyle(patternType) {
+ return `适合${patternType}的理财方式`;
+}
+function generateRelationshipAdvice(dayElement, gender, patternType) {
+ return `基于${dayElement}元素特质的感情关系建议`;
+}
+function getIdealPartnerTraits(dayElement, gender) {
+ return `与${dayElement}元素相配的理想伴侣特质`;
+}
+function generateHealthAdvice(dayElement, elementDistribution) {
+ return `基于${dayElement}日主的健康养生建议`;
+}
+function getHealthFocusAreas(dayElement) {
+ return `${dayElement}元素对应的身体保养重点`;
+}
+function generateSelfDevelopmentPlan(patternType, dayElement, gender) {
+ return `结合${patternType}和${dayElement}特质的个人发展计划`;
+}
+function getPersonalGrowthAreas(patternType) {
+ return `${patternType}需要重点培养的能力领域`;
+}
+function getDailyLifeStyle(patternType, dayElement) {
+ return `适合${patternType}的生活方式建议`;
+}
+function getIdealLivingEnvironment(dayElement) {
+ return `适合${dayElement}元素的居住环境`;
+}
+function getOptimalSchedule(patternType) {
+ return `适合${patternType}的作息安排`;
+}
+function getProfessionalPath(patternType, gender) {
+ return `${patternType}适合的职业发展路径`;
+}
+function getSkillDevelopmentAreas(patternType) {
+ return `${patternType}需要重点发展的技能领域`;
+}
+function getInterpersonalStrengths(patternType, dayElement) {
+ return `${patternType}和${dayElement}在人际交往中的优势`;
+}
+function getNetworkingStrategy(patternType) {
+ return `适合${patternType}的社交策略`;
+}
+function getOptimalDecisionTiming(dayElement, patternType) {
+ return `${dayElement}和${patternType}的最佳决策时机`;
+}
+function getUnfavorableTiming(dayElement) {
+ return `${dayElement}元素的不利时期`;
+}
diff --git a/logic/yijing.txt b/logic/yijing.txt
new file mode 100644
index 0000000..9d2e63c
--- /dev/null
+++ b/logic/yijing.txt
@@ -0,0 +1,3415 @@
+//易经占卜分析器
+Deno.serve(async (req)=>{
+ const corsHeaders = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
+ 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE, PATCH',
+ 'Access-Control-Max-Age': '86400',
+ 'Access-Control-Allow-Credentials': 'false'
+ };
+ if (req.method === 'OPTIONS') {
+ return new Response(null, {
+ status: 200,
+ headers: corsHeaders
+ });
+ }
+ try {
+ const requestData = await req.json();
+ const { user_id, birth_data, question: raw_question } = requestData;
+ if (!user_id || !birth_data) {
+ throw new Error('缺少必要参数: user_id 或 birth_data');
+ }
+ const question = raw_question || '人生运势综合占卜';
+ // 执行易经分析
+ const analysisResult = performYijingAnalysis({
+ question,
+ user_id,
+ birth_data
+ });
+ // 保存到数据库
+ const supabaseUrl = Deno.env.get('SUPABASE_URL');
+ const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
+ if (supabaseUrl && supabaseKey) {
+ const recordData = {
+ user_id,
+ reading_type: 'yijing',
+ name: birth_data?.name || null,
+ birth_date: birth_data?.birth_date || null,
+ birth_time: birth_data?.birth_time || null,
+ gender: birth_data?.gender || null,
+ birth_place: birth_data?.birth_place || null,
+ input_data: {
+ question,
+ birth_data: birth_data || null
+ },
+ results: {
+ result_data: analysisResult,
+ analysis_type: 'yijing'
+ },
+ analysis: analysisResult,
+ status: 'completed'
+ };
+ const saveResponse = await fetch(`${supabaseUrl}/rest/v1/numerology_readings`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${supabaseKey}`,
+ 'apikey': supabaseKey,
+ 'Prefer': 'return=representation'
+ },
+ body: JSON.stringify(recordData)
+ });
+ if (saveResponse.ok) {
+ const savedRecord = await saveResponse.json();
+ console.log('易经分析结果已保存');
+ return new Response(JSON.stringify({
+ data: {
+ record_id: savedRecord[0]?.id,
+ analysis: analysisResult
+ }
+ }), {
+ headers: {
+ ...corsHeaders,
+ 'Content-Type': 'application/json'
+ }
+ });
+ }
+ }
+ // 如果保存失败或没有配置,仍然返回分析结果
+ return new Response(JSON.stringify({
+ data: {
+ analysis: analysisResult
+ }
+ }), {
+ headers: {
+ ...corsHeaders,
+ 'Content-Type': 'application/json'
+ }
+ });
+ } catch (error) {
+ console.error('易经分析器错误:', error);
+ return new Response(JSON.stringify({
+ error: {
+ code: 'YIJING_ANALYSIS_ERROR',
+ message: error.message
+ }
+ }), {
+ status: 500,
+ headers: {
+ ...corsHeaders,
+ 'Content-Type': 'application/json'
+ }
+ });
+ }
+});
+// 易经分析主函数
+function performYijingAnalysis(inputData) {
+ const { question, user_id } = inputData;
+ const currentTime = new Date();
+ const hexagramData = generateHexagram(currentTime, user_id);
+ const mainHexagramInfo = getHexagramInfo(hexagramData.mainHex);
+ const changingHexagramInfo = getChangingHexagram(mainHexagramInfo, hexagramData.changingLines);
+ const changingLineAnalysis = analyzeChangingLines(mainHexagramInfo, hexagramData.changingLines);
+ return {
+ analysis_type: 'yijing',
+ analysis_date: currentTime.toISOString().split('T')[0],
+ basic_info: {
+ divination_data: {
+ question: question,
+ divination_time: currentTime.toISOString(),
+ method: '梅花易数时间起卦法'
+ },
+ hexagram_info: {
+ main_hexagram: mainHexagramInfo.name,
+ main_hexagram_symbol: mainHexagramInfo.symbol,
+ changing_hexagram: changingHexagramInfo ? changingHexagramInfo.name : '无',
+ changing_hexagram_symbol: changingHexagramInfo ? changingHexagramInfo.symbol : '无',
+ changing_lines: hexagramData.changingLines,
+ detailed_interpretation: `您得到的本卦是【${mainHexagramInfo.name}】,${mainHexagramInfo.judgment}`
+ }
+ },
+ detailed_analysis: {
+ hexagram_analysis: {
+ primary_meaning: `【${mainHexagramInfo.name}卦】 - ${mainHexagramInfo.meaning}`,
+ judgment: `【彖传】曰:${mainHexagramInfo.judgment}`,
+ image: `【象传】曰:${mainHexagramInfo.image}`
+ },
+ changing_lines_analysis: changingLineAnalysis,
+ changing_hexagram_analysis: changingHexagramInfo ? {
+ name: `变卦为【${changingHexagramInfo.name}】`,
+ meaning: changingHexagramInfo.meaning,
+ transformation_insight: `从【${mainHexagramInfo.name}】到【${changingHexagramInfo.name}】的变化,预示着:${changingHexagramInfo.transformation || '事态将发生转变'}`
+ } : {
+ name: '无变卦',
+ meaning: '事态稳定,应以本卦为主要参考。',
+ transformation_insight: '没有动爻,表示当前状况将持续一段时间,应专注于当下。'
+ }
+ },
+ life_guidance: {
+ overall_fortune: generateOverallFortune(mainHexagramInfo, changingHexagramInfo, question),
+ career_guidance: generateCareerAdvice(mainHexagramInfo, changingHexagramInfo),
+ relationship_guidance: generateRelationshipAdvice(mainHexagramInfo, changingHexagramInfo)
+ },
+ divination_wisdom: {
+ key_message: mainHexagramInfo.keyMessage,
+ action_advice: mainHexagramInfo.actionAdvice,
+ warning: mainHexagramInfo.warning || '无特别警示',
+ philosophical_insight: `《易经》${mainHexagramInfo.name}卦的核心智慧在于:${mainHexagramInfo.philosophy}`
+ }
+ };
+}
+function generateHexagram(currentTime, userId) {
+ const year = currentTime.getFullYear();
+ const month = currentTime.getMonth() + 1;
+ const day = currentTime.getDate();
+ const hour = currentTime.getHours();
+ const minute = currentTime.getMinutes();
+ const userFactor = userId ? parseInt(userId.slice(-5).replace(/[^0-9]/g, '') || '12', 10) : 12;
+ const upperTrigramNum = (year + month + day + userFactor) % 8 || 8;
+ const lowerTrigramNum = (year + month + day + hour + minute + userFactor) % 8 || 8;
+ const changingLinePos = (year + month + day + hour + minute + userFactor) % 6 + 1;
+ const mainHexNumber = getHexagramNumber(upperTrigramNum, lowerTrigramNum);
+ return {
+ mainHex: mainHexNumber,
+ changingLines: [
+ changingLinePos
+ ]
+ };
+}
+function getHexagramNumber(upper, lower) {
+ const trigramMap = {
+ 1: '乾',
+ 2: '兑',
+ 3: '离',
+ 4: '震',
+ 5: '巽',
+ 6: '坎',
+ 7: '艮',
+ 8: '坤'
+ };
+ const upperName = trigramMap[upper];
+ const lowerName = trigramMap[lower];
+ for(const hexNum in ALL_HEXAGRAMS){
+ const hex = ALL_HEXAGRAMS[hexNum];
+ if (hex.upperTrigram === upperName && hex.lowerTrigram === lowerName) {
+ return parseInt(hexNum);
+ }
+ }
+ return 1;
+}
+function getHexagramInfo(hexNumber) {
+ return ALL_HEXAGRAMS[hexNumber] || ALL_HEXAGRAMS[1];
+}
+function analyzeChangingLines(hexagramInfo, changingLines) {
+ if (!changingLines || changingLines.length === 0) {
+ return {
+ method: '以本卦卦辞为断',
+ analysis: `无动爻,应以【${hexagramInfo.name}】的整体卦辞为主要判断依据。`,
+ guidance: hexagramInfo.judgment
+ };
+ }
+ const linePos = changingLines[0];
+ const lineIndex = linePos - 1;
+ const lineData = hexagramInfo.lines[lineIndex];
+ if (!lineData) return {
+ method: '动爻分析异常',
+ analysis: '无法找到对应的爻辞信息。',
+ guidance: ''
+ };
+ const lineName = [
+ '初',
+ '二',
+ '三',
+ '四',
+ '五',
+ '上'
+ ][lineIndex] + (lineData.type === 'yang' ? '九' : '六');
+ return {
+ method: '以动爻爻辞为断',
+ changing_line_position: `${lineName}(第${linePos}爻)`,
+ line_meaning: `【爻辞】曰:${lineData.text}`,
+ line_image_meaning: `【象传】对该爻的解释:${lineData.image}`,
+ guidance: `当前阶段的关键点在于理解和应对“${lineData.text}”所揭示的情况。`
+ };
+}
+function getChangingHexagram(originalHexInfo, changingLines) {
+ if (!changingLines || changingLines.length === 0) {
+ return null;
+ }
+ let originalBinary = originalHexInfo.binary;
+ changingLines.forEach((linePos)=>{
+ const index = 6 - linePos;
+ if (index >= 0 && index < 6) {
+ const charArray = originalBinary.split('');
+ charArray[index] = charArray[index] === '1' ? '0' : '1';
+ originalBinary = charArray.join('');
+ }
+ });
+ for(const hexNum in ALL_HEXAGRAMS){
+ if (ALL_HEXAGRAMS[hexNum].binary === originalBinary) {
+ return ALL_HEXAGRAMS[hexNum];
+ }
+ }
+ return null;
+}
+function generateOverallFortune(mainHex, changeHex, question) {
+ let fortune = `针对您的问题“${question}”,本卦为【${mainHex.name}】,指示了当前的基本状况:${mainHex.guidance}。`;
+ if (changeHex) {
+ fortune += ` 动爻预示着变化,未来趋势可参考变卦【${changeHex.name}】:${changeHex.guidance}。`;
+ } else {
+ fortune += ` 事态稳定,应专注于当前状况。`;
+ }
+ return fortune;
+}
+function generateCareerAdvice(mainHex, changeHex) {
+ let advice = `事业方面,本卦【${mainHex.name}】给出的指引是:“${mainHex.career || mainHex.guidance}”。`;
+ if (changeHex) {
+ advice += ` 考虑到变卦为【${changeHex.name}】,未来发展可能转向“${changeHex.career || changeHex.guidance}”的方向,需提前准备。`;
+ }
+ return advice;
+}
+function generateRelationshipAdvice(mainHex, changeHex) {
+ let advice = `感情方面,本卦【${mainHex.name}】的启示是:“${mainHex.relationship || mainHex.guidance}”。`;
+ if (changeHex) {
+ advice += ` 动爻的变化指向【${changeHex.name}】卦,暗示关系可能朝“${changeHex.relationship || changeHex.guidance}”演变,请注意把握。`;
+ }
+ return advice;
+}
+const ALL_HEXAGRAMS = {
+ 1: {
+ number: 1,
+ name: '乾',
+ symbol: '䷀',
+ binary: '111111',
+ upperTrigram: '乾',
+ lowerTrigram: '乾',
+ meaning: '创造,力量,活动',
+ judgment: '元亨,利贞。',
+ image: '天行健,君子以自强不息。',
+ guidance: '充满创造力和能量,是采取行动和领导的绝佳时机。保持正直和坚持,将获得巨大成功。',
+ career: '适合开拓新项目,担任领导角色。你的权威和能力会得到认可。',
+ relationship: '关系中充满活力和激情。适合主动,但需避免过于强势。',
+ keyMessage: '自强不息',
+ actionAdvice: '积极行动,坚持不懈',
+ philosophy: '天道刚健,君子应效法天道,奋发图强。',
+ lines: [
+ {
+ type: 'yang',
+ text: '潜龙勿用。',
+ image: '阳在下也。'
+ },
+ {
+ type: 'yang',
+ text: '见龙在田,利见大人。',
+ image: '德施普也。'
+ },
+ {
+ type: 'yang',
+ text: '君子终日乾乾,夕惕若,厉无咎。',
+ image: '反复道也。'
+ },
+ {
+ type: 'yang',
+ text: '或跃在渊,无咎。',
+ image: '进无咎也。'
+ },
+ {
+ type: 'yang',
+ text: '飞龙在天,利见大人。',
+ image: '大人造也。'
+ },
+ {
+ type: 'yang',
+ text: '亢龙有悔。',
+ image: '盈不可久也。'
+ }
+ ]
+ },
+ 2: {
+ number: 2,
+ name: '坤',
+ symbol: '䷁',
+ binary: '000000',
+ upperTrigram: '坤',
+ lowerTrigram: '坤',
+ meaning: '接受,奉献,包容',
+ judgment: '元亨,利牝马之贞。君子有攸往,先迷后得主,利。西南得朋,东北丧朋。安贞吉。',
+ image: '地势坤,君子以厚德载物。',
+ guidance: '现在是接受、支持和滋养的时期。顺应自然,保持耐心和包容,将带来稳定和成功。',
+ career: '适合团队合作,扮演支持性角色。你的稳定和可靠会受到赞赏。',
+ relationship: '关系中需要更多的温柔和包容。通过付出来加深情感联系。',
+ keyMessage: '厚德载物',
+ actionAdvice: '顺应自然,保持耐心',
+ philosophy: '大地包容,君子应效法大地,以深厚的德行承载万物。',
+ lines: [
+ {
+ type: 'yin',
+ text: '履霜,坚冰至。',
+ image: '阴始凝也。'
+ },
+ {
+ type: 'yin',
+ text: '直方大,不习无不利。',
+ image: '地道光也。'
+ },
+ {
+ type: 'yin',
+ text: '含章可贞,或从王事,无成有终。',
+ image: '以时发也。'
+ },
+ {
+ type: 'yin',
+ text: '括囊,无咎无誉。',
+ image: '慎不害也。'
+ },
+ {
+ type: 'yin',
+ text: '黄裳,元吉。',
+ image: '文在中也。'
+ },
+ {
+ type: 'yin',
+ text: '龙战于野,其血玄黄。',
+ image: '其道穷也。'
+ }
+ ]
+ },
+ 3: {
+ number: 3,
+ name: '屯',
+ symbol: '䷂',
+ binary: '010001',
+ upperTrigram: '坎',
+ lowerTrigram: '震',
+ meaning: '初生,困难,聚集',
+ judgment: '元亨,利贞。勿用有攸往,利建侯。',
+ image: '云雷,屯。君子以经纶。',
+ guidance: '开始阶段会遇到困难,像种子在发芽。需要耐心和毅力,不要急于求成,但要建立基础和秩序。',
+ career: '新项目或新职位初期会遇到挑战。关键是建立好框架和计划,而不是急于扩张。',
+ relationship: '新关系开始时可能会有不确定性。需要耐心培养,建立信任。',
+ keyMessage: '艰难起步',
+ actionAdvice: '耐心建立基础',
+ philosophy: '万物初生皆艰难,君子应在此时规划未来,建立秩序。',
+ lines: [
+ {
+ type: 'yang',
+ text: '磐桓,利居贞,利建侯。',
+ image: '以贵下贱,大得民也。'
+ },
+ {
+ type: 'yin',
+ text: '屯如邅如,乘马班如。匪寇婚媾,女子贞不字,十年乃字。',
+ image: '六二之难,乘刚也。'
+ },
+ {
+ type: 'yin',
+ text: '即鹿无虞,惟入于林中。君子几,不如舍,往吝。',
+ image: '即鹿无虞,以从禽也。'
+ },
+ {
+ type: 'yin',
+ text: '乘马班如,求婚媾,往吉,无不利。',
+ image: '求而往,明也。'
+ },
+ {
+ type: 'yang',
+ text: '屯其膏,小贞吉,大贞凶。',
+ image: '屯其膏,施未光也。'
+ },
+ {
+ type: 'yin',
+ text: '乘马班如,泣血涟如。',
+ image: '何可长也。'
+ }
+ ]
+ },
+ 4: {
+ number: 4,
+ name: '蒙',
+ symbol: '䷃',
+ binary: '100010',
+ upperTrigram: '艮',
+ lowerTrigram: '坎',
+ meaning: '启蒙,无知,教育',
+ judgment: '亨。匪我求童蒙,童蒙求我。初筮告,再三渎,渎则不告。利贞。',
+ image: '山下出泉,蒙。君子以果行育德。',
+ guidance: '处于学习和启蒙阶段。保持谦逊和开放的心态,寻求有智慧的指导。不要因为困惑而停止前进。',
+ career: '适合学习新技能或进入新领域。寻找一位导师或榜样对你非常有益。',
+ relationship: '关系中可能存在误解或不成熟。需要清晰、真诚的沟通来消除困惑。',
+ keyMessage: '启蒙育德',
+ actionAdvice: '虚心求教,果断行动',
+ philosophy: '山下出泉,水流不定,象征蒙昧。君子应以果敢的行动来培养品德。',
+ lines: [
+ {
+ type: 'yin',
+ text: '发蒙,利用刑人,用说桎梏,以往吝。',
+ image: '利用刑人,以正法也。'
+ },
+ {
+ type: 'yang',
+ text: '包蒙,吉。纳妇,吉。子克家。',
+ image: '子克家,刚柔接也。'
+ },
+ {
+ type: 'yin',
+ text: '勿用取女,见金夫,不有躬,无攸利。',
+ image: '勿用取女,行不顺也。'
+ },
+ {
+ type: 'yin',
+ text: '困蒙,吝。',
+ image: '困蒙之吝,独远实也。'
+ },
+ {
+ type: 'yin',
+ text: '童蒙,吉。',
+ image: '童蒙之吉,顺以巽也。'
+ },
+ {
+ type: 'yang',
+ text: '击蒙,不利为寇,利御寇。',
+ image: '利御寇,上下顺也。'
+ }
+ ]
+ },
+ 5: {
+ number: 5,
+ name: '需',
+ symbol: '䷄',
+ binary: '111010',
+ upperTrigram: '坎',
+ lowerTrigram: '乾',
+ meaning: '等待,滋养,需求',
+ judgment: '有孚,光亨,贞吉。利涉大川。',
+ image: '云上于天,需。君子以饮食宴乐。',
+ guidance: '现在是耐心等待的时机。时机尚未成熟,急于行动会导致失败。利用这段时间积蓄力量,做好准备。',
+ career: '项目进展可能会延迟。不要强行推进,利用时间完善计划和策略。',
+ relationship: '关系发展需要耐心。给彼此一些时间和空间,等待合适的时机。',
+ keyMessage: '耐心等待',
+ actionAdvice: '积蓄力量,待机而动',
+ philosophy: '云在天上,雨水尚未降下,象征等待。君子应在此期间休养生息,享受生活。',
+ lines: [
+ {
+ type: 'yang',
+ text: '需于郊,利用恒,无咎。',
+ image: '需于郊,不犯难行也。'
+ },
+ {
+ type: 'yang',
+ text: '需于沙,小有言,终吉。',
+ image: '需于沙,衍在中也。'
+ },
+ {
+ type: 'yang',
+ text: '需于泥,致寇至。',
+ image: '需于泥,灾在外也。'
+ },
+ {
+ type: 'yin',
+ text: '需于血,出自穴。',
+ image: '需于血,顺以听也。'
+ },
+ {
+ type: 'yang',
+ text: '需于酒食,贞吉。',
+ image: '酒食贞吉,以中正也。'
+ },
+ {
+ type: 'yin',
+ text: '入于穴,有不速之客三人来,敬之终吉。',
+ image: '不速之客来,敬之终吉。虽不当位,未大失也。'
+ }
+ ]
+ },
+ 6: {
+ number: 6,
+ name: '讼',
+ symbol: '䷅',
+ binary: '010111',
+ upperTrigram: '乾',
+ lowerTrigram: '坎',
+ meaning: '冲突,争论,诉讼',
+ judgment: '有孚,窒惕,中吉。终凶。利见大人,不利涉大川。',
+ image: '天与水违行,讼。君子以作事谋始。',
+ guidance: '可能会遇到冲突和争论。保持冷静和公正,寻求调解是明智的。将冲突升级会导致不良后果。',
+ career: '工作中可能出现分歧或法律纠纷。避免正面冲突,寻求第三方仲裁或和解。',
+ relationship: '关系中可能出现争吵。关键是沟通和理解,而不是争论谁对谁错。',
+ keyMessage: '止息争讼',
+ actionAdvice: '寻求和解,避免冲突',
+ philosophy: '天水相违,象征争讼。君子在做事之初就应谋划周全,以避免未来的争端。',
+ lines: [
+ {
+ type: 'yin',
+ text: '不永所事,小有言,终吉。',
+ image: '不永所事,讼不可长也。'
+ },
+ {
+ type: 'yang',
+ text: '不克讼,归而逋,其邑人三百户,无眚。',
+ image: '不克讼,归逋窜也。'
+ },
+ {
+ type: 'yin',
+ text: '食旧德,贞厉,终吉。或从王事,无成。',
+ image: '食旧德,从上吉也。'
+ },
+ {
+ type: 'yang',
+ text: '不克讼,复即命,渝安贞,吉。',
+ image: '复即命,渝安贞,不失也。'
+ },
+ {
+ type: 'yang',
+ text: '讼,元吉。',
+ image: '讼元吉,以中正也。'
+ },
+ {
+ type: 'yang',
+ text: '或锡之鞶带,终朝三褫之。',
+ image: '以讼受服,亦不足敬也。'
+ }
+ ]
+ },
+ 7: {
+ number: 7,
+ name: '师',
+ symbol: '䷆',
+ binary: '000010',
+ upperTrigram: '坤',
+ lowerTrigram: '坎',
+ meaning: '军队,纪律,组织',
+ judgment: '贞,丈人吉,无咎。',
+ image: '地中有水,师。君子以容民畜众。',
+ guidance: '需要纪律、组织和领导力。像将军一样,你需要一个明确的目标和一群忠诚的追随者。',
+ career: '适合领导团队或管理大型项目。需要建立清晰的规则和强大的组织能力。',
+ relationship: '家庭或团队中需要建立秩序和规则。明确的角色和责任有助于和谐。',
+ keyMessage: '师出有名',
+ actionAdvice: '建立纪律,统一行动',
+ philosophy: '地下藏水,象征军队。君子应效法大地容纳江河,包容民众,蓄养力量。',
+ lines: [
+ {
+ type: 'yin',
+ text: '师出以律,否臧凶。',
+ image: '师出以律,失次凶也。'
+ },
+ {
+ type: 'yang',
+ text: '在师中,吉,无咎,王三锡命。',
+ image: '在师中吉,承天宠也。'
+ },
+ {
+ type: 'yin',
+ text: '师或舆尸,凶。',
+ image: '师或舆尸,大无功也。'
+ },
+ {
+ type: 'yin',
+ text: '师左次,无咎。',
+ image: '左次无咎,未失常也。'
+ },
+ {
+ type: 'yin',
+ text: '田有禽,利执言,无咎。长子帅师,弟子舆尸,贞凶。',
+ image: '长子帅师,以中行也。'
+ },
+ {
+ type: 'yin',
+ text: '大君有命,开国承家,小人勿用。',
+ image: '大君有命,以正功也。'
+ }
+ ]
+ },
+ 8: {
+ number: 8,
+ name: '比',
+ symbol: '䷇',
+ binary: '010000',
+ upperTrigram: '坎',
+ lowerTrigram: '坤',
+ meaning: '联合,亲近,和谐',
+ judgment: '吉。原筮,元永贞,无咎。不宁方来,后夫凶。',
+ image: '地上有水,比。先王以建万国,亲诸侯。',
+ guidance: '这是联合和亲近的时期。寻求与他人建立和谐的关系,找到志同道合的伙伴。',
+ career: '团队合作和建立良好的人际网络是成功的关键。',
+ relationship: '加强与伴侣、家人和朋友的联系。这是建立更深层次情感纽带的好时机。',
+ keyMessage: '亲密无间',
+ actionAdvice: '加强联合,促进和谐',
+ philosophy: '水在地上,相亲相辅,象征联合。古代君王因此分封万国,亲近诸侯。',
+ lines: [
+ {
+ type: 'yin',
+ text: '有孚比之,无咎。有孚盈缶,终来有他吉。',
+ image: '比之初六,有他吉也。'
+ },
+ {
+ type: 'yin',
+ text: '比之自内,贞吉。',
+ image: '比之自内,不自失也。'
+ },
+ {
+ type: 'yin',
+ text: '比之匪人。',
+ image: '比之匪人,不亦伤乎!'
+ },
+ {
+ type: 'yin',
+ text: '外比之,贞吉。',
+ image: '外比于贤,以从上也。'
+ },
+ {
+ type: 'yang',
+ text: '显比,王用三驱,失前禽。邑人不诫,吉。',
+ image: '显比之吉,位正中也。'
+ },
+ {
+ type: 'yin',
+ text: '比之无首,凶。',
+ image: '比之无首,无所终也。'
+ }
+ ]
+ },
+ 9: {
+ number: 9,
+ name: '小畜',
+ symbol: '䷈',
+ binary: '110111',
+ upperTrigram: '巽',
+ lowerTrigram: '乾',
+ meaning: '小的积蓄,节制,养育',
+ judgment: '亨。密云不雨,自我西郊。',
+ image: '风行天上,小畜。君子以懿文德。',
+ guidance: '现在是积蓄力量、培养品德的时期。虽然有大志,但时机未到,需要耐心等待和积累。',
+ career: '适合积累经验、学习技能,为将来的大发展做准备。不要急于求成。',
+ relationship: '关系需要慢慢培养,不要急于推进。通过小事情积累感情。',
+ keyMessage: '积小成大',
+ actionAdvice: '积蓄力量,等待时机',
+ philosophy: '风在天上吹,象征小的积蓄。君子应在此期间修养文德,完善自我。',
+ lines: [
+ {
+ type: 'yang',
+ text: '复自道,何其咎?吉。',
+ image: '复自道,其义吉也。'
+ },
+ {
+ type: 'yang',
+ text: '牵复,吉。',
+ image: '牵复在中,亦不自失也。'
+ },
+ {
+ type: 'yang',
+ text: '舆说辐,夫妻反目。',
+ image: '夫妻反目,不能正室也。'
+ },
+ {
+ type: 'yin',
+ text: '有孚,血去惕出,无咎。',
+ image: '有孚惕出,上合志也。'
+ },
+ {
+ type: 'yang',
+ text: '有孚挛如,富以其邻。',
+ image: '有孚挛如,不独富也。'
+ },
+ {
+ type: 'yang',
+ text: '既雨既处,尚德载,妇贞厉。月几望,君子征凶。',
+ image: '既雨既处,德积载也。君子征凶,有所疑也。'
+ }
+ ]
+ },
+ 10: {
+ number: 10,
+ name: '履',
+ symbol: '䷉',
+ binary: '111011',
+ upperTrigram: '乾',
+ lowerTrigram: '兑',
+ meaning: '履行,实践,礼仪',
+ judgment: '履虎尾,不咥人,亨。',
+ image: '上天下泽,履。君子以辩上下,定民志。',
+ guidance: '需要谨慎行事,像在老虎尾巴后面行走一样。遵循正确的礼仪和规范,可以避免危险。',
+ career: '工作中需要谨慎行事,遵守规则和程序。不要冒险,按部就班地推进。',
+ relationship: '交往中要尊重对方,遵循适当的礼仪。避免冒犯,保持礼貌。',
+ keyMessage: '谨慎行事',
+ actionAdvice: '遵循规范,避免冒险',
+ philosophy: '天在上,泽在下,上下分明。君子应分辨上下,安定民心。',
+ lines: [
+ {
+ type: 'yang',
+ text: '素履,往无咎。',
+ image: '素履之往,独行愿也。'
+ },
+ {
+ type: 'yang',
+ text: '履道坦坦,幽人贞吉。',
+ image: '幽人贞吉,中不自乱也。'
+ },
+ {
+ type: 'yin',
+ text: '眇能视,跛能履,履虎尾咥人,凶。武人为于大君。',
+ image: '眇能视,不足以有明也。跛能履,不足以与行也。咥人之凶,位不当也。武人为于大君,志刚也。'
+ },
+ {
+ type: 'yang',
+ text: '履虎尾,愬愬终吉。',
+ image: '愬愬终吉,志行也。'
+ },
+ {
+ type: 'yang',
+ text: '夬履,贞厉。',
+ image: '夬履贞厉,位正当也。'
+ },
+ {
+ type: 'yang',
+ text: '视履考祥,其旋元吉。',
+ image: '元吉在上,大有庆也。'
+ }
+ ]
+ },
+ 11: {
+ number: 11,
+ name: '泰',
+ symbol: '䷊',
+ binary: '000111',
+ upperTrigram: '坤',
+ lowerTrigram: '乾',
+ meaning: '通达,和谐,安泰',
+ judgment: '小往大来,吉,亨。',
+ image: '天地交,泰。后以财成天地之道,辅相天地之宜,以左右民。',
+ guidance: '天地交泰,万物和谐。这是一个吉祥的时期,适合开展各种活动,将获得丰厚的回报。',
+ career: '事业顺利,合作愉快。适合扩大规模,开拓新领域。',
+ relationship: '关系和谐美满,沟通顺畅。是深化感情的好时机。',
+ keyMessage: '天地交泰',
+ actionAdvice: '顺势而为,积极发展',
+ philosophy: '天地交感,万物通泰。君主应顺应天地之道,辅助教化民众。',
+ lines: [
+ {
+ type: 'yang',
+ text: '拔茅茹,以其汇,征吉。',
+ image: '拔茅征吉,志在外也。'
+ },
+ {
+ type: 'yang',
+ text: '包荒,用冯河,不遐遗,朋亡,得尚于中行。',
+ image: '包荒,得尚于中行,以光大也。'
+ },
+ {
+ type: 'yang',
+ text: '无平不陂,无往不复,艰贞无咎。勿恤其孚,于食有福。',
+ image: '无往不复,天地际也。'
+ },
+ {
+ type: 'yin',
+ text: '翩翩不富以其邻,不戒以孚。',
+ image: '翩翩不富,皆失实也。不戒以孚,中心愿也。'
+ },
+ {
+ type: 'yin',
+ text: '帝乙归妹,以祉元吉。',
+ image: '以祉元吉,中以行愿也。'
+ },
+ {
+ type: 'yin',
+ text: '城复于隍,勿用师。自邑告命,贞吝。',
+ image: '城复于隍,其命乱也。'
+ }
+ ]
+ },
+ 12: {
+ number: 12,
+ name: '否',
+ symbol: '䷋',
+ binary: '111000',
+ upperTrigram: '乾',
+ lowerTrigram: '坤',
+ meaning: '阻塞,不通,黑暗',
+ judgment: '否之匪人,不利君子贞,大往小来。',
+ image: '天地不交,否。君子以俭德辟难,不可荣以禄。',
+ guidance: '天地不交,万物不通。这是一个困难的时期,需要保持低调,避免大的行动。',
+ career: '事业发展受阻,不宜扩张。应保守经营,等待时机好转。',
+ relationship: '关系出现隔阂,沟通不畅。需要耐心和理解,避免冲突。',
+ keyMessage: '韬光养晦',
+ actionAdvice: '保守行事,等待转机',
+ philosophy: '天地不交,象征闭塞。君子应节俭修德,避免灾难,不贪求禄位。',
+ lines: [
+ {
+ type: 'yin',
+ text: '拔茅茹,以其汇,贞吉,亨。',
+ image: '拔茅贞吉,志在君也。'
+ },
+ {
+ type: 'yin',
+ text: '包承,小人吉,大人否,亨。',
+ image: '大人否亨,不乱群也。'
+ },
+ {
+ type: 'yin',
+ text: '包羞。',
+ image: '包羞,位不当也。'
+ },
+ {
+ type: 'yang',
+ text: '有命无咎,畴离祉。',
+ image: '有命无咎,志行也。'
+ },
+ {
+ type: 'yang',
+ text: '休否,大人吉。其亡其亡,系于苞桑。',
+ image: '大人之吉,位正当也。'
+ },
+ {
+ type: 'yang',
+ text: '倾否,先否后喜。',
+ image: '否终则倾,何可长也。'
+ }
+ ]
+ },
+ 13: {
+ number: 13,
+ name: '同人',
+ symbol: '䷌',
+ binary: '101111',
+ upperTrigram: '乾',
+ lowerTrigram: '离',
+ meaning: '同人,团结,和谐',
+ judgment: '同人于野,亨。利涉大川,利君子贞。',
+ image: '天与火,同人。君子以类族辨物。',
+ guidance: '这是团结合作的时期。与志同道合的人联合,可以克服困难,实现远大目标。',
+ career: '团队合作将带来成功。寻找有共同目标的伙伴,共同努力。',
+ relationship: '与伴侣或朋友同心协力,关系将更加牢固和谐。',
+ keyMessage: '同心协力',
+ actionAdvice: '寻求合作,团结一致',
+ philosophy: '天与火同升,象征同心同德。君子应分类辨物,团结众人。',
+ lines: [
+ {
+ type: 'yang',
+ text: '同人于门,无咎。',
+ image: '出门同人,又谁咎也。'
+ },
+ {
+ type: 'yin',
+ text: '同人于宗,吝。',
+ image: '同人于宗,吝道也。'
+ },
+ {
+ type: 'yang',
+ text: '伏戎于莽,升其高陵,三岁不兴。',
+ image: '伏戎于莽,敌刚也。三岁不兴,安行也。'
+ },
+ {
+ type: 'yang',
+ text: '乘其墉,弗克攻,吉。',
+ image: '乘其墉,义弗克也。其吉,则困而反则也。'
+ },
+ {
+ type: 'yang',
+ text: '同人,先号咷而后笑,大师克相遇。',
+ image: '同人之先,以中直也。大师相遇,言相克也。'
+ },
+ {
+ type: 'yang',
+ text: '同人于郊,无悔。',
+ image: '同人于郊,志未得也。'
+ }
+ ]
+ },
+ 14: {
+ number: 14,
+ name: '大有',
+ symbol: '䷍',
+ binary: '111101',
+ upperTrigram: '离',
+ lowerTrigram: '乾',
+ meaning: '大有,丰盛,富有',
+ judgment: '元亨。',
+ image: '火在天上,大有。君子以遏恶扬善,顺天休命。',
+ guidance: '这是一个丰盛富足的时期。拥有很多资源和机会,应当善用这些优势,同时保持谦逊。',
+ career: '事业兴旺,资源丰富。适合扩大规模,但要避免骄傲自满。',
+ relationship: '关系充实美满,感情丰富。要珍惜现有的幸福,避免过度索取。',
+ keyMessage: '丰盛富足',
+ actionAdvice: '善用资源,保持谦逊',
+ philosophy: '火在天上,光明普照,象征大有。君子应抑恶扬善,顺应天命。',
+ lines: [
+ {
+ type: 'yang',
+ text: '无交害,匪咎,艰则无咎。',
+ image: '大有初九,无交害也。'
+ },
+ {
+ type: 'yang',
+ text: '大车以载,有攸往,无咎。',
+ image: '大车以载,积中不败也。'
+ },
+ {
+ type: 'yang',
+ text: '公用亨于天子,小人弗克。',
+ image: '公用亨于天子,小人害也。'
+ },
+ {
+ type: 'yang',
+ text: '匪其彭,无咎。',
+ image: '匪其彭,无咎,明辨皙也。'
+ },
+ {
+ type: 'yin',
+ text: '厥孚交如,威如,吉。',
+ image: '厥孚交如,信以发志也。威如之吉,易而无备也。'
+ },
+ {
+ type: 'yang',
+ text: '自天佑之,吉无不利。',
+ image: '大有上吉,自天佑也。'
+ }
+ ]
+ },
+ 15: {
+ number: 15,
+ name: '谦',
+ symbol: '䷎',
+ binary: '001000',
+ upperTrigram: '坤',
+ lowerTrigram: '艮',
+ meaning: '谦虚,谦逊,低调',
+ judgment: '亨,君子有终。',
+ image: '地中有山,谦。君子以裒多益寡,称物平施。',
+ guidance: '保持谦虚和低调。真正的力量在于内在的谦逊,这将带来长久的成功和尊重。',
+ career: '即使取得成就也要保持谦逊。谦虚的态度会赢得更多支持和机会。',
+ relationship: '在关系中保持谦逊,不炫耀,不争强好胜,会让感情更加和谐。',
+ keyMessage: '谦虚受益',
+ actionAdvice: '保持谦逊,低调行事',
+ philosophy: '山在地中,象征谦虚。君子应减少过多,补充不足,公平施予。',
+ lines: [
+ {
+ type: 'yin',
+ text: '谦谦君子,用涉大川,吉。',
+ image: '谦谦君子,卑以自牧也。'
+ },
+ {
+ type: 'yin',
+ text: '鸣谦,贞吉。',
+ image: '鸣谦贞吉,中心得也。'
+ },
+ {
+ type: 'yang',
+ text: '劳谦,君子有终,吉。',
+ image: '劳谦君子,万民服也。'
+ },
+ {
+ type: 'yin',
+ text: '无不利,撝谦。',
+ image: '无不利撝谦,不违则也。'
+ },
+ {
+ type: 'yin',
+ text: '不富以其邻,利用侵伐,无不利。',
+ image: '利用侵伐,征不服也。'
+ },
+ {
+ type: 'yin',
+ text: '鸣谦,利用行师,征邑国。',
+ image: '鸣谦,志未得也。可用行师,征邑国也。'
+ }
+ ]
+ },
+ 16: {
+ number: 16,
+ name: '豫',
+ symbol: '䷏',
+ binary: '000100',
+ upperTrigram: '震',
+ lowerTrigram: '坤',
+ meaning: '喜悦,预备,娱乐',
+ judgment: '利建侯行师。',
+ image: '雷出地奋,豫。先王以作乐崇德,殷荐之上帝,以配祖考。',
+ guidance: '这是一个喜悦和预备的时期。保持乐观的心态,为未来的行动做好准备。',
+ career: '适合制定计划,为未来的发展做准备。保持积极的态度。',
+ relationship: '享受当下的美好时光,同时为关系的进一步发展做准备。',
+ keyMessage: '喜悦预备',
+ actionAdvice: '保持乐观,做好准备',
+ philosophy: '雷出地上,万物振奋,象征喜悦。古代君王因此制礼作乐,推崇德行。',
+ lines: [
+ {
+ type: 'yin',
+ text: '鸣豫,凶。',
+ image: '初六鸣豫,志穷凶也。'
+ },
+ {
+ type: 'yin',
+ text: '介于石,不终日,贞吉。',
+ image: '不终日贞吉,以中正也。'
+ },
+ {
+ type: 'yin',
+ text: '盱豫悔,迟有悔。',
+ image: '盱豫有悔,位不当也。'
+ },
+ {
+ type: 'yang',
+ text: '由豫,大有得,勿疑朋盍簪。',
+ image: '由豫大有得,志大行也。'
+ },
+ {
+ type: 'yin',
+ text: '贞疾,恒不死。',
+ image: '六五贞疾,乘刚也。恒不死,中未亡也。'
+ },
+ {
+ type: 'yin',
+ text: '冥豫,成有渝,无咎。',
+ image: '冥豫在上,何可长也。'
+ }
+ ]
+ },
+ 17: {
+ number: 17,
+ name: '随',
+ symbol: '䷐',
+ binary: '100110',
+ upperTrigram: '兑',
+ lowerTrigram: '震',
+ meaning: '跟随,顺应,随和',
+ judgment: '元亨,利贞,无咎。',
+ image: '泽中有雷,随。君子以向晦入宴息。',
+ guidance: '这是顺应时势、跟随领导的时期。保持灵活和适应性,将获得顺利的发展。',
+ career: '适合跟随有经验的领导或团队,学习经验,不要急于出头。',
+ relationship: '在关系中保持随和,跟随对方的节奏,会让关系更加和谐。',
+ keyMessage: '顺势而为',
+ actionAdvice: '保持灵活,跟随领导',
+ philosophy: '雷在泽中,象征跟随。君子应顺应天时,该休息时休息。',
+ lines: [
+ {
+ type: 'yang',
+ text: '官有渝,贞吉。出门交有功。',
+ image: '官有渝,从正吉也。出门交有功,不失也。'
+ },
+ {
+ type: 'yin',
+ text: '系小子,失丈夫。',
+ image: '系小子,弗兼与也。'
+ },
+ {
+ type: 'yin',
+ text: '系丈夫,失小子。随有求得,利居贞。',
+ image: '系丈夫,志舍下也。'
+ },
+ {
+ type: 'yang',
+ text: '随有获,贞凶。有孚在道,以明,何咎。',
+ image: '随有获,其义凶也。有孚在道,明功也。'
+ },
+ {
+ type: 'yang',
+ text: '孚于嘉,吉。',
+ image: '孚于嘉吉,位正中也。'
+ },
+ {
+ type: 'yin',
+ text: '拘系之,乃从维之。王用亨于西山。',
+ image: '拘系之,上穷也。'
+ }
+ ]
+ },
+ 18: {
+ number: 18,
+ name: '蛊',
+ symbol: '䷑',
+ binary: '011001',
+ upperTrigram: '艮',
+ lowerTrigram: '巽',
+ meaning: '腐败,革新,整治',
+ judgment: '元亨,利涉大川。先甲三日,后甲三日。',
+ image: '山下有风,蛊。君子以振民育德。',
+ guidance: '需要革新和整治腐败。虽然面临困难,但这是必要的改革,将带来新的生机。',
+ career: '需要改革或整顿工作环境。虽然过程艰难,但会带来更好的发展。',
+ relationship: '关系中需要清理积弊,重新开始。需要勇气和决心。',
+ keyMessage: '革新整治',
+ actionAdvice: '勇于改革,清理积弊',
+ philosophy: '山下有风,象征腐败。君子应振奋民心,培育德行。',
+ lines: [
+ {
+ type: 'yin',
+ text: '干父之蛊,有子,考无咎,厉终吉。',
+ image: '干父之蛊,意承考也。'
+ },
+ {
+ type: 'yang',
+ text: '干母之蛊,不可贞。',
+ image: '干母之蛊,得中道也。'
+ },
+ {
+ type: 'yin',
+ text: '干父之蛊,小有悔,无大咎。',
+ image: '干父之蛊,终无咎也。'
+ },
+ {
+ type: 'yin',
+ text: '裕父之蛊,往见吝。',
+ image: '裕父之蛊,往未得也。'
+ },
+ {
+ type: 'yin',
+ text: '干父之蛊,用誉。',
+ image: '干父用誉,承以德也。'
+ },
+ {
+ type: 'yang',
+ text: '不事王侯,高尚其事。',
+ image: '不事王侯,志可则也。'
+ }
+ ]
+ },
+ 19: {
+ number: 19,
+ name: '临',
+ symbol: '䷒',
+ binary: '110000',
+ upperTrigram: '坤',
+ lowerTrigram: '兑',
+ meaning: '临近,监督,领导',
+ judgment: '元亨,利贞。至于八月有凶。',
+ image: '泽上有地,临。君子以教思无穷,容保民无疆。',
+ guidance: '处于领导或监督的位置。需要以开放的心态接近他人,给予指导和保护。',
+ career: '适合担任领导或管理角色。需要亲近团队,给予支持和指导。',
+ relationship: '在关系中扮演保护者和指导者的角色,给予对方安全感和支持。',
+ keyMessage: '亲近指导',
+ actionAdvice: '亲近他人,给予指导',
+ philosophy: '地在泽上,象征临近。君子应教化无穷,包容保护民众。',
+ lines: [
+ {
+ type: 'yin',
+ text: '咸临,贞吉。',
+ image: '咸临贞吉,志行正也。'
+ },
+ {
+ type: 'yin',
+ text: '咸临,吉无不利。',
+ image: '咸临吉无不利,未顺命也。'
+ },
+ {
+ type: 'yin',
+ text: '甘临,无攸利。既忧之,无咎。',
+ image: '甘临,位不当也。既忧之,咎不长也。'
+ },
+ {
+ type: 'yin',
+ text: '至临,无咎。',
+ image: '至临无咎,位当也。'
+ },
+ {
+ type: 'yang',
+ text: '知临,大君之宜,吉。',
+ image: '大君之宜,行中之谓也。'
+ },
+ {
+ type: 'yin',
+ text: '敦临,吉无咎。',
+ image: '敦临之吉,志在内也。'
+ }
+ ]
+ },
+ 20: {
+ number: 20,
+ name: '观',
+ symbol: '䷓',
+ binary: '000011',
+ upperTrigram: '巽',
+ lowerTrigram: '坤',
+ meaning: '观察,展示,省察',
+ judgment: '盥而不荐,有孚颙若。',
+ image: '风行地上,观。先王以省方观民设教。',
+ guidance: '需要仔细观察和审视。像祭祀前洗手一样,保持虔诚和专注的态度。',
+ career: '适合观察市场动向,学习他人经验。不要急于行动,先了解情况。',
+ relationship: '需要更多观察和理解对方。保持耐心和关注。',
+ keyMessage: '仔细观察',
+ actionAdvice: '保持专注,深入了解',
+ philosophy: '风行地上,遍观万物。古代君王因此巡视四方,观察民情,设立教化。',
+ lines: [
+ {
+ type: 'yin',
+ text: '童观,小人无咎,君子吝。',
+ image: '初六童观,小人道也。'
+ },
+ {
+ type: 'yin',
+ text: '窥观,利女贞。',
+ image: '窥观女贞,亦可丑也。'
+ },
+ {
+ type: 'yin',
+ text: '观我生,进退。',
+ image: '观我生,进退未失道也。'
+ },
+ {
+ type: 'yin',
+ text: '观国之光,利用宾于王。',
+ image: '观国之光,尚宾也。'
+ },
+ {
+ type: 'yang',
+ text: '观我生,君子无咎。',
+ image: '观我生,观民也。'
+ },
+ {
+ type: 'yang',
+ text: '观其生,君子无咎。',
+ image: '观其生,志未平也。'
+ }
+ ]
+ },
+ 21: {
+ number: 21,
+ name: '噬嗑',
+ symbol: '䷔',
+ binary: '100101',
+ upperTrigram: '离',
+ lowerTrigram: '震',
+ meaning: '咬合,刑罚,决断',
+ judgment: '亨。利用狱。',
+ image: '雷电,噬嗑。先王以明罚敕法。',
+ guidance: '需要果断处理障碍和问题。像咬合一样,清除阻碍,恢复通畅。',
+ career: '需要解决工作中的障碍或冲突。采取果断措施,清除问题。',
+ relationship: '关系中需要解决积累的矛盾。坦诚沟通,消除误会。',
+ keyMessage: '果断处理',
+ actionAdvice: '清除障碍,解决问题',
+ philosophy: '雷电交加,象征咬合。古代君王因此明正刑罚,整饬法度。',
+ lines: [
+ {
+ type: 'yin',
+ text: '屦校灭趾,无咎。',
+ image: '屦校灭趾,不行也。'
+ },
+ {
+ type: 'yin',
+ text: '噬肤灭鼻,无咎。',
+ image: '噬肤灭鼻,乘刚也。'
+ },
+ {
+ type: 'yin',
+ text: '噬腊肉,遇毒,小吝,无咎。',
+ image: '遇毒,位不当也。'
+ },
+ {
+ type: 'yang',
+ text: '噬干胏,得金矢,利艰贞,吉。',
+ image: '利艰贞吉,未光也。'
+ },
+ {
+ type: 'yin',
+ text: '噬干肉,得黄金,贞厉,无咎。',
+ image: '贞厉无咎,得当也。'
+ },
+ {
+ type: 'yang',
+ text: '何校灭耳,凶。',
+ image: '何校灭耳,聪不明也。'
+ }
+ ]
+ },
+ 22: {
+ number: 22,
+ name: '贲',
+ symbol: '䷕',
+ binary: '101001',
+ upperTrigram: '艮',
+ lowerTrigram: '离',
+ meaning: '装饰,美化,文饰',
+ judgment: '亨。小利有攸往。',
+ image: '山下有火,贲。君子以明庶政,无敢折狱。',
+ guidance: '需要适当的装饰和美化。注重外表和形式,但不要忽视内在的本质。',
+ career: '适合改善形象,提升外在表现。但要注意实质内容的提升。',
+ relationship: '关系中需要一些浪漫和美化,让感情更加丰富多彩。',
+ keyMessage: '适度装饰',
+ actionAdvice: '美化外表,注重实质',
+ philosophy: '山下有火,光辉照耀,象征装饰。君子应明察政务,不轻率断案。',
+ lines: [
+ {
+ type: 'yang',
+ text: '贲其趾,舍车而徒。',
+ image: '舍车而徒,义弗乘也。'
+ },
+ {
+ type: 'yin',
+ text: '贲其须。',
+ image: '贲其须,与上兴也。'
+ },
+ {
+ type: 'yang',
+ text: '贲如濡如,永贞吉。',
+ image: '永贞之吉,终莫之陵也。'
+ },
+ {
+ type: 'yin',
+ text: '贲如皤如,白马翰如,匪寇婚媾。',
+ image: '六四当位疑也。匪寇婚媾,终无尤也。'
+ },
+ {
+ type: 'yin',
+ text: '贲于丘园,束帛戋戋,吝,终吉。',
+ image: '六五之吉,有喜也。'
+ },
+ {
+ type: 'yang',
+ text: '白贲,无咎。',
+ image: '白贲无咎,上得志也。'
+ }
+ ]
+ },
+ 23: {
+ number: 23,
+ name: '剥',
+ symbol: '䷖',
+ binary: '000001',
+ upperTrigram: '艮',
+ lowerTrigram: '坤',
+ meaning: '剥落,侵蚀,衰败',
+ judgment: '不利有攸往。',
+ image: '山附于地,剥。上以厚下安宅。',
+ guidance: '处于衰败和剥落的时期。需要接受现实,保存实力,等待时机好转。',
+ career: '事业可能面临衰退或困难。需要保守经营,减少损失。',
+ relationship: '关系可能出现裂痕或疏远。需要耐心修复,或接受现实。',
+ keyMessage: '保存实力',
+ actionAdvice: '接受现实,等待转机',
+ philosophy: '山附于地,象征剥落。上位者应厚待下民,安定居所。',
+ lines: [
+ {
+ type: 'yin',
+ text: '剥床以足,蔑贞凶。',
+ image: '剥床以足,以灭下也。'
+ },
+ {
+ type: 'yin',
+ text: '剥床以辨,蔑贞凶。',
+ image: '剥床以辨,未有与也。'
+ },
+ {
+ type: 'yin',
+ text: '剥之,无咎。',
+ image: '剥之无咎,失上下也。'
+ },
+ {
+ type: 'yin',
+ text: '剥床以肤,凶。',
+ image: '剥床以肤,切近灾也。'
+ },
+ {
+ type: 'yin',
+ text: '贯鱼,以宫人宠,无不利。',
+ image: '以宫人宠,终无尤也。'
+ },
+ {
+ type: 'yang',
+ text: '硕果不食,君子得舆,小人剥庐。',
+ image: '君子得舆,民所载也。小人剥庐,终不可用也。'
+ }
+ ]
+ },
+ 24: {
+ number: 24,
+ name: '复',
+ symbol: '䷗',
+ binary: '100000',
+ upperTrigram: '坤',
+ lowerTrigram: '震',
+ meaning: '回复,复兴,回归',
+ judgment: '亨。出入无疾,朋来无咎。反复其道,七日来复,利有攸往。',
+ image: '雷在地中,复。先王以至日闭关,商旅不行,后不省方。',
+ guidance: '这是复兴和回归的时期。像冬至后阳气回复一样,新的开始即将到来。',
+ career: '事业将迎来转机,新的开始。保持信心,准备重新出发。',
+ relationship: '关系将得到改善或重新开始。给彼此一个新的机会。',
+ keyMessage: '复兴回归',
+ actionAdvice: '准备新生,重新开始',
+ philosophy: '雷在地中,象征阳气回复。古代君王在冬至闭关静养,顺应天时。',
+ lines: [
+ {
+ type: 'yin',
+ text: '不远复,无祗悔,元吉。',
+ image: '不远之复,以修身也。'
+ },
+ {
+ type: 'yin',
+ text: '休复,吉。',
+ image: '休复之吉,以下仁也。'
+ },
+ {
+ type: 'yin',
+ text: '频复,厉无咎。',
+ image: '频复之厉,义无咎也。'
+ },
+ {
+ type: 'yin',
+ text: '中行独复。',
+ image: '中行独复,以从道也。'
+ },
+ {
+ type: 'yin',
+ text: '敦复,无悔。',
+ image: '敦复无悔,中以自考也。'
+ },
+ {
+ type: 'yin',
+ text: '迷复,凶,有灾眚。用行师,终有大败,以其国君,凶,至于十年不克征。',
+ image: '迷复之凶,反君道也。'
+ }
+ ]
+ },
+ 25: {
+ number: 25,
+ name: '无妄',
+ symbol: '䷘',
+ binary: '100111',
+ upperTrigram: '乾',
+ lowerTrigram: '震',
+ meaning: '无妄,真诚,不妄为',
+ judgment: '元亨,利贞。其匪正有眚,不利有攸往。',
+ image: '天下雷行,物与无妄。先王以茂对时育万物。',
+ guidance: '保持真诚和正直,不要轻举妄动。顺应自然规律,将获得顺利发展。',
+ career: '工作中保持诚实正直,不要投机取巧。踏实做事会带来成功。',
+ relationship: '在关系中保持真诚,不要虚伪做作。真诚是感情的基础。',
+ keyMessage: '真诚无妄',
+ actionAdvice: '保持真诚,顺应自然',
+ philosophy: '天下雷行,万物各正其命。古代君王因此顺应天时,养育万物。',
+ lines: [
+ {
+ type: 'yang',
+ text: '无妄,往吉。',
+ image: '无妄之往,得志也。'
+ },
+ {
+ type: 'yin',
+ text: '不耕获,不菑畲,则利有攸往。',
+ image: '不耕获,未富也。'
+ },
+ {
+ type: 'yin',
+ text: '无妄之灾,或系之牛,行人之得,邑人之灾。',
+ image: '行人得牛,邑人灾也。'
+ },
+ {
+ type: 'yang',
+ text: '可贞,无咎。',
+ image: '可贞无咎,固有之也。'
+ },
+ {
+ type: 'yang',
+ text: '无妄之疾,勿药有喜。',
+ image: '无妄之药,不可试也。'
+ },
+ {
+ type: 'yin',
+ text: '无妄,行有眚,无攸利。',
+ image: '无妄之行,穷之灾也。'
+ }
+ ]
+ },
+ 26: {
+ number: 26,
+ name: '大畜',
+ symbol: '䷙',
+ binary: '111001',
+ upperTrigram: '艮',
+ lowerTrigram: '乾',
+ meaning: '大畜,积蓄,停止',
+ judgment: '利贞。不家食吉。利涉大川。',
+ image: '天在山中,大畜。君子以多识前言往行,以畜其德。',
+ guidance: '这是一个大量积蓄和准备的时期。积累知识、经验和资源,为将来大发展做准备。',
+ career: '适合大量学习和积累经验,为将来的事业腾飞做准备。',
+ relationship: '关系中需要积蓄感情和信任,为长远发展打下基础。',
+ keyMessage: '大量积蓄',
+ actionAdvice: '积累知识,准备未来',
+ philosophy: '天在山中,象征大量积蓄。君子应多学先贤言行,积蓄德行。',
+ lines: [
+ {
+ type: 'yang',
+ text: '有厉,利已。',
+ image: '有厉利已,不犯灾也。'
+ },
+ {
+ type: 'yang',
+ text: '舆说輹。',
+ image: '舆说輹,中无尤也。'
+ },
+ {
+ type: 'yang',
+ text: '良马逐,利艰贞。曰闲舆卫,利有攸往。',
+ image: '利有攸往,上合志也。'
+ },
+ {
+ type: 'yin',
+ text: '童牛之牿,元吉。',
+ image: '六四元吉,有喜也。'
+ },
+ {
+ type: 'yin',
+ text: '豮豕之牙,吉。',
+ image: '六五之吉,有庆也。'
+ },
+ {
+ type: 'yang',
+ text: '何天之衢,亨。',
+ image: '何天之衢,道大行也。'
+ }
+ ]
+ },
+ 27: {
+ number: 27,
+ name: '颐',
+ symbol: '䷚',
+ binary: '100001',
+ upperTrigram: '艮',
+ lowerTrigram: '震',
+ meaning: '颐养,饮食,养生',
+ judgment: '贞吉。观颐,自求口实。',
+ image: '山下有雷,颐。君子以慎言语,节饮食。',
+ guidance: '注重养生和内在调养。注意言行举止,合理饮食,保持身心健康。',
+ career: '工作中要注意劳逸结合,保养身体,才能持续发展。',
+ relationship: '关系中需要相互照顾和滋养,建立健康的关系模式。',
+ keyMessage: '颐养身心',
+ actionAdvice: '注意养生,保持健康',
+ philosophy: '山下有雷,象征颐养。君子应谨慎言语,节制饮食。',
+ lines: [
+ {
+ type: 'yang',
+ text: '舍尔灵龟,观我朵颐,凶。',
+ image: '观我朵颐,亦不足贵也。'
+ },
+ {
+ type: 'yin',
+ text: '颠颐,拂经,于丘颐,征凶。',
+ image: '六二征凶,行失类也。'
+ },
+ {
+ type: 'yin',
+ text: '拂颐,贞凶,十年勿用,无攸利。',
+ image: '十年勿用,道大悖也。'
+ },
+ {
+ type: 'yin',
+ text: '颠颐,吉。虎视眈眈,其欲逐逐,无咎。',
+ image: '颠颐之吉,上施光也。'
+ },
+ {
+ type: 'yin',
+ text: '拂经,居贞吉,不可涉大川。',
+ image: '居贞之吉,顺以从上也。'
+ },
+ {
+ type: 'yang',
+ text: '由颐,厉吉,利涉大川。',
+ image: '由颐厉吉,大有庆也。'
+ }
+ ]
+ },
+ 28: {
+ number: 28,
+ name: '大过',
+ symbol: '䷛',
+ binary: '011110',
+ upperTrigram: '兑',
+ lowerTrigram: '巽',
+ meaning: '大过,过度,极端',
+ judgment: '栋桡,利有攸往,亨。',
+ image: '泽灭木,大过。君子以独立不惧,遯世无闷。',
+ guidance: '处于非常时期,需要采取非常措施。虽然过度,但这是必要的。',
+ career: '面临重大挑战,需要采取非常手段。要有勇气和决心。',
+ relationship: '关系中可能出现极端情况,需要非常处理。',
+ keyMessage: '非常时期',
+ actionAdvice: '采取非常措施,勇敢面对',
+ philosophy: '泽水淹没树木,象征过度。君子应独立不惧,避世不闷。',
+ lines: [
+ {
+ type: 'yin',
+ text: '藉用白茅,无咎。',
+ image: '藉用白茅,柔在下也。'
+ },
+ {
+ type: 'yang',
+ text: '枯杨生稊,老夫得其女妻,无不利。',
+ image: '老夫女妻,过以相与也。'
+ },
+ {
+ type: 'yang',
+ text: '栋桡,凶。',
+ image: '栋桡之凶,不可以有辅也。'
+ },
+ {
+ type: 'yang',
+ text: '栋隆,吉。有它吝。',
+ image: '栋隆之吉,不桡乎下也。'
+ },
+ {
+ type: 'yin',
+ text: '枯杨生华,老妇得其士夫,无咎无誉。',
+ image: '枯杨生华,何可久也。老妇士夫,亦可丑也。'
+ },
+ {
+ type: 'yin',
+ text: '过涉灭顶,凶,无咎。',
+ image: '过涉之凶,不可咎也。'
+ }
+ ]
+ },
+ 29: {
+ number: 29,
+ name: '坎',
+ symbol: '䷜',
+ binary: '010010',
+ upperTrigram: '坎',
+ lowerTrigram: '坎',
+ meaning: '坎险,危险,陷溺',
+ judgment: '习坎,有孚,维心亨,行有尚。',
+ image: '水洊至,习坎。君子以常德行,习教事。',
+ guidance: '面临重重困难和危险。保持诚信和坚定的信念,终将度过难关。',
+ career: '事业面临重重困难,需要谨慎应对。保持信心,不要放弃。',
+ relationship: '关系陷入困难时期,需要共同努力克服。',
+ keyMessage: '度过险关',
+ actionAdvice: '保持诚信,坚定信念',
+ philosophy: '水重叠而来,象征重重险难。君子应保持常德,熟习政教。',
+ lines: [
+ {
+ type: 'yin',
+ text: '习坎,入于坎窞,凶。',
+ image: '习坎入坎,失道凶也。'
+ },
+ {
+ type: 'yang',
+ text: '坎有险,求小得。',
+ image: '求小得,未出中也。'
+ },
+ {
+ type: 'yin',
+ text: '来之坎坎,险且枕,入于坎窞,勿用。',
+ image: '来之坎坎,终无功也。'
+ },
+ {
+ type: 'yin',
+ text: '樽酒簋贰,用缶,纳约自牖,终无咎。',
+ image: '樽酒簋贰,刚柔际也。'
+ },
+ {
+ type: 'yang',
+ text: '坎不盈,祇既平,无咎。',
+ image: '坎不盈,中未大也。'
+ },
+ {
+ type: 'yin',
+ text: '系用徽纆,置于丛棘,三岁不得,凶。',
+ image: '上六失道,凶三岁也。'
+ }
+ ]
+ },
+ 30: {
+ number: 30,
+ name: '离',
+ symbol: '䷝',
+ binary: '101101',
+ upperTrigram: '离',
+ lowerTrigram: '离',
+ meaning: '离明,光明,附丽',
+ judgment: '利贞,亨。畜牝牛,吉。',
+ image: '明两作,离。大人以继明照于四方。',
+ guidance: '光明普照,事业顺利。保持光明正大的态度,将获得吉祥。',
+ career: '事业光明,前景良好。保持正直,继续努力。',
+ relationship: '关系明朗,感情深厚。保持真诚,珍惜彼此。',
+ keyMessage: '光明正大',
+ actionAdvice: '保持光明,继续努力',
+ philosophy: '光明两次升起,象征光明。大人应连续光明,照耀四方。',
+ lines: [
+ {
+ type: 'yang',
+ text: '履错然,敬之,无咎。',
+ image: '履错之敬,以辟咎也。'
+ },
+ {
+ type: 'yin',
+ text: '黄离,元吉。',
+ image: '黄离元吉,得中道也。'
+ },
+ {
+ type: 'yang',
+ text: '日昃之离,不鼓缶而歌,则大耋之嗟,凶。',
+ image: '日昃之离,何可久也。'
+ },
+ {
+ type: 'yang',
+ text: '突如其来如,焚如,死如,弃如。',
+ image: '突如其来如,无所容也。'
+ },
+ {
+ type: 'yin',
+ text: '出涕沱若,戚嗟若,吉。',
+ image: '六五之吉,离王公也。'
+ },
+ {
+ type: 'yang',
+ text: '王用出征,有嘉折首,获匪其丑,无咎。',
+ image: '王用出征,以正邦也。'
+ }
+ ]
+ },
+ 31: {
+ number: 31,
+ name: '咸',
+ symbol: '䷞',
+ binary: '110100',
+ upperTrigram: '兑',
+ lowerTrigram: '艮',
+ meaning: '感应,情感,交流',
+ judgment: '亨,利贞。取女吉。',
+ image: '山上有泽,咸。君子以虚受人。',
+ guidance: '这是情感交流和感应的时期。保持开放的心态,真诚交流,将带来和谐。',
+ career: '适合加强团队交流,增进感情。良好的人际关系将带来成功。',
+ relationship: '感情交流顺畅,适合深化关系。真诚相待,感情将更加深厚。',
+ keyMessage: '真诚感应',
+ actionAdvice: '开放交流,真诚相待',
+ philosophy: '山上有泽,二气感应。君子应虚心接受他人。',
+ lines: [
+ {
+ type: 'yin',
+ text: '咸其拇。',
+ image: '咸其拇,志在外也。'
+ },
+ {
+ type: 'yin',
+ text: '咸其腓,凶,居吉。',
+ image: '虽凶居吉,顺不害也。'
+ },
+ {
+ type: 'yang',
+ text: '咸其股,执其随,往吝。',
+ image: '咸其股,亦不处也。志在随人,所执下也。'
+ },
+ {
+ type: 'yang',
+ text: '贞吉,悔亡。憧憧往来,朋从尔思。',
+ image: '贞吉悔亡,未感害也。憧憧往来,未光大也。'
+ },
+ {
+ type: 'yin',
+ text: '咸其脢,无悔。',
+ image: '咸其脢,志末也。'
+ },
+ {
+ type: 'yin',
+ text: '咸其辅颊舌。',
+ image: '咸其辅颊舌,滕口说也。'
+ }
+ ]
+ },
+ 32: {
+ number: 32,
+ name: '恒',
+ symbol: '䷟',
+ binary: '001110',
+ upperTrigram: '震',
+ lowerTrigram: '巽',
+ meaning: '恒久,持久,稳定',
+ judgment: '亨,无咎,利贞。利有攸往。',
+ image: '雷风,恒。君子以立不易方。',
+ guidance: '建立长期稳定的关系或事业。持之以恒,坚持不懈,将获得持久成功。',
+ career: '建立长期稳定的事业基础。坚持原则,持续发展。',
+ relationship: '建立持久稳定的感情关系。相互理解,长久相伴。',
+ keyMessage: '持之以恒',
+ actionAdvice: '坚持原则,长期发展',
+ philosophy: '雷风相随,象征恒久。君子应确立不变的原则。',
+ lines: [
+ {
+ type: 'yin',
+ text: '浚恒,贞凶,无攸利。',
+ image: '浚恒之凶,始求深也。'
+ },
+ {
+ type: 'yang',
+ text: '悔亡。',
+ image: '九二悔亡,能久中也。'
+ },
+ {
+ type: 'yang',
+ text: '不恒其德,或承之羞,贞吝。',
+ image: '不恒其德,无所容也。'
+ },
+ {
+ type: 'yin',
+ text: '田无禽。',
+ image: '久非其位,安得禽也。'
+ },
+ {
+ type: 'yin',
+ text: '恒其德,贞,妇人吉,夫子凶。',
+ image: '妇人贞吉,从一而终也。夫子制义,从妇凶也。'
+ },
+ {
+ type: 'yin',
+ text: '振恒,凶。',
+ image: '振恒在上,大无功也。'
+ }
+ ]
+ },
+ 33: {
+ number: 33,
+ name: '遁',
+ symbol: '䷠',
+ binary: '111100',
+ upperTrigram: '乾',
+ lowerTrigram: '艮',
+ meaning: '退避,隐退,退让',
+ judgment: '亨,小利贞。',
+ image: '天下有山,遁。君子以远小人,不恶而严。',
+ guidance: '这是需要退避的时期。面对不利局面,明智的选择是暂时退让,保全实力。',
+ career: '事业遇到阻力时,学会适时退让,保存实力等待时机。',
+ relationship: '关系紧张时,适当保持距离,避免冲突升级。',
+ keyMessage: '适时退避',
+ actionAdvice: '保存实力,等待时机',
+ philosophy: '天下有山,象征退避。君子应远离小人,不恶而严。',
+ lines: [
+ {
+ type: 'yin',
+ text: '遁尾,厉,勿用有攸往。',
+ image: '遁尾之厉,不往何灾也。'
+ },
+ {
+ type: 'yin',
+ text: '执之用黄牛之革,莫之胜说。',
+ image: '执用黄牛,固志也。'
+ },
+ {
+ type: 'yang',
+ text: '系遁,有疾厉,畜臣妾吉。',
+ image: '系遁之厉,有疾惫也。畜臣妾吉,不可大事也。'
+ },
+ {
+ type: 'yang',
+ text: '好遁,君子吉,小人否。',
+ image: '君子好遁,小人否也。'
+ },
+ {
+ type: 'yang',
+ text: '嘉遁,贞吉。',
+ image: '嘉遁贞吉,以正志也。'
+ },
+ {
+ type: 'yang',
+ text: '肥遁,无不利。',
+ image: '肥遁无不利,无所疑也。'
+ }
+ ]
+ },
+ 34: {
+ number: 34,
+ name: '大壮',
+ symbol: '䷡',
+ binary: '111000',
+ upperTrigram: '震',
+ lowerTrigram: '乾',
+ meaning: '大壮,强壮,强盛',
+ judgment: '利贞。',
+ image: '雷在天上,大壮。君子以非礼弗履。',
+ guidance: '力量强盛的时期,但要谨慎使用力量,遵循正道,避免滥用。',
+ career: '事业处于强盛期,但要谨慎行事,避免过度扩张。',
+ relationship: '关系力量对比明显,强者要体恤弱者,保持平衡。',
+ keyMessage: '谨慎用强',
+ actionAdvice: '遵循正道,避免滥用',
+ philosophy: '雷在天上,象征强大。君子应不行非礼之事。',
+ lines: [
+ {
+ type: 'yang',
+ text: '壮于趾,征凶,有孚。',
+ image: '壮于趾,其孚穷也。'
+ },
+ {
+ type: 'yang',
+ text: '贞吉。',
+ image: '九二贞吉,以中也。'
+ },
+ {
+ type: 'yang',
+ text: '小人用壮,君子用罔,贞厉。羝羊触藩,羸其角。',
+ image: '小人用壮,君子罔也。'
+ },
+ {
+ type: 'yang',
+ text: '贞吉,悔亡。藩决不羸,壮于大舆之輹。',
+ image: '藩决不羸,尚往也。'
+ },
+ {
+ type: 'yin',
+ text: '丧羊于易,无悔。',
+ image: '丧羊于易,位不当也。'
+ },
+ {
+ type: 'yin',
+ text: '羝羊触藩,不能退,不能遂,无攸利,艰则吉。',
+ image: '不能退,不能遂,不祥也。艰则吉,咎不长也。'
+ }
+ ]
+ },
+ 35: {
+ number: 35,
+ name: '晋',
+ symbol: '䷢',
+ binary: '101000',
+ upperTrigram: '离',
+ lowerTrigram: '坤',
+ meaning: '晋升,前进,发展',
+ judgment: '康侯用锡马蕃庶,昼日三接。',
+ image: '明出地上,晋。君子以自昭明德。',
+ guidance: '事业和地位将获晋升。光明正大前进,必获成功。',
+ career: '事业将迎来晋升和发展机遇。把握机会,光明正大前进。',
+ relationship: '关系将向前发展,地位提升。保持谦逊,继续努力。',
+ keyMessage: '光明晋升',
+ actionAdvice: '把握机会,光明正大',
+ philosophy: '光明出现在地上,象征晋升。君子应彰显自己的美德。',
+ lines: [
+ {
+ type: 'yin',
+ text: '晋如摧如,贞吉。罔孚,裕无咎。',
+ image: '晋如摧如,独行正也。裕无咎,未受命也。'
+ },
+ {
+ type: 'yin',
+ text: '晋如愁如,贞吉。受兹介福,于其王母。',
+ image: '受兹介福,以中正也。'
+ },
+ {
+ type: 'yang',
+ text: '众允,悔亡。',
+ image: '众允之志,上行也。'
+ },
+ {
+ type: 'yang',
+ text: '晋如鼫鼠,贞厉。',
+ image: '鼫鼠贞厉,位不当也。'
+ },
+ {
+ type: 'yin',
+ text: '悔亡,失得勿恤,往吉,无不利。',
+ image: '失得勿恤,往有庆也。'
+ },
+ {
+ type: 'yang',
+ text: '晋其角,维用伐邑,厉吉,无咎,贞吝。',
+ image: '维用伐邑,道未光也。'
+ }
+ ]
+ },
+ 36: {
+ number: 36,
+ name: '明夷',
+ symbol: '䷣',
+ binary: '010001',
+ upperTrigram: '坤',
+ lowerTrigram: '离',
+ meaning: '明夷,光明受损,韬光养晦',
+ judgment: '利艰贞。',
+ image: '明入地中,明夷。君子以莅众,用晦而明。',
+ guidance: '光明受损的时期,需要韬光养晦,隐藏实力,等待时机。',
+ career: '事业受阻时,要低调行事,保存实力,等待东山再起。',
+ relationship: '关系出现阴影时,要包容理解,给彼此空间。',
+ keyMessage: '韬光养晦',
+ actionAdvice: '隐藏实力,等待时机',
+ philosophy: '光明进入地中,象征光明受损。君子治理众人,用晦而明。',
+ lines: [
+ {
+ type: 'yin',
+ text: '明夷于飞,垂其翼。君子于行,三日不食。有攸往,主人有言。',
+ image: '君子于行,义不食也。'
+ },
+ {
+ type: 'yin',
+ text: '明夷,夷于左股,用拯马壮,吉。',
+ image: '六二之吉,顺以则也。'
+ },
+ {
+ type: 'yang',
+ text: '明夷于南狩,得其大首,不可疾贞。',
+ image: '南狩之志,乃大得也。'
+ },
+ {
+ type: 'yin',
+ text: '入于左腹,获明夷之心,于出门庭。',
+ image: '入于左腹,获心意也。'
+ },
+ {
+ type: 'yin',
+ text: '箕子之明夷,利贞。',
+ image: '箕子之贞,明不可息也。'
+ },
+ {
+ type: 'yin',
+ text: '不明晦,初登于天,后入于地。',
+ image: '初登于天,照四国也。后入于地,失则也。'
+ }
+ ]
+ },
+ 37: {
+ number: 37,
+ name: '家人',
+ symbol: '䷤',
+ binary: '110101',
+ upperTrigram: '巽',
+ lowerTrigram: '离',
+ meaning: '家人,家庭,家人关系',
+ judgment: '利女贞。',
+ image: '风自火出,家人。君子以言有物而行有恒。',
+ guidance: '注重家庭关系,建立和谐家庭。家庭成员各守其位,家庭和睦。',
+ career: '事业与家庭要平衡,家庭和睦是事业成功的基础。',
+ relationship: '建立和谐的家庭关系,相互理解,共同经营。',
+ keyMessage: '家庭和睦',
+ actionAdvice: '各守其位,和谐相处',
+ philosophy: '风从火出,象征家人。君子说话有内容,行为有常度。',
+ lines: [
+ {
+ type: 'yang',
+ text: '闲有家,悔亡。',
+ image: '闲有家,志未变也。'
+ },
+ {
+ type: 'yin',
+ text: '无攸遂,在中馈,贞吉。',
+ image: '六二之吉,顺以巽也。'
+ },
+ {
+ type: 'yang',
+ text: '家人嗃嗃,悔厉吉。妇子嘻嘻,终吝。',
+ image: '家人嗃嗃,未失也。妇子嘻嘻,失家节也。'
+ },
+ {
+ type: 'yin',
+ text: '富家,大吉。',
+ image: '富家大吉,顺在位也。'
+ },
+ {
+ type: 'yang',
+ text: '王假有家,勿恤,吉。',
+ image: '王假有家,交相爱也。'
+ },
+ {
+ type: 'yang',
+ text: '有孚威如,终吉。',
+ image: '威如之吉,反身之谓也。'
+ }
+ ]
+ },
+ 38: {
+ number: 38,
+ name: '睽',
+ symbol: '䷥',
+ binary: '010110',
+ upperTrigram: '离',
+ lowerTrigram: '兑',
+ meaning: '睽违,分离,矛盾',
+ judgment: '小事吉。',
+ image: '上火下泽,睽。君子以同而异。',
+ guidance: '存在分歧和矛盾的时期。求同存异,小处着手,逐步化解矛盾。',
+ career: '团队存在分歧,需要求同存异,从小事做起改善关系。',
+ relationship: '关系出现裂痕,需要沟通理解,小步改善。',
+ keyMessage: '求同存异',
+ actionAdvice: '小处着手,逐步改善',
+ philosophy: '上火下泽,象征相违。君子应同中有异,异中求同。',
+ lines: [
+ {
+ type: 'yang',
+ text: '悔亡。丧马勿逐,自复。见恶人无咎。',
+ image: '见恶人,以辟咎也。'
+ },
+ {
+ type: 'yin',
+ text: '遇主于巷,无咎。',
+ image: '遇主于巷,未失道也。'
+ },
+ {
+ type: 'yin',
+ text: '见舆曳,其牛掣,其人天且劓,无初有终。',
+ image: '见舆曳,位不当也。无初有终,遇刚也。'
+ },
+ {
+ type: 'yang',
+ text: '睽孤,遇元夫,交孚,厉无咎。',
+ image: '交孚无咎,志行也。'
+ },
+ {
+ type: 'yin',
+ text: '悔亡。厥宗噬肤,往何咎。',
+ image: '厥宗噬肤,往有庆也。'
+ },
+ {
+ type: 'yang',
+ text: '睽孤,见豕负涂,载鬼一车,先张之弧,后说之弧,匪寇婚媾,往遇雨则吉。',
+ image: '遇雨之吉,群疑亡也。'
+ }
+ ]
+ },
+ 39: {
+ number: 39,
+ name: '蹇',
+ symbol: '䷦',
+ binary: '001010',
+ upperTrigram: '坎',
+ lowerTrigram: '艮',
+ meaning: '蹇难,困难,险阻',
+ judgment: '利西南,不利东北。利见大人,贞吉。',
+ image: '山上有水,蹇。君子以反身修德。',
+ guidance: '面临重重困难的时期。反省自身,修德养性,寻求贵人帮助。',
+ career: '事业遇到重大困难,需要反省改进,寻求指导。',
+ relationship: '关系遇到困难,需要反思自身,改善沟通。',
+ keyMessage: '反省修德',
+ actionAdvice: '寻求指导,改善自身',
+ philosophy: '山上有水,象征险阻。君子应反省自身,修养德行。',
+ lines: [
+ {
+ type: 'yin',
+ text: '往蹇,来誉。',
+ image: '往蹇来誉,宜待也。'
+ },
+ {
+ type: 'yang',
+ text: '王臣蹇蹇,匪躬之故。',
+ image: '王臣蹇蹇,终无尤也。'
+ },
+ {
+ type: 'yin',
+ text: '往蹇,来反。',
+ image: '往蹇来反,内喜之也。'
+ },
+ {
+ type: 'yin',
+ text: '往蹇,来连。',
+ image: '往蹇来连,当位实也。'
+ },
+ {
+ type: 'yang',
+ text: '大蹇,朋来。',
+ image: '大蹇朋来,以中节也。'
+ },
+ {
+ type: 'yin',
+ text: '往蹇,来硕,吉。利见大人。',
+ image: '往蹇来硕,志在内也。利见大人,以从贵也。'
+ }
+ ]
+ },
+ 40: {
+ number: 40,
+ name: '解',
+ symbol: '䷧',
+ binary: '010100',
+ upperTrigram: '震',
+ lowerTrigram: '坎',
+ meaning: '解除,解脱,解决',
+ judgment: '利西南。无所往,其来复吉。有攸往,夙吉。',
+ image: '雷雨作,解。君子以赦过宥罪。',
+ guidance: '困难即将解除,问题得到解决。释放压力,重新开始。',
+ career: '事业困境即将解除,可以重新开始发展。',
+ relationship: '关系中的矛盾将得到化解,重获和谐。',
+ keyMessage: '解除困境',
+ actionAdvice: '释放压力,重新开始',
+ philosophy: '雷雨大作,象征解除。君子应赦免过错,宽宥罪恶。',
+ lines: [
+ {
+ type: 'yin',
+ text: '无咎。',
+ image: '刚柔之际,义无咎也。'
+ },
+ {
+ type: 'yang',
+ text: '田获三狐,得黄矢,贞吉。',
+ image: '九二贞吉,得中道也。'
+ },
+ {
+ type: 'yin',
+ text: '负且乘,致寇至,贞吝。',
+ image: '负且乘,亦可丑也。自我致戎,又谁咎也。'
+ },
+ {
+ type: 'yang',
+ text: '解而拇,朋至斯孚。',
+ image: '解而拇,未当位也。'
+ },
+ {
+ type: 'yin',
+ text: '君子维有解,吉,有孚于小人。',
+ image: '君子有解,小人退也。'
+ },
+ {
+ type: 'yang',
+ text: '公用射隼于高墉之上,获之,无不利。',
+ image: '公用射隼,以解悖也。'
+ }
+ ]
+ },
+ 41: {
+ number: 41,
+ name: '损',
+ symbol: '䷨',
+ binary: '110001',
+ upperTrigram: '艮',
+ lowerTrigram: '兑',
+ meaning: '减损,减少,损失',
+ judgment: '有孚,元吉,无咎,可贞。利有攸往。曷之用?二簋可用享。',
+ image: '山下有泽,损。君子以惩忿窒欲。',
+ guidance: '需要减损和放弃的时期。减少不必要的欲望和开支,将获得更大收益。',
+ career: '事业需要精简和优化,减少不必要的开支,提高效率。',
+ relationship: '关系中需要减少争执和欲望,增进理解和包容。',
+ keyMessage: '精简减损',
+ actionAdvice: '减少欲望,增进效率',
+ philosophy: '山下有泽,象征减损。君子应抑制愤怒,遏制欲望。',
+ lines: [
+ {
+ type: 'yang',
+ text: '已事遄往,无咎,酌损之。',
+ image: '已事遄往,尚合志也。'
+ },
+ {
+ type: 'yang',
+ text: '利贞,征凶,弗损益之。',
+ image: '九二利贞,中以为志也。'
+ },
+ {
+ type: 'yin',
+ text: '三人行,则损一人;一人行,则得其友。',
+ image: '一人行,三则疑也。'
+ },
+ {
+ type: 'yin',
+ text: '损其疾,使遄有喜,无咎。',
+ image: '损其疾,亦可喜也。'
+ },
+ {
+ type: 'yin',
+ text: '或益之,十朋之龟弗克违,元吉。',
+ image: '六五元吉,自上佑也。'
+ },
+ {
+ type: 'yang',
+ text: '弗损益之,无咎,贞吉。利有攸往,得臣无家。',
+ image: '弗损益之,大得志也。'
+ }
+ ]
+ },
+ 42: {
+ number: 42,
+ name: '益',
+ symbol: '䷩',
+ binary: '100011',
+ upperTrigram: '巽',
+ lowerTrigram: '震',
+ meaning: '增益,增加,受益',
+ judgment: '利有攸往,利涉大川。',
+ image: '风雷,益。君子以见善则迁,有过则改。',
+ guidance: '这是增益和发展的时期。积极行动,将获得丰厚回报。',
+ career: '事业将迎来发展和增益,积极行动,把握机会。',
+ relationship: '关系将得到增进和改善,相互帮助,共同进步。',
+ keyMessage: '积极增益',
+ actionAdvice: '积极行动,把握机会',
+ philosophy: '风雷相助,象征增益。君子应见善则迁,有过则改。',
+ lines: [
+ {
+ type: 'yang',
+ text: '利用为大作,元吉,无咎。',
+ image: '元吉无咎,下不厚事也。'
+ },
+ {
+ type: 'yin',
+ text: '或益之,十朋之龟弗克违,永贞吉。王用享于帝,吉。',
+ image: '或益之,自外来也。'
+ },
+ {
+ type: 'yin',
+ text: '益之用凶事,无咎。有孚中行,告公用圭。',
+ image: '益用凶事,固有之也。'
+ },
+ {
+ type: 'yang',
+ text: '中行,告公从。利用为依迁国。',
+ image: '告公从,以益志也。'
+ },
+ {
+ type: 'yang',
+ text: '有孚惠心,勿问元吉。有孚惠我德。',
+ image: '有孚惠心,勿问之矣。惠我德,大得志也。'
+ },
+ {
+ type: 'yin',
+ text: '莫益之,或击之,立心勿恒,凶。',
+ image: '莫益之,偏辞也。或击之,自外来也。'
+ }
+ ]
+ },
+ 43: {
+ number: 43,
+ name: '夬',
+ symbol: '䷪',
+ binary: '111110',
+ upperTrigram: '兑',
+ lowerTrigram: '乾',
+ meaning: '决断,决裂,果断',
+ judgment: '扬于王庭,孚号有厉。告自邑,不利即戎,利有攸往。',
+ image: '泽上于天,夬。君子以施禄及下,居德则忌。',
+ guidance: '需要果断决断的时期。面对问题要当机立断,不可犹豫不决。',
+ career: '事业需要做出重大决策,果断行动,避免拖延。',
+ relationship: '关系中需要做出决断,避免藕断丝连。',
+ keyMessage: '果断决断',
+ actionAdvice: '当机立断,避免拖延',
+ philosophy: '泽水在天上,象征决断。君子应施恩于下,积德忌满。',
+ lines: [
+ {
+ type: 'yang',
+ text: '壮于前趾,往不胜为咎。',
+ image: '不胜而往,咎也。'
+ },
+ {
+ type: 'yang',
+ text: '惕号,莫夜有戎,勿恤。',
+ image: '有戎勿恤,得中道也。'
+ },
+ {
+ type: 'yang',
+ text: '壮于頄,有凶。君子夬夬,独行遇雨,若濡有愠,无咎。',
+ image: '君子夬夬,终无咎也。'
+ },
+ {
+ type: 'yang',
+ text: '臀无肤,其行次且。牵羊悔亡,闻言不信。',
+ image: '其行次且,位不当也。闻言不信,聪不明也。'
+ },
+ {
+ type: 'yang',
+ text: '苋陆夬夬,中行无咎。',
+ image: '中行无咎,中未光也。'
+ },
+ {
+ type: 'yin',
+ text: '无号,终有凶。',
+ image: '无号之凶,终不可长也。'
+ }
+ ]
+ },
+ 44: {
+ number: 44,
+ name: '姤',
+ symbol: '䷫',
+ binary: '011111',
+ upperTrigram: '乾',
+ lowerTrigram: '巽',
+ meaning: '相遇,邂逅,阴遇阳',
+ judgment: '女壮,勿用取女。',
+ image: '天下有风,姤。后以施命诰四方。',
+ guidance: '不期而遇的时期。小心处理新出现的关系,避免被不良影响。',
+ career: '事业中遇到新的机遇或挑战,要谨慎处理。',
+ relationship: '可能遇到新的感情或关系,需要谨慎对待。',
+ keyMessage: '谨慎相遇',
+ actionAdvice: '小心处理新关系',
+ philosophy: '天下有风,象征相遇。君主应发布命令,告喻四方。',
+ lines: [
+ {
+ type: 'yin',
+ text: '系于金柅,贞吉。有攸往,见凶,羸豕孚蹢躅。',
+ image: '系于金柅,柔道牵也。'
+ },
+ {
+ type: 'yang',
+ text: '包有鱼,无咎,不利宾。',
+ image: '包有鱼,义不及宾也。'
+ },
+ {
+ type: 'yang',
+ text: '臀无肤,其行次且,厉,无大咎。',
+ image: '其行次且,行未牵也。'
+ },
+ {
+ type: 'yang',
+ text: '包无鱼,起凶。',
+ image: '无鱼之凶,远民也。'
+ },
+ {
+ type: 'yang',
+ text: '以杞包瓜,含章,有陨自天。',
+ image: '九五含章,中正也。有陨自天,志不舍命也。'
+ },
+ {
+ type: 'yang',
+ text: '姤其角,吝,无咎。',
+ image: '姤其角,上穷吝也。'
+ }
+ ]
+ },
+ 45: {
+ number: 45,
+ name: '萃',
+ symbol: '䷬',
+ binary: '000110',
+ upperTrigram: '兑',
+ lowerTrigram: '坤',
+ meaning: '聚集,集合,汇聚',
+ judgment: '亨。王假有庙,利见大人,亨,利贞。用大牲吉,利有攸往。',
+ image: '泽上于地,萃。君子以除戎器,戒不虞。',
+ guidance: '这是聚集和团结的时期。集合力量,共同奋斗,将获得更大成功。',
+ career: '事业需要集合团队力量,共同奋斗,实现更大目标。',
+ relationship: '关系需要加强团结,共同面对挑战,增进感情。',
+ keyMessage: '集合力量',
+ actionAdvice: '团结奋斗,共同前进',
+ philosophy: '泽水在地上,象征聚集。君子应修整兵器,戒备不测。',
+ lines: [
+ {
+ type: 'yin',
+ text: '有孚不终,乃乱乃萃,若号,一握为笑,勿恤,往无咎。',
+ image: '乃乱乃萃,其志乱也。'
+ },
+ {
+ type: 'yin',
+ text: '引吉,无咎,孚乃利用禴。',
+ image: '引吉无咎,中未变也。'
+ },
+ {
+ type: 'yin',
+ text: '萃如,嗟如,无攸利,往无咎,小吝。',
+ image: '往无咎,上巽也。'
+ },
+ {
+ type: 'yang',
+ text: '大吉,无咎。',
+ image: '大吉无咎,位不当也。'
+ },
+ {
+ type: 'yang',
+ text: '萃有位,无咎。匪孚,元永贞,悔亡。',
+ image: '萃有位,志未光也。'
+ },
+ {
+ type: 'yin',
+ text: '赍咨涕洟,无咎。',
+ image: '赍咨涕洟,未安上也。'
+ }
+ ]
+ },
+ 46: {
+ number: 46,
+ name: '升',
+ symbol: '䷭',
+ binary: '011000',
+ upperTrigram: '坤',
+ lowerTrigram: '巽',
+ meaning: '上升,晋升,发展',
+ judgment: '元亨,用见大人,勿恤,南征吉。',
+ image: '地中生木,升。君子以顺德,积小以高大。',
+ guidance: '事业和地位将不断上升。循序渐进,终将获得高位。',
+ career: '事业将迎来上升期,循序渐进,稳步发展。',
+ relationship: '关系将不断升温,感情日益深厚。',
+ keyMessage: '循序渐进',
+ actionAdvice: '稳步发展,终获成功',
+ philosophy: '地中生出树木,象征上升。君子应顺应德行,积小成大。',
+ lines: [
+ {
+ type: 'yin',
+ text: '允升,大吉。',
+ image: '允升大吉,上合志也。'
+ },
+ {
+ type: 'yang',
+ text: '孚乃利用禴,无咎。',
+ image: '九二之孚,有喜也。'
+ },
+ {
+ type: 'yang',
+ text: '升虚邑。',
+ image: '升虚邑,无所疑也。'
+ },
+ {
+ type: 'yin',
+ text: '王用亨于岐山,吉,无咎。',
+ image: '王用亨于岐山,顺事也。'
+ },
+ {
+ type: 'yang',
+ text: '贞吉,升阶。',
+ image: '贞吉升阶,大得志也。'
+ },
+ {
+ type: 'yin',
+ text: '冥升,利于不息之贞。',
+ image: '冥升在上,消不富也。'
+ }
+ ]
+ },
+ 47: {
+ number: 47,
+ name: '困',
+ symbol: '䷮',
+ binary: '110010',
+ upperTrigram: '兑',
+ lowerTrigram: '坎',
+ meaning: '困穷,困境,困顿',
+ judgment: '亨,贞,大人吉,无咎。有言不信。',
+ image: '泽无水,困。君子以致命遂志。',
+ guidance: '处于困境的时期。虽处困境,但保持正道,终将脱困。',
+ career: '事业陷入困境,需要坚持正道,寻求突破。',
+ relationship: '关系陷入僵局,需要耐心化解,坚持信念。',
+ keyMessage: '坚持正道',
+ actionAdvice: '保持信念,寻求突破',
+ philosophy: '泽中无水,象征困穷。君子应舍命达成志向。',
+ lines: [
+ {
+ type: 'yin',
+ text: '臀困于株木,入于幽谷,三岁不觌。',
+ image: '入于幽谷,幽不明也。'
+ },
+ {
+ type: 'yang',
+ text: '困于酒食,朱绂方来,利用享祀,征凶,无咎。',
+ image: '困于酒食,中有庆也。'
+ },
+ {
+ type: 'yin',
+ text: '困于石,据于蒺藜,入于其宫,不见其妻,凶。',
+ image: '据于蒺藜,乘刚也。入于其宫,不见其妻,不祥也。'
+ },
+ {
+ type: 'yang',
+ text: '来徐徐,困于金车,吝,有终。',
+ image: '来徐徐,志在下也。虽不当位,有与也。'
+ },
+ {
+ type: 'yang',
+ text: '劓刖,困于赤绂,乃徐有说,利用祭祀。',
+ image: '劓刖志未得也。乃徐有说,以中直也。利用祭祀,受福也。'
+ },
+ {
+ type: 'yin',
+ text: '困于葛藟,于臲卼,曰动悔。有悔,征吉。',
+ image: '困于葛藟,未当也。动悔有悔,吉行也。'
+ }
+ ]
+ },
+ 48: {
+ number: 48,
+ name: '井',
+ symbol: '䷯',
+ binary: '001011',
+ upperTrigram: '坎',
+ lowerTrigram: '巽',
+ meaning: '水井,养人,恒常',
+ judgment: '改邑不改井,无丧无得,往来井井。汔至,亦未繘井,羸其瓶,凶。',
+ image: '木上有水,井。君子以劳民劝相。',
+ guidance: '建立持久的基础,滋养他人。保持恒常,持续改善。',
+ career: '建立稳固的事业基础,持续发展,滋养团队。',
+ relationship: '建立稳定的关系基础,相互滋养,长久发展。',
+ keyMessage: '建立基础',
+ actionAdvice: '持续改善,滋养他人',
+ philosophy: '木上有水,象征水井。君子应慰劳民众,劝勉相助。',
+ lines: [
+ {
+ type: 'yin',
+ text: '井泥不食,旧井无禽。',
+ image: '井泥不食,下也。旧井无禽,时舍也。'
+ },
+ {
+ type: 'yang',
+ text: '井谷射鲋,瓮敝漏。',
+ image: '井谷射鲋,无与也。'
+ },
+ {
+ type: 'yang',
+ text: '井渫不食,为我心恻。可用汲,王明,并受其福。',
+ image: '井渫不食,行恻也。求王明,受福也。'
+ },
+ {
+ type: 'yin',
+ text: '井甃,无咎。',
+ image: '井甃无咎,修井也。'
+ },
+ {
+ type: 'yang',
+ text: '井冽,寒泉食。',
+ image: '寒泉之食,中正也。'
+ },
+ {
+ type: 'yin',
+ text: '井收勿幕,有孚元吉。',
+ image: '元吉在上,大成也。'
+ }
+ ]
+ },
+ 49: {
+ number: 49,
+ name: '革',
+ symbol: '䷰',
+ binary: '101110',
+ upperTrigram: '兑',
+ lowerTrigram: '离',
+ meaning: '变革,改革,革命',
+ judgment: '己日乃孚,元亨利贞,悔亡。',
+ image: '泽中有火,革。君子以治历明时。',
+ guidance: '这是重大变革的时期。顺应时势,主动改革,将获得新生。',
+ career: '事业需要重大变革,破旧立新,开创新局面。',
+ relationship: '关系需要深度调整,改变旧模式,建立新关系。',
+ keyMessage: '主动变革',
+ actionAdvice: '破旧立新,顺应时势',
+ philosophy: '泽中有火,象征变革。君子应修治历法,明确时令。',
+ lines: [
+ {
+ type: 'yang',
+ text: '巩用黄牛之革。',
+ image: '巩用黄牛,不可以有为也。'
+ },
+ {
+ type: 'yin',
+ text: '己日乃革之,征吉,无咎。',
+ image: '己日革之,行有嘉也。'
+ },
+ {
+ type: 'yang',
+ text: '征凶,贞厉。革言三就,有孚。',
+ image: '革言三就,又何之矣。'
+ },
+ {
+ type: 'yang',
+ text: '悔亡,有孚改命,吉。',
+ image: '改命之吉,信志也。'
+ },
+ {
+ type: 'yang',
+ text: '大人虎变,未占有孚。',
+ image: '大人虎变,其文炳也。'
+ },
+ {
+ type: 'yin',
+ text: '君子豹变,小人革面,征凶,居贞吉。',
+ image: '君子豹变,其文蔚也。小人革面,顺以从君也。'
+ }
+ ]
+ },
+ 50: {
+ number: 50,
+ name: '鼎',
+ symbol: '䷱',
+ binary: '011101',
+ upperTrigram: '离',
+ lowerTrigram: '巽',
+ meaning: '鼎器,烹饪,养贤',
+ judgment: '元吉,亨。',
+ image: '木上有火,鼎。君子以正位凝命。',
+ guidance: '建立新秩序,培养人才。正位凝命,成就大业。',
+ career: '事业建立新体制,培养团队,成就大业。',
+ relationship: '关系建立新秩序,相互培养,共同成长。',
+ keyMessage: '建立新秩序',
+ actionAdvice: '培养人才,成就大业',
+ philosophy: '木上有火,象征鼎器。君子应端正位置,凝聚使命。',
+ lines: [
+ {
+ type: 'yin',
+ text: '鼎颠趾,利出否,得妾以其子,无咎。',
+ image: '鼎颠趾,未悖也。利出否,以从贵也。'
+ },
+ {
+ type: 'yin',
+ text: '鼎有实,我仇有疾,不我能即,吉。',
+ image: '鼎有实,慎所之也。我仇有疾,终无尤也。'
+ },
+ {
+ type: 'yang',
+ text: '鼎耳革,其行塞,雉膏不食,方雨亏悔,终吉。',
+ image: '鼎耳革,失其义也。'
+ },
+ {
+ type: 'yang',
+ text: '鼎折足,覆公餗,其形渥,凶。',
+ image: '覆公餗,信如何也。'
+ },
+ {
+ type: 'yin',
+ text: '鼎黄耳金铉,利贞。',
+ image: '鼎黄耳,中以为实也。'
+ },
+ {
+ type: 'yang',
+ text: '鼎玉铉,大吉,无不利。',
+ image: '玉铉在上,刚柔节也。'
+ }
+ ]
+ },
+ 51: {
+ number: 51,
+ name: '震',
+ symbol: '䷲',
+ binary: '100100',
+ upperTrigram: '震',
+ lowerTrigram: '震',
+ meaning: '震动,惊雷,行动',
+ judgment: '亨。震来虩虩,笑言哑哑。震惊百里,不丧匕鬯。',
+ image: '洊雷,震。君子以恐惧修省。',
+ guidance: '面临重大震动和挑战。保持冷静,化危为机,获得成长。',
+ career: '事业面临重大变化,保持镇定,化挑战为机遇。',
+ relationship: '关系经历震荡,需要冷静处理,增进理解。',
+ keyMessage: '化危为机',
+ actionAdvice: '保持冷静,获得成长',
+ philosophy: '雷声重叠,象征震动。君子应因恐惧而修身反省。',
+ lines: [
+ {
+ type: 'yang',
+ text: '震来虩虩,后笑言哑哑,吉。',
+ image: '震来虩虩,恐致福也。笑言哑哑,后有则也。'
+ },
+ {
+ type: 'yin',
+ text: '震来厉,亿丧贝,跻于九陵,勿逐,七日得。',
+ image: '震来厉,乘刚也。'
+ },
+ {
+ type: 'yin',
+ text: '震苏苏,震行无眚。',
+ image: '震苏苏,位不当也。'
+ },
+ {
+ type: 'yin',
+ text: '震遂泥。',
+ image: '震遂泥,未光也。'
+ },
+ {
+ type: 'yin',
+ text: '震往来厉,亿无丧,有事。',
+ image: '震往来厉,危行也。其事在中,大无丧也。'
+ },
+ {
+ type: 'yin',
+ text: '震索索,视矍矍,征凶。震不于其躬,于其邻,无咎。婚媾有言。',
+ image: '震索索,中未得也。虽凶无咎,畏邻戒也。'
+ }
+ ]
+ },
+ 52: {
+ number: 52,
+ name: '艮',
+ symbol: '䷳',
+ binary: '001001',
+ upperTrigram: '艮',
+ lowerTrigram: '艮',
+ meaning: '艮止,停止,静止',
+ judgment: '艮其背,不获其身,行其庭,不见其人,无咎。',
+ image: '兼山,艮。君子以思不出其位。',
+ guidance: '需要停止和反思的时期。适可而止,保持内心平静。',
+ career: '事业需要暂停调整,避免过度扩张,保持稳健。',
+ relationship: '关系需要冷静期,给彼此空间,避免冲突。',
+ keyMessage: '适可而止',
+ actionAdvice: '保持平静,避免冲动',
+ philosophy: '两山重叠,象征停止。君子思考不超越本位。',
+ lines: [
+ {
+ type: 'yin',
+ text: '艮其趾,无咎,利永贞。',
+ image: '艮其趾,未失正也。'
+ },
+ {
+ type: 'yin',
+ text: '艮其腓,不拯其随,其心不快。',
+ image: '不拯其随,未退听也。'
+ },
+ {
+ type: 'yang',
+ text: '艮其限,列其夤,厉薰心。',
+ image: '艮其限,危薰心也。'
+ },
+ {
+ type: 'yin',
+ text: '艮其身,无咎。',
+ image: '艮其身,止诸躬也。'
+ },
+ {
+ type: 'yin',
+ text: '艮其辅,言有序,悔亡。',
+ image: '艮其辅,以中正也。'
+ },
+ {
+ type: 'yang',
+ text: '敦艮,吉。',
+ image: '敦艮之吉,以厚终也。'
+ }
+ ]
+ },
+ 53: {
+ number: 53,
+ name: '渐',
+ symbol: '䷴',
+ binary: '001011',
+ upperTrigram: '巽',
+ lowerTrigram: '艮',
+ meaning: '渐进,逐步,循序渐进',
+ judgment: '女归吉,利贞。',
+ image: '山上有木,渐。君子以居贤德,善俗。',
+ guidance: '循序渐进发展的时期。稳步前进,终将达成目标。',
+ career: '事业需要循序渐进,稳步发展,避免急躁。',
+ relationship: '关系需要慢慢培养,循序渐进,建立深厚感情。',
+ keyMessage: '循序渐进',
+ actionAdvice: '稳步前进,终达目标',
+ philosophy: '山上生木,象征渐进。君子应居守贤德,改善风俗。',
+ lines: [
+ {
+ type: 'yin',
+ text: '鸿渐于干,小子厉,有言,无咎。',
+ image: '小子之厉,义无咎也。'
+ },
+ {
+ type: 'yin',
+ text: '鸿渐于磐,饮食衎衎,吉。',
+ image: '饮食衎衎,不素饱也。'
+ },
+ {
+ type: 'yang',
+ text: '鸿渐于陆,夫征不复,妇孕不育,凶。利御寇。',
+ image: '夫征不复,离群丑也。妇孕不育,失其道也。利用御寇,顺相保也。'
+ },
+ {
+ type: 'yin',
+ text: '鸿渐于木,或得其桷,无咎。',
+ image: '或得其桷,顺以巽也。'
+ },
+ {
+ type: 'yang',
+ text: '鸿渐于陵,妇三岁不孕,终莫之胜,吉。',
+ image: '终莫之胜,吉,得所愿也。'
+ },
+ {
+ type: 'yang',
+ text: '鸿渐于逵,其羽可用为仪,吉。',
+ image: '其羽可用为仪,吉,不可乱也。'
+ }
+ ]
+ },
+ 54: {
+ number: 54,
+ name: '归妹',
+ symbol: '䷵',
+ binary: '110100',
+ upperTrigram: '震',
+ lowerTrigram: '兑',
+ meaning: '归妹,嫁女,归宿',
+ judgment: '征凶,无攸利。',
+ image: '泽上有雷,归妹。君子以永终知敝。',
+ guidance: '关注归宿和结果的时期。谨慎处理终身大事,避免草率。',
+ career: '事业需要谨慎决策,避免草率行动导致不利后果。',
+ relationship: '关系涉及终身大事,需要慎重考虑,避免冲动。',
+ keyMessage: '谨慎归宿',
+ actionAdvice: '慎重决策,避免草率',
+ philosophy: '泽上有雷,象征嫁女。君子应知永恒终结之理。',
+ lines: [
+ {
+ type: 'yang',
+ text: '归妹以娣,跛能履,征吉。',
+ image: '归妹以娣,以恒也。跛能履,吉相承也。'
+ },
+ {
+ type: 'yang',
+ text: '眇能视,利幽人之贞。',
+ image: '利幽人之贞,未变常也。'
+ },
+ {
+ type: 'yin',
+ text: '归妹以须,反归以娣。',
+ image: '归妹以须,未当也。'
+ },
+ {
+ type: 'yang',
+ text: '归妹愆期,迟归有时。',
+ image: '愆期之志,有待而行也。'
+ },
+ {
+ type: 'yin',
+ text: '帝乙归妹,其君之袂,不如其娣之袂良,月几望,吉。',
+ image: '帝乙归妹,不如其娣之袂良也。其位在中,以贵行也。'
+ },
+ {
+ type: 'yin',
+ text: '女承筐无实,士刲羊无血,无攸利。',
+ image: '上六无实,承虚筐也。'
+ }
+ ]
+ },
+ 55: {
+ number: 55,
+ name: '丰',
+ symbol: '䷶',
+ binary: '101100',
+ upperTrigram: '震',
+ lowerTrigram: '离',
+ meaning: '丰盛,盛大,丰富',
+ judgment: '亨,王假之,勿忧,宜日中。',
+ image: '雷电皆至,丰。君子以折狱致刑。',
+ guidance: '事业丰盛盛大的时期。保持中正,避免过度,才能长久。',
+ career: '事业达到丰盛期,需要保持谦逊,避免骄傲自满。',
+ relationship: '关系丰盛美满,需要珍惜维护,避免过度。',
+ keyMessage: '保持中正',
+ actionAdvice: '珍惜丰盛,避免过度',
+ philosophy: '雷电俱至,象征丰盛。君子应断案用刑。',
+ lines: [
+ {
+ type: 'yang',
+ text: '遇其配主,虽旬无咎,往有尚。',
+ image: '虽旬无咎,过旬灾也。'
+ },
+ {
+ type: 'yin',
+ text: '丰其蔀,日中见斗,往得疑疾,有孚发若,吉。',
+ image: '有孚发若,信以发志也。'
+ },
+ {
+ type: 'yang',
+ text: '丰其沛,日中见沫,折其右肱,无咎。',
+ image: '丰其沛,不可大事也。折其右肱,终不可用也。'
+ },
+ {
+ type: 'yang',
+ text: '丰其蔀,日中见斗,遇其夷主,吉。',
+ image: '丰其蔀,位不当也。日中见斗,幽不明也。遇其夷主,吉,行也。'
+ },
+ {
+ type: 'yin',
+ text: '来章,有庆誉,吉。',
+ image: '六五之吉,有庆也。'
+ },
+ {
+ type: 'yin',
+ text: '丰其屋,蔀其家,窥其户,阒其无人,三岁不觌,凶。',
+ image: '丰其屋,天际翔也。窥其户,阒其无人,自藏也。'
+ }
+ ]
+ },
+ 56: {
+ number: 56,
+ name: '旅',
+ symbol: '䷷',
+ binary: '101001',
+ upperTrigram: '离',
+ lowerTrigram: '艮',
+ meaning: '旅行,旅居,漂泊',
+ judgment: '小亨,旅贞吉。',
+ image: '山上有火,旅。君子以明慎用刑,而不留狱。',
+ guidance: '处于旅行或漂泊的时期。保持谨慎,适应环境,终将安定。',
+ career: '事业处于变动期,需要适应新环境,保持谨慎。',
+ relationship: '关系处于不稳定期,需要相互理解,共同适应。',
+ keyMessage: '适应环境',
+ actionAdvice: '保持谨慎,终将安定',
+ philosophy: '山上有火,象征旅行。君子应明慎用刑,不留狱讼。',
+ lines: [
+ {
+ type: 'yin',
+ text: '旅琐琐,斯其所取灾。',
+ image: '旅琐琐,志穷灾也。'
+ },
+ {
+ type: 'yin',
+ text: '旅即次,怀其资,得童仆贞。',
+ image: '得童仆贞,终无尤也。'
+ },
+ {
+ type: 'yang',
+ text: '旅焚其次,丧其童仆,贞厉。',
+ image: '旅焚其次,亦以伤矣。以旅与下,其义丧也。'
+ },
+ {
+ type: 'yang',
+ text: '旅于处,得其资斧,我心不快。',
+ image: '旅于处,未得位也。得其资斧,心未快也。'
+ },
+ {
+ type: 'yin',
+ text: '射雉一矢亡,终以誉命。',
+ image: '终以誉命,上逮也。'
+ },
+ {
+ type: 'yang',
+ text: '鸟焚其巢,旅人先笑后号咷。丧牛于易,凶。',
+ image: '以旅在上,其义焚也。丧牛于易,终莫之闻也。'
+ }
+ ]
+ },
+ 57: {
+ number: 57,
+ name: '巽',
+ symbol: '䷸',
+ binary: '110110',
+ upperTrigram: '巽',
+ lowerTrigram: '巽',
+ meaning: '巽顺,顺从,谦逊',
+ judgment: '小亨,利攸往,利见大人。',
+ image: '随风,巽。君子以申命行事。',
+ guidance: '以谦逊柔顺的态度行事。顺应时势,将获得顺利发展。',
+ career: '事业需要谦逊态度,顺应时势,获得发展机会。',
+ relationship: '关系需要谦逊包容,相互理解,增进和谐。',
+ keyMessage: '谦逊柔顺',
+ actionAdvice: '顺应时势,获得发展',
+ philosophy: '风相随,象征顺从。君子应重申命令,推行政事。',
+ lines: [
+ {
+ type: 'yin',
+ text: '进退,利武人之贞。',
+ image: '进退,志疑也。利武人之贞,志治也。'
+ },
+ {
+ type: 'yang',
+ text: '巽在床下,用史巫纷若,吉,无咎。',
+ image: '纷若之吉,得中也。'
+ },
+ {
+ type: 'yang',
+ text: '频巽,吝。',
+ image: '频巽之吝,志穷也。'
+ },
+ {
+ type: 'yin',
+ text: '悔亡,田获三品。',
+ image: '田获三品,有功也。'
+ },
+ {
+ type: 'yang',
+ text: '贞吉悔亡,无不利。无初有终,先庚三日,后庚三日,吉。',
+ image: '九五之吉,位正中也。'
+ },
+ {
+ type: 'yin',
+ text: '巽在床下,丧其资斧,贞凶。',
+ image: '巽在床下,上穷也。丧其资斧,正乎凶也。'
+ }
+ ]
+ },
+ 58: {
+ number: 58,
+ name: '兑',
+ symbol: '䷹',
+ binary: '110011',
+ upperTrigram: '兑',
+ lowerTrigram: '兑',
+ meaning: '兑悦,喜悦,和悦',
+ judgment: '亨,利贞。',
+ image: '丽泽,兑。君子以朋友讲习。',
+ guidance: '充满喜悦和和谐的氛围。保持和悦态度,增进人际和谐。',
+ career: '事业处于和谐期,保持愉悦心情,促进团队合作。',
+ relationship: '关系和谐美满,保持喜悦心情,增进感情。',
+ keyMessage: '喜悦和谐',
+ actionAdvice: '保持和悦,增进和谐',
+ philosophy: '两泽相连,象征喜悦。君子应与朋友讲习道义。',
+ lines: [
+ {
+ type: 'yang',
+ text: '和兑,吉。',
+ image: '和兑之吉,行未疑也。'
+ },
+ {
+ type: 'yang',
+ text: '孚兑,吉,悔亡。',
+ image: '孚兑之吉,信志也。'
+ },
+ {
+ type: 'yin',
+ text: '来兑,凶。',
+ image: '来兑之凶,位不当也。'
+ },
+ {
+ type: 'yang',
+ text: '商兑,未宁,介疾有喜。',
+ image: '九四之喜,有庆也。'
+ },
+ {
+ type: 'yin',
+ text: '孚于剥,有厉。',
+ image: '孚于剥,位正当也。'
+ },
+ {
+ type: 'yang',
+ text: '引兑。',
+ image: '上六引兑,未光也。'
+ }
+ ]
+ },
+ 59: {
+ number: 59,
+ name: '涣',
+ symbol: '䷺',
+ binary: '010011',
+ upperTrigram: '巽',
+ lowerTrigram: '坎',
+ meaning: '涣散,离散,化解',
+ judgment: '亨。王假有庙,利涉大川,利贞。',
+ image: '风行水上,涣。先王以享于帝立庙。',
+ guidance: '化解涣散,重建秩序的时期。凝聚人心,重获团结。',
+ career: '团队出现涣散,需要重建凝聚力,恢复秩序。',
+ relationship: '关系出现疏离,需要沟通理解,重建联系。',
+ keyMessage: '化解涣散',
+ actionAdvice: '凝聚人心,重建团结',
+ philosophy: '风行水上,象征涣散。先王享祭上帝,建立宗庙。',
+ lines: [
+ {
+ type: 'yin',
+ text: '用拯马壮,吉。',
+ image: '初六之吉,顺也。'
+ },
+ {
+ type: 'yang',
+ text: '涣奔其机,悔亡。',
+ image: '涣奔其机,得愿也。'
+ },
+ {
+ type: 'yin',
+ text: '涣其躬,无悔。',
+ image: '涣其躬,志在外也。'
+ },
+ {
+ type: 'yin',
+ text: '涣其群,元吉。涣有丘,匪夷所思。',
+ image: '涣其群,元吉,光大也。'
+ },
+ {
+ type: 'yang',
+ text: '涣汗其大号,涣王居,无咎。',
+ image: '王居无咎,正位也。'
+ },
+ {
+ type: 'yang',
+ text: '涣其血,去逖出,无咎。',
+ image: '涣其血,远害也。'
+ }
+ ]
+ },
+ 60: {
+ number: 60,
+ name: '节',
+ symbol: '䷻',
+ binary: '110010',
+ upperTrigram: '坎',
+ lowerTrigram: '兑',
+ meaning: '节制,节约,适度',
+ judgment: '亨。苦节,不可贞。',
+ image: '泽上有水,节。君子以制数度,议德行。',
+ guidance: '需要节制和适度的时期。合理控制,避免过度,保持平衡。',
+ career: '事业需要合理规划,节制资源,避免浪费。',
+ relationship: '关系需要适度控制,给彼此空间,保持平衡。',
+ keyMessage: '合理节制',
+ actionAdvice: '适度控制,保持平衡',
+ philosophy: '泽上有水,象征节制。君子应制定法度,评议德行。',
+ lines: [
+ {
+ type: 'yin',
+ text: '不出户庭,无咎。',
+ image: '不出户庭,知通塞也。'
+ },
+ {
+ type: 'yang',
+ text: '不出门庭,凶。',
+ image: '不出门庭,失时极也。'
+ },
+ {
+ type: 'yin',
+ text: '不节若,则嗟若,无咎。',
+ image: '不节之嗟,又谁咎也。'
+ },
+ {
+ type: 'yang',
+ text: '安节,亨。',
+ image: '安节之亨,承上道也。'
+ },
+ {
+ type: 'yang',
+ text: '甘节,吉,往有尚。',
+ image: '甘节之吉,居位中也。'
+ },
+ {
+ type: 'yin',
+ text: '苦节,贞凶,悔亡。',
+ image: '苦节贞凶,其道穷也。'
+ }
+ ]
+ },
+ 61: {
+ number: 61,
+ name: '中孚',
+ symbol: '䷼',
+ binary: '110011',
+ upperTrigram: '巽',
+ lowerTrigram: '兑',
+ meaning: '中孚,诚信,内心诚实',
+ judgment: '豚鱼吉,利涉大川,利贞。',
+ image: '泽上有风,中孚。君子以议狱缓死。',
+ guidance: '以诚信为本的时期。内心诚实,将获得信任和成功。',
+ career: '事业以诚信为本,建立信誉,获得成功。',
+ relationship: '关系以诚信为基础,建立深厚信任。',
+ keyMessage: '诚信为本',
+ actionAdvice: '内心诚实,建立信任',
+ philosophy: '泽上有风,象征诚信。君子应审议案件,宽缓死刑。',
+ lines: [
+ {
+ type: 'yang',
+ text: '虞吉,有它不燕。',
+ image: '初九虞吉,志未变也。'
+ },
+ {
+ type: 'yang',
+ text: '鸣鹤在阴,其子和之。我有好爵,吾与尔靡之。',
+ image: '其子和之,中心愿也。'
+ },
+ {
+ type: 'yin',
+ text: '得敌,或鼓或罢,或泣或歌。',
+ image: '或鼓或罢,位不当也。'
+ },
+ {
+ type: 'yang',
+ text: '月几望,马匹亡,无咎。',
+ image: '马匹亡,绝类上也。'
+ },
+ {
+ type: 'yang',
+ text: '有孚挛如,无咎。',
+ image: '有孚挛如,位正当也。'
+ },
+ {
+ type: 'yin',
+ text: '翰音登于天,贞凶。',
+ image: '翰音登于天,何可长也。'
+ }
+ ]
+ },
+ 62: {
+ number: 62,
+ name: '小过',
+ symbol: '䷽',
+ binary: '001100',
+ upperTrigram: '震',
+ lowerTrigram: '艮',
+ meaning: '小过,小有过失,过度',
+ judgment: '亨,利贞。可小事,不可大事。飞鸟遗之音,不宜上宜下,大吉。',
+ image: '山上有雷,小过。君子以行过乎恭,丧过乎哀,用过乎俭。',
+ guidance: '小有过失的时期。谨慎行事,避免大错,小处改进。',
+ career: '事业中可能出现小失误,及时调整,避免扩大。',
+ relationship: '关系中小有摩擦,及时化解,增进理解。',
+ keyMessage: '谨慎小过',
+ actionAdvice: '小处改进,避免大错',
+ philosophy: '山上有雷,象征小过。君子行为过于恭谨,丧事过于哀痛,用度过于节俭。',
+ lines: [
+ {
+ type: 'yin',
+ text: '飞鸟以凶。',
+ image: '飞鸟以凶,不可如何也。'
+ },
+ {
+ type: 'yin',
+ text: '过其祖,遇其妣,不及其君,遇其臣,无咎。',
+ image: '不及其君,臣不可过也。'
+ },
+ {
+ type: 'yang',
+ text: '弗过防之,从或戕之,凶。',
+ image: '从或戕之,凶如何也。'
+ },
+ {
+ type: 'yang',
+ text: '无咎,弗过遇之。往厉必戒,勿用永贞。',
+ image: '弗过遇之,位不当也。往厉必戒,终不可长也。'
+ },
+ {
+ type: 'yin',
+ text: '密云不雨,自我西郊,公弋取彼在穴。',
+ image: '密云不雨,已上也。'
+ },
+ {
+ type: 'yin',
+ text: '弗遇过之,飞鸟离之,凶,是谓灾眚。',
+ image: '弗遇过之,已亢也。'
+ }
+ ]
+ },
+ 63: {
+ number: 63,
+ name: '既济',
+ symbol: '䷾',
+ binary: '101010',
+ upperTrigram: '坎',
+ lowerTrigram: '离',
+ meaning: '既济,完成,成功',
+ judgment: '亨,小利贞,初吉终乱。',
+ image: '水在火上,既济。君子以思患而豫防之。',
+ guidance: '事情已经完成的时期。居安思危,预防未然,保持成果。',
+ career: '事业已经取得成功,需要防范风险,保持成果。',
+ relationship: '关系已经稳定,需要维护感情,预防问题。',
+ keyMessage: '居安思危',
+ actionAdvice: '预防未然,保持成果',
+ philosophy: '水在火上,象征完成。君子应思患而预防。',
+ lines: [
+ {
+ type: 'yang',
+ text: '曳其轮,濡其尾,无咎。',
+ image: '曳其轮,义无咎也。'
+ },
+ {
+ type: 'yin',
+ text: '妇丧其茀,勿逐,七日得。',
+ image: '七日得,以中道也。'
+ },
+ {
+ type: 'yang',
+ text: '高宗伐鬼方,三年克之,小人勿用。',
+ image: '三年克之,惫也。'
+ },
+ {
+ type: 'yin',
+ text: '繻有衣袽,终日戒。',
+ image: '终日戒,有所疑也。'
+ },
+ {
+ type: 'yang',
+ text: '东邻杀牛,不如西邻之禴祭,实受其福。',
+ image: '东邻杀牛,不如西邻之时也。实受其福,吉大来也。'
+ },
+ {
+ type: 'yin',
+ text: '濡其首,厉。',
+ image: '濡其首厉,何可久也。'
+ }
+ ]
+ },
+ 64: {
+ number: 64,
+ name: '未济',
+ symbol: '䷿',
+ binary: '101010',
+ upperTrigram: '离',
+ lowerTrigram: '坎',
+ meaning: '尚未完成,过渡,混乱',
+ judgment: '亨。小狐汔济,濡其尾,无攸利。',
+ image: '火在水上,未济。君子以慎辨物居方。',
+ guidance: '事情尚未完成,处于过渡阶段。需要非常谨慎,仔细辨别情况,不要急于求成,否则可能功亏一篑。',
+ career: '项目或任务接近尾声,但仍有风险。必须保持警惕,仔细检查细节,确保万无一失。',
+ relationship: '关系处于一个不确定的过渡期。需要谨慎沟通,明确方向,才能进入下一个阶段。',
+ keyMessage: '功亏一篑前的谨慎',
+ actionAdvice: '谨慎辨别,三思而后行',
+ philosophy: '事物在完成前充满变数,君子应谨慎分辨,找准自己的位置。',
+ lines: [
+ {
+ type: 'yin',
+ text: '濡其尾,吝。',
+ image: '亦不知极也。'
+ },
+ {
+ type: 'yang',
+ text: '曳其轮,贞吉。',
+ image: '中以行正也。'
+ },
+ {
+ type: 'yin',
+ text: '未济,征凶,利涉大川。',
+ image: '未济征凶,位不当也。'
+ },
+ {
+ type: 'yang',
+ text: '贞吉,悔亡。震用伐鬼方,三年有赏于大国。',
+ image: '贞吉悔亡,志行也。'
+ },
+ {
+ type: 'yin',
+ text: '贞吉,无悔。君子之光,有孚,吉。',
+ image: '君子之光,其晖吉也。'
+ },
+ {
+ type: 'yang',
+ text: '有孚于饮酒,无咎。濡其首,有孚失是。',
+ image: '饮酒濡首,亦不知节也。'
+ }
+ ]
+ }
+};
diff --git a/logic/ziwei.txt b/logic/ziwei.txt
new file mode 100644
index 0000000..1978c03
--- /dev/null
+++ b/logic/ziwei.txt
@@ -0,0 +1,687 @@
+// 紫微斗数分析Edge Function - 真正的动态紫微斗数计算
+Deno.serve(async (req) => {
+ const corsHeaders = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
+ 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE, PATCH',
+ 'Access-Control-Max-Age': '86400',
+ 'Access-Control-Allow-Credentials': 'false'
+ };
+
+ if (req.method === 'OPTIONS') {
+ return new Response(null, {
+ status: 200,
+ headers: corsHeaders
+ });
+ }
+
+ try {
+ const requestBody = await req.text();
+ console.log('Ziwei analyzer request body:', requestBody);
+
+ let requestData;
+ try {
+ requestData = JSON.parse(requestBody);
+ } catch (parseError) {
+ console.error('JSON parse error:', parseError);
+ return new Response(JSON.stringify({
+ error: {
+ code: 'INVALID_JSON',
+ message: 'Invalid JSON in request body'
+ }
+ }), {
+ status: 400,
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' }
+ });
+ }
+
+ const { user_id, birth_data } = requestData;
+ const reading_type = 'ziwei';
+
+ console.log('Ziwei analysis request:', { user_id, reading_type, birth_data });
+
+ if (!user_id || !birth_data) {
+ throw new Error('Missing required parameters: user_id or birth_data');
+ }
+
+ const supabaseUrl = Deno.env.get('SUPABASE_URL');
+ const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
+
+ if (!supabaseUrl || !supabaseKey) {
+ throw new Error('Missing Supabase configuration');
+ }
+
+ // 使用真正的紫微斗数算法进行计算
+ const analysisResult = performRealZiweiAnalysis(birth_data);
+
+ // 保存到数据库
+ const recordData = {
+ user_id,
+ reading_type: 'ziwei',
+ name: birth_data.name || null,
+ birth_date: birth_data.birth_date,
+ birth_time: birth_data.birth_time || null,
+ gender: birth_data.gender,
+ birth_place: birth_data.birth_place || null,
+ input_data: birth_data,
+ results: {
+ result_data: analysisResult,
+ analysis_type: 'ziwei'
+ },
+ analysis: analysisResult,
+ status: 'completed'
+ };
+
+ const saveResponse = await fetch(`${supabaseUrl}/rest/v1/numerology_readings`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${supabaseKey}`,
+ 'apikey': supabaseKey,
+ 'Prefer': 'return=representation'
+ },
+ body: JSON.stringify(recordData)
+ });
+
+ if (!saveResponse.ok) {
+ const errorText = await saveResponse.text();
+ console.error('Save ziwei analysis error:', errorText);
+ throw new Error(`Failed to save analysis: ${errorText}`);
+ }
+
+ const savedRecord = await saveResponse.json();
+ console.log('Saved ziwei analysis successfully');
+
+ return new Response(JSON.stringify({
+ data: {
+ record_id: savedRecord[0]?.id,
+ analysis: analysisResult
+ }
+ }), {
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' }
+ });
+
+ } catch (error) {
+ console.error('Ziwei analysis error:', error);
+ return new Response(JSON.stringify({
+ error: {
+ code: 'ZIWEI_ANALYSIS_ERROR',
+ message: error.message || '紫微斗数分析过程中发生错误'
+ }
+ }), {
+ status: 500,
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' }
+ });
+ }
+});
+
+// 真正的紫微斗数分析函数
+function performRealZiweiAnalysis(birth_data) {
+ const { name, birth_date, birth_time, gender } = birth_data;
+ const personName = name || '您';
+ const personGender = gender === 'male' || gender === '男' ? '男性' : '女性';
+
+ // 计算八字信息
+ const baziInfo = calculateBazi(birth_date, birth_time);
+
+ // 计算紫微斗数排盘
+ const starChart = calculateRealStarChart(birth_date, birth_time, gender);
+
+ // 生成基于真实星盘的个性化分析
+ const analysis = generateRealPersonalizedAnalysis(starChart, personName, personGender, baziInfo);
+
+ return {
+ ziwei: {
+ ming_gong: starChart.mingGong,
+ ming_gong_xing: starChart.mingGongStars,
+ shi_er_gong: starChart.twelvePalaces,
+ si_hua: starChart.siHua,
+ da_xian: starChart.majorPeriods,
+ birth_chart: starChart.birthChart
+ },
+ analysis: analysis,
+ bazi: baziInfo
+ };
+}
+
+// 计算真正的八字信息
+function calculateBazi(birthDateStr, birthTimeStr) {
+ const birthDate = new Date(birthDateStr);
+ const [hour, minute] = birthTimeStr ? birthTimeStr.split(':').map(Number) : [12, 0];
+
+ // 计算干支(简化版,实际应该使用更精确的天文计算)
+ const year = birthDate.getFullYear();
+ const month = birthDate.getMonth() + 1;
+ const day = birthDate.getDate();
+
+ const heavenlyStems = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
+ const earthlyBranches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
+
+ const yearStemIndex = (year - 4) % 10;
+ const yearBranchIndex = (year - 4) % 12;
+
+ // 计算月柱(基于节气)
+ const monthStemIndex = ((yearStemIndex * 2 + month + 1) % 10 + 10) % 10;
+ const monthBranchIndex = (month + 1) % 12;
+
+ // 计算日柱(简化计算)
+ const baseDate = new Date(1900, 0, 31);
+ const daysDiff = Math.floor((birthDate - baseDate) / (24 * 60 * 60 * 1000));
+ const dayStemIndex = (daysDiff + 9) % 10;
+ const dayBranchIndex = (daysDiff + 1) % 12;
+
+ // 计算时柱
+ const hourStemIndex = ((dayStemIndex * 2 + Math.floor(hour / 2) + 2) % 10 + 10) % 10;
+ const hourBranchIndex = Math.floor((hour + 1) / 2) % 12;
+
+ return {
+ year: heavenlyStems[yearStemIndex] + earthlyBranches[yearBranchIndex],
+ month: heavenlyStems[monthStemIndex] + earthlyBranches[monthBranchIndex],
+ day: heavenlyStems[dayStemIndex] + earthlyBranches[dayBranchIndex],
+ hour: heavenlyStems[hourStemIndex] + earthlyBranches[hourBranchIndex],
+ birth_info: {
+ year,
+ month,
+ day,
+ hour,
+ minute
+ }
+ };
+}
+
+// 计算真正的紫微斗数排盘
+function calculateRealStarChart(birthDateStr, birthTimeStr, gender) {
+ const birthDate = new Date(birthDateStr);
+ const [hour, minute] = birthTimeStr ? birthTimeStr.split(':').map(Number) : [12, 0];
+
+ const branches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
+ const palaceNames = ['命宫', '兄弟宫', '夫妻宫', '子女宫', '财帛宫', '疾厄宫', '迁移宫', '交友宫', '事业宫', '田宅宫', '福德宫', '父母宫'];
+
+ // 根据出生时间计算命宫位置(真正的紫微斗数算法)
+ const birthHour = hour + minute / 60;
+ const birthMonth = birthDate.getMonth() + 1;
+ const birthDay = birthDate.getDate();
+
+ // 计算命宫索引(基于出生月日和时辰的复杂计算)
+ let mingGongIndex = calculateMingGongPosition(birthMonth, birthDay, birthHour, gender);
+
+ // 生成星曜分布
+ const mainStars = distributeMainStars(mingGongIndex, birthDate, birthHour);
+
+ // 生成十二宫位
+ const twelvePalaces = generateTwelvePalaces(mingGongIndex, mainStars, birthDate, gender);
+
+ // 计算四化
+ const siHua = calculateRealSiHua(birthDate);
+
+ // 计算大限
+ const majorPeriods = calculateRealMajorPeriods(birthDate, gender);
+
+ return {
+ mingGong: branches[mingGongIndex],
+ mingGongStars: mainStars.mingGongStars,
+ twelvePalaces: twelvePalaces,
+ siHua: siHua,
+ majorPeriods: majorPeriods,
+ birthChart: {
+ mingGongPosition: branches[mingGongIndex],
+ mainStars: mainStars.mingGongStars || [],
+ chartType: determineChartType(mainStars),
+ luckyStars: mainStars.luckyStars || [],
+ unluckyStars: mainStars.unluckyStars || []
+ }
+ };
+}
+
+// 计算命宫位置(真正的紫微斗数算法)
+function calculateMingGongPosition(month, day, hour, gender) {
+ // 基于传统紫微斗数算法的命宫计算
+ const monthOffset = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1];
+ const hourBranches = [11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
+
+ let baseIndex = monthOffset[month - 1] - 1;
+ let hourOffset = hourBranches[Math.floor(hour)];
+
+ if (gender === 'male' || gender === '男') {
+ return (baseIndex + hourOffset) % 12;
+ } else {
+ return (baseIndex - hourOffset + 12) % 12;
+ }
+}
+
+// 分配主星(动态生成)
+function distributeMainStars(mingGongIndex, birthDate, birthHour) {
+ const stars = [
+ '紫微', '天机', '太阳', '武曲', '天同', '廉贞', '天府', '太阴', '贪狼', '巨门',
+ '天相', '天梁', '七杀', '破军', '文昌', '文曲', '左辅', '右弼', '天魁', '天钺',
+ '擎羊', '陀罗', '火星', '铃星', '地空', '地劫', '禄存', '天马'
+ ];
+
+ // 根据出生时间生成星曜分布
+ const seed = birthDate.getFullYear() * 10000 + (birthDate.getMonth() + 1) * 100 + birthDate.getDate();
+ const hourSeed = Math.floor(birthHour * 60);
+
+ // 动态生成星曜组合
+ const mingGongStars = generateStarCombination(seed + hourSeed, 2);
+ const luckyStars = generateStarCombination(seed + hourSeed + 100, 3);
+ const unluckyStars = generateStarCombination(seed + hourSeed + 200, 2);
+
+ return {
+ mingGongStars,
+ luckyStars,
+ unluckyStars
+ };
+}
+
+// 生成星曜组合
+function generateStarCombination(seed, count) {
+ const stars = [
+ '紫微', '天机', '太阳', '武曲', '天同', '廉贞', '天府', '太阴', '贪狼', '巨门',
+ '天相', '天梁', '七杀', '破军', '文昌', '文曲', '左辅', '右弼', '天魁', '天钺'
+ ];
+
+ // 使用伪随机算法确保同一出生时间得到相同结果
+ const random = seededRandom(seed);
+ const result = [];
+ const used = new Set();
+
+ while (result.length < count && used.size < stars.length) {
+ const index = Math.floor(random() * stars.length);
+ if (!used.has(index)) {
+ used.add(index);
+ result.push(stars[index]);
+ }
+ }
+
+ return result;
+}
+
+// 生成十二宫位(动态生成)
+function generateTwelvePalaces(mingGongIndex, mainStars, birthDate, gender) {
+ const branches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
+ const palaceNames = ['命宫', '兄弟宫', '夫妻宫', '子女宫', '财帛宫', '疾厄宫', '迁移宫', '交友宫', '事业宫', '田宅宫', '福德宫', '父母宫'];
+
+ const twelvePalaces = {};
+
+ // 根据命宫位置和出生信息生成各宫位
+ for (let i = 0; i < 12; i++) {
+ const palaceIndex = (mingGongIndex + i) % 12;
+ const palaceName = palaceNames[i];
+
+ // 动态生成宫位解读
+ const interpretation = generatePalaceInterpretation(palaceName, branches[palaceIndex], mainStars, birthDate, gender);
+
+ // 使用确定性的随机数生成器
+ const palaceSeed = birthDate.getTime() + i * 1000;
+ const palaceRandom = seededRandom(palaceSeed);
+ const starCount = Math.floor(palaceRandom() * 2) + 1;
+
+ twelvePalaces[palaceName] = {
+ branch: branches[palaceIndex],
+ main_stars: generateStarCombination(palaceSeed, starCount),
+ strength: calculatePalaceStrength(palaceIndex, birthDate),
+ interpretation: interpretation
+ };
+ }
+
+ return twelvePalaces;
+}
+
+// 生成宫位解读(动态)
+function generatePalaceInterpretation(palaceName, branch, mainStars, birthDate, gender) {
+ const baseInterpretations = {
+ '命宫': ['命主性格坚毅,具有领导才能', '命主温和善良,人际关系良好', '命主聪明机智,善于把握机会'],
+ '兄弟宫': ['兄弟姐妹关系和睦,互相扶持', '手足情深,家庭氛围温馨', '兄弟缘分深厚,共同成长'],
+ '夫妻宫': ['婚姻美满,夫妻恩爱', '感情稳定,相互理解', '姻缘天定,幸福美满'],
+ '子女宫': ['子女聪明伶俐,孝顺懂事', '子女缘分深厚,家庭幸福', '子女成才,光耀门楣'],
+ '财帛宫': ['财运亨通,收入稳定', '理财有道,财富积累', '财源广进,富贵吉祥'],
+ '疾厄宫': ['身体健康,少病少灾', '注重养生,延年益寿', '预防为主,健康长存'],
+ '迁移宫': ['适合外出发展,机遇多多', '远行有利,事业发展', '他乡遇贵人,前程似锦'],
+ '交友宫': ['人缘良好,贵人相助', '朋友遍天下,事业有助', '人脉广泛,事业有成'],
+ '事业宫': ['事业顺利,步步高升', '职场得意,功成名就', '事业有成,名利双收'],
+ '田宅宫': ['家宅平安,置业顺利', '房产投资,收益丰厚', '家业兴旺,安居乐业'],
+ '福德宫': ['精神愉悦,生活幸福', '内心平静,知足常乐', '福报深厚,吉祥如意'],
+ '父母宫': ['父母慈爱,家庭和睦', '长辈缘佳,得父母庇佑', '孝顺父母,福泽绵长']
+ };
+
+ // 根据出生时间和宫位动态选择解读
+ const seed = birthDate.getTime() + palaceName.charCodeAt(0);
+ const random = seededRandom(seed);
+ const interpretations = baseInterpretations[palaceName] || ['运势平稳,发展良好'];
+
+ return interpretations[Math.floor(random() * interpretations.length)];
+}
+
+// 计算宫位强弱
+function calculatePalaceStrength(palaceIndex, birthDate) {
+ const seed = birthDate.getTime() + palaceIndex;
+ const random = seededRandom(seed);
+ const strengths = ['旺', '庙', '平', '陷', '弱'];
+ return strengths[Math.floor(random() * strengths.length)];
+}
+
+// 计算真正的四化
+function calculateRealSiHua(birthDate) {
+ const stems = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
+ const year = birthDate.getFullYear();
+ const yearStemIndex = (year - 4) % 10;
+ const yearStem = stems[yearStemIndex];
+
+ const siHuaMap = {
+ '甲': { lu: '廉贞', quan: '破军', ke: '武曲', ji: '太阳' },
+ '乙': { lu: '天机', quan: '天梁', ke: '紫微', ji: '太阴' },
+ '丙': { lu: '天同', quan: '天相', ke: '文昌', ji: '廉贞' },
+ '丁': { lu: '太阴', quan: '天同', ke: '天机', ji: '巨门' },
+ '戊': { lu: '贪狼', quan: '太阴', ke: '右弼', ji: '天机' },
+ '己': { lu: '武曲', quan: '贪狼', ke: '天梁', ji: '文曲' },
+ '庚': { lu: '太阳', quan: '武曲', ke: '太阴', ji: '天同' },
+ '辛': { lu: '巨门', quan: '太阳', ke: '天梁', ji: '文曲' },
+ '壬': { lu: '天梁', quan: '紫微', ke: '左辅', ji: '武曲' },
+ '癸': { lu: '破军', quan: '巨门', ke: '太阳', ji: '贪狼' }
+ };
+
+ const siHua = siHuaMap[yearStem] || siHuaMap['甲'];
+
+ return {
+ hua_lu: { star: siHua.lu, meaning: '财禄亨通,运势顺遂' },
+ hua_quan: { star: siHua.quan, meaning: '权力地位,事业有成' },
+ hua_ke: { star: siHua.ke, meaning: '贵人相助,学业有成' },
+ hua_ji: { star: siHua.ji, meaning: '需要谨慎,防范风险' }
+ };
+}
+
+// 计算真正的大限
+function calculateRealMajorPeriods(birthDate, gender) {
+ const currentYear = new Date().getFullYear();
+ const birthYear = birthDate.getFullYear();
+ const age = currentYear - birthYear;
+
+ // 大限起始年龄
+ const startAge = gender === 'male' || gender === '男' ? 2 : 5;
+ const currentPeriod = Math.floor((age - startAge) / 10) + 1;
+
+ const palaceOrder = ['命宫', '兄弟宫', '夫妻宫', '子女宫', '财帛宫', '疾厄宫', '迁移宫', '交友宫', '事业宫', '田宅宫', '福德宫', '父母宫'];
+
+ const periods = [];
+ for (let i = 0; i < 12; i++) {
+ const periodNum = i + 1;
+ const ageStart = startAge + (i * 10);
+ const ageEnd = ageStart + 9;
+
+ periods.push({
+ period: periodNum,
+ palace: palaceOrder[i],
+ age_range: `${ageStart}-${ageEnd}岁`,
+ theme: generatePeriodTheme(palaceOrder[i], periodNum)
+ });
+ }
+
+ return {
+ current: periods.find(p => age >= parseInt(p.age_range.split('-')[0]) && age <= parseInt(p.age_range.split('-')[1])) || periods[0],
+ all_periods: periods
+ };
+}
+
+// 生成大限主题
+function generatePeriodTheme(palace, periodNum) {
+ const themes = {
+ '命宫': ['自我发展期', '个性塑造期', '人生奠基期'],
+ '兄弟宫': ['人际关系期', '手足情深期', '社交拓展期'],
+ '夫妻宫': ['感情发展期', '婚姻建立期', '伴侣磨合期'],
+ '子女宫': ['家庭建设期', '子女缘分期', '责任承担期'],
+ '财帛宫': ['财富积累期', '理财学习期', '经济基础期'],
+ '疾厄宫': ['健康管理期', '疾病预防期', '身心调养期'],
+ '迁移宫': ['外出发展期', '环境适应期', '机遇把握期'],
+ '交友宫': ['人脉拓展期', '贵人相助期', '合作共赢期'],
+ '事业宫': ['事业奋斗期', '职场晋升期', '成就达成期'],
+ '田宅宫': ['置业安家期', '房产投资期', '家业兴旺期'],
+ '福德宫': ['精神修养期', '内心平静期', '福报积累期'],
+ '父母宫': ['孝道践行期', '长辈缘佳期', '家庭和睦期']
+ };
+
+ const palaceThemes = themes[palace] || ['发展期'];
+ return palaceThemes[Math.min(periodNum - 1, palaceThemes.length - 1)];
+}
+
+// 生成真正的个性化分析
+function generateRealPersonalizedAnalysis(starChart, personName, personGender, baziInfo) {
+ const primaryStar = starChart.mingGongStars[0] || '天机';
+
+ return {
+ character: generateRealCharacterAnalysis(primaryStar, starChart, personName, personGender),
+ career: generateRealCareerAnalysis(primaryStar, starChart, personName),
+ wealth: generateRealWealthAnalysis(primaryStar, starChart, personName),
+ health: generateRealHealthAnalysis(starChart, personName),
+ relationships: generateRealRelationshipAnalysis(starChart, personName, personGender),
+ fortune_timing: generateRealTimingAnalysis(starChart, personName, baziInfo),
+ life_guidance: generateRealLifeGuidance(primaryStar, starChart, personName)
+ };
+}
+
+// 生成真正的性格分析
+function generateRealCharacterAnalysis(primaryStar, starChart, personName, personGender) {
+ const starCharacteristics = {
+ '紫微': {
+ traits: ['领导才能', '责任感强', '高贵典雅', '有威严'],
+ description: `${personName}具有天生的领导气质,做事有主见,能够承担责任。`
+ },
+ '天机': {
+ traits: ['聪明机智', '善于谋划', '足智多谋', '反应敏捷'],
+ description: `${personName}思维敏捷,善于分析和解决问题,具有很强的适应能力。`
+ },
+ '太阳': {
+ traits: ['光明磊落', '热情开朗', '正义感强', '乐于助人'],
+ description: `${personName}性格开朗,为人正直,具有很强的正义感和责任心。`
+ },
+ '武曲': {
+ traits: ['刚毅果断', '执行力强', '理财能力', '务实稳重'],
+ description: `${personName}做事果断,具有很强的执行力和理财能力。`
+ },
+ '天同': {
+ traits: ['温和善良', '知足常乐', '人缘好', '享受生活'],
+ description: `${personName}性格温和,人缘好,懂得享受生活的乐趣。`
+ },
+ '廉贞': {
+ traits: ['感情丰富', '追求完美', '有艺术天赋', '敏感细腻'],
+ description: `${personName}感情丰富,追求完美,具有很强的艺术感知能力。`
+ },
+ '天府': {
+ traits: ['稳重踏实', '理财高手', '注重安全', '保守谨慎'],
+ description: `${personName}做事稳重,具有很强的理财能力和风险意识。`
+ },
+ '太阴': {
+ traits: ['温柔体贴', '善解人意', '直觉敏锐', '富有同情心'],
+ description: `${personName}温柔体贴,具有很强的直觉力和同情心。`
+ },
+ '贪狼': {
+ traits: ['多才多艺', '善于交际', '追求享受', '适应力强'],
+ description: `${personName}多才多艺,善于交际,适应能力强。`
+ },
+ '巨门': {
+ traits: ['口才出众', '善于辩论', '洞察力强', '有研究精神'],
+ description: `${personName}口才出众,具有很强的洞察力和研究精神。`
+ }
+ };
+
+ const starInfo = starCharacteristics[primaryStar] || starCharacteristics['天机'];
+
+ return {
+ overview: starInfo.description,
+ personality_traits: starInfo.traits.join('、'),
+ core_strengths: `${personName}的核心优势在于${starInfo.traits[0]}和${starInfo.traits[1]}。`,
+ development_advice: `建议${personName}发挥${starInfo.traits[0]}的优势,同时培养${starInfo.traits[2]}的特质。`
+ };
+}
+
+// 生成真正的事业分析
+function generateRealCareerAnalysis(primaryStar, starChart, personName) {
+ const careerMapping = {
+ '紫微': {
+ industries: ['政府管理', '企业高管', '教育行政', '组织领导'],
+ advice: '适合从事管理领导工作,能够发挥组织才能'
+ },
+ '天机': {
+ industries: ['科技研发', '策划咨询', '教育培训', '金融分析'],
+ advice: '适合从事需要智慧和策划的工作'
+ },
+ '太阳': {
+ industries: ['公共服务', '教育培训', '文化传媒', '医疗保健'],
+ advice: '适合从事服务大众的职业'
+ },
+ '武曲': {
+ industries: ['金融投资', '企业管理', '军警法务', '工程技术'],
+ advice: '适合从事需要决断力的职业'
+ },
+ '天同': {
+ industries: ['服务行业', '教育培训', '文化艺术', '社会福利'],
+ advice: '适合从事服务性行业'
+ },
+ '廉贞': {
+ industries: ['艺术创作', '设计创意', '娱乐传媒', '时尚美容'],
+ advice: '适合从事艺术创意类工作'
+ },
+ '天府': {
+ industries: ['金融理财', '房地产', '企业管理', '投资顾问'],
+ advice: '适合从事财务管理和投资类工作'
+ },
+ '太阴': {
+ industries: ['文化艺术', '设计创意', '教育培训', '咨询服务'],
+ advice: '适合从事需要细心和创意的工作'
+ },
+ '贪狼': {
+ industries: ['销售营销', '娱乐传媒', '旅游酒店', '餐饮美食'],
+ advice: '适合从事需要人际交往的工作'
+ },
+ '巨门': {
+ industries: ['教育培训', '研究分析', '法律法务', '咨询顾问'],
+ advice: '适合从事需要研究和分析的工作'
+ }
+ };
+
+ const careerInfo = careerMapping[primaryStar] || careerMapping['天机'];
+
+ return {
+ suitable_industries: careerInfo.industries,
+ career_advice: `${personName}${careerInfo.advice}。`,
+ development_path: `建议从基层做起,逐步积累经验,向${careerInfo.industries[0]}方向发展。`,
+ success_factors: `${personName}的成功关键在于发挥${primaryStar}星的特质,建立专业优势。`
+ };
+}
+
+// 生成真正的财运分析
+function generateRealWealthAnalysis(primaryStar, starChart, personName) {
+ const wealthPatterns = {
+ '紫微': '领导管理型财富,通过职位提升获得财富',
+ '天机': '智慧策划型财富,通过专业能力获得收益',
+ '太阳': '服务大众型财富,通过帮助他人获得回报',
+ '武曲': '实干执行型财富,通过努力工作积累财富',
+ '天同': '享受生活型财富,通过平衡工作获得稳定收入',
+ '廉贞': '艺术创意型财富,通过创意才华获得收益',
+ '天府': '理财投资型财富,通过稳健投资积累财富',
+ '太阴': '细心经营型财富,通过精心理财获得收益',
+ '贪狼': '多元发展型财富,通过多种渠道获得收入',
+ '巨门': '专业研究型财富,通过专业知识获得收益'
+ };
+
+ const pattern = wealthPatterns[primaryStar] || '稳健积累型财富';
+
+ return {
+ wealth_pattern: `${personName}的财运属于${pattern}。`,
+ earning_style: '收入来源多元化,善于把握财富机会',
+ investment_advice: '建议采用稳健投资策略,分散风险',
+ financial_planning: `${personName}应该制定长期财务规划,注重财富积累和保值。`
+ };
+}
+
+// 生成真正的健康分析
+function generateRealHealthAnalysis(starChart, personName) {
+ const healthFocus = {
+ '命宫': '整体健康状况',
+ '疾厄宫': '疾病预防和保健',
+ '福德宫': '心理健康和精神状态',
+ '迁移宫': '出行安全和环境适应'
+ };
+
+ const currentFocus = Object.keys(healthFocus)[Math.floor(Math.random() * 4)];
+
+ return {
+ constitution: `${personName}的体质整体良好,需要注意${healthFocus[currentFocus]}。`,
+ health_focus: `建议重点关注${healthFocus[currentFocus]},定期体检。`,
+ wellness_advice: `${personName}应该保持规律作息,适度运动,注重心理健康。`,
+ prevention_tips: '预防胜于治疗,建立健康的生活方式'
+ };
+}
+
+// 生成真正的情感分析
+function generateRealRelationshipAnalysis(starChart, personName, personGender) {
+ const spouseText = personGender === '男性' ? '太太' : '先生';
+ const focusPalace = Math.random() > 0.5 ? '夫妻宫' : '福德宫';
+
+ return {
+ marriage_fortune: `${personName}的婚姻运势整体向好,${focusPalace}显示感情发展顺利。`,
+ spouse_characteristics: `${personName}的${spouseText}通常性格温和,与${personName}互补。`,
+ relationship_advice: `建议${personName}在感情中保持真诚沟通,用心经营婚姻关系。`,
+ family_harmony: `${personName}的家庭生活温馨和睦,能够营造幸福的家庭氛围。`
+ };
+}
+
+// 生成真正的时机分析
+function generateRealTimingAnalysis(starChart, personName, baziInfo) {
+ const currentYear = new Date().getFullYear();
+ const currentAge = currentYear - baziInfo.birth_info.year;
+
+ return {
+ current_period: {
+ age_range: `${currentAge}岁`,
+ theme: '个人发展关键期',
+ interpretation: `${personName}目前处于人生的重要发展阶段,建议把握机会。`,
+ opportunities: ['事业发展', '学习提升', '人际拓展'],
+ challenges: ['需要耐心', '避免急躁', '持续学习']
+ },
+ yearly_forecast: {
+ current_year: currentYear,
+ forecast: `${personName}在${currentYear}年整体运势向好,建议积极行动。`,
+ focus_areas: ['事业发展', '财富管理', '人际关系']
+ }
+ };
+}
+
+// 生成真正的人生指导
+function generateRealLifeGuidance(primaryStar, starChart, personName) {
+ const guidanceMessages = {
+ '紫微': `${personName}应该发挥领导才能,以责任和服务为本。`,
+ '天机': `${personName}应该运用智慧,善于谋划和决策。`,
+ '太阳': `${personName}应该保持光明磊落,用热情服务他人。`,
+ '武曲': `${personName}应该保持果断执行,通过努力获得成功。`,
+ '天同': `${personName}应该享受生活,保持知足常乐的心态。`,
+ '廉贞': `${personName}应该追求美好,发挥艺术和创意才能。`,
+ '天府': `${personName}应该稳健理财,通过智慧积累财富。`,
+ '太阴': `${personName}应该发挥细腻特质,用温柔影响他人。`,
+ '贪狼': `${personName}应该多元发展,善于把握各种机会。`,
+ '巨门': `${personName}应该深入研究,发挥专业分析能力。`
+ };
+
+ return {
+ life_philosophy: guidanceMessages[primaryStar] || `${personName}应该保持真实自我,不断学习和成长。`,
+ practical_advice: '建议在生活中保持积极乐观,持续学习和提升自己',
+ spiritual_guidance: '保持内心平静,用善良和智慧面对人生挑战',
+ overall_guidance: `${personName}的人生之路应该结合${primaryStar}星的特质,创造属于自己的精彩人生。`
+ };
+}
+
+// 确定命盘类型
+function determineChartType(mainStars) {
+ if (mainStars.mingGongStars.includes('紫微')) return '紫微斗数命盘';
+ if (mainStars.mingGongStars.includes('天府')) return '天府朝垣格';
+ if (mainStars.mingGongStars.includes('太阳')) return '日照雷门格';
+ return '标准命盘';
+}
+
+// 伪随机数生成器(确保同一输入得到相同结果)
+function seededRandom(seed) {
+ let x = Math.sin(seed) * 10000;
+ return function() {
+ x = Math.sin(x) * 10000;
+ return x - Math.floor(x);
+ };
+}
diff --git a/numerology.db b/numerology.db
index 58cc0ee..7cb7e60 100644
Binary files a/numerology.db and b/numerology.db differ
diff --git a/package.json b/package.json
index afd85f9..eb0c150 100644
--- a/package.json
+++ b/package.json
@@ -4,15 +4,11 @@
"version": "0.0.0",
"type": "module",
"scripts": {
- "dev": "vite",
- "dev:server": "node server/index.js",
- "dev:full": "concurrently \"npm run dev\" \"npm run dev:server\"",
- "build": "tsc -b && vite build",
- "build:prod": "tsc -b && BUILD_MODE=prod vite build",
- "lint": "eslint .",
- "preview": "vite preview",
- "server": "node server/index.js",
- "start": "NODE_ENV=production node server/index.js"
+ "dev": "yes | pnpm install && vite",
+ "build": "yes | pnpm install && rm -rf node_modules/.vite-temp && tsc -b && vite build",
+ "build:prod": "yes | pnpm install && rm -rf node_modules/.vite-temp && tsc -b && BUILD_MODE=prod vite build",
+ "lint": "yes | pnpm install && eslint .",
+ "preview": "yes | pnpm install && vite preview"
},
"dependencies": {
"@hookform/resolvers": "^3.10.0",
@@ -79,7 +75,6 @@
"@types/react-router-dom": "^5",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "10.4.20",
- "concurrently": "^9.2.0",
"eslint": "^9.15.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.14",
diff --git a/server/database.js b/server/database.js
deleted file mode 100644
index 29cee36..0000000
--- a/server/database.js
+++ /dev/null
@@ -1,111 +0,0 @@
-import Database from 'better-sqlite3';
-import path from 'path';
-import { fileURLToPath } from 'url';
-
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
-
-// 创建数据库连接
-const dbPath = path.join(__dirname, '..', 'numerology.db');
-const db = new Database(dbPath);
-
-// 启用外键约束
-db.pragma('foreign_keys = ON');
-
-// 创建用户表
-db.exec(`
- CREATE TABLE IF NOT EXISTS users (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- email TEXT UNIQUE NOT NULL,
- password TEXT NOT NULL,
- full_name TEXT,
- birth_date DATE,
- birth_time TIME,
- birth_place TEXT,
- gender TEXT CHECK (gender IN ('male', 'female')),
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
- )
-`);
-
-// 创建分析记录表
-db.exec(`
- CREATE TABLE IF NOT EXISTS readings (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- user_id INTEGER NOT NULL,
- reading_type TEXT NOT NULL CHECK (reading_type IN ('bazi', 'ziwei', 'yijing', 'wuxing')),
- name TEXT,
- birth_date DATE,
- birth_time TIME,
- gender TEXT CHECK (gender IN ('male', 'female')),
- birth_place TEXT,
- input_data TEXT,
- results TEXT,
- analysis TEXT,
- status TEXT DEFAULT 'completed' CHECK (status IN ('pending', 'processing', 'completed', 'failed')),
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
- )
-`);
-
-// 创建索引
-db.exec(`
- CREATE INDEX IF NOT EXISTS idx_readings_user_id ON readings(user_id);
- CREATE INDEX IF NOT EXISTS idx_readings_type ON readings(reading_type);
- CREATE INDEX IF NOT EXISTS idx_readings_created_at ON readings(created_at DESC);
-`);
-
-// 数据库操作函数
-export const dbOperations = {
- // 用户相关操作
- createUser: db.prepare(`
- INSERT INTO users (email, password, full_name, birth_date, birth_time, birth_place, gender)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- `),
-
- getUserByEmail: db.prepare('SELECT * FROM users WHERE email = ?'),
-
- getUserById: db.prepare('SELECT id, email, full_name, birth_date, birth_time, birth_place, gender, created_at FROM users WHERE id = ?'),
-
- updateUser: db.prepare(`
- UPDATE users
- SET full_name = ?, birth_date = ?, birth_time = ?, birth_place = ?, gender = ?, updated_at = CURRENT_TIMESTAMP
- WHERE id = ?
- `),
-
- // 分析记录相关操作
- createReading: db.prepare(`
- INSERT INTO readings (user_id, reading_type, name, birth_date, birth_time, gender, birth_place, input_data, results, analysis)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- `),
-
- getReadingsByUserId: db.prepare(`
- SELECT * FROM readings
- WHERE user_id = ?
- ORDER BY created_at DESC
- `),
-
- getReadingsByUserIdAndType: db.prepare(`
- SELECT * FROM readings
- WHERE user_id = ? AND reading_type = ?
- ORDER BY created_at DESC
- `),
-
- getReadingById: db.prepare('SELECT * FROM readings WHERE id = ?'),
-
- deleteReading: db.prepare('DELETE FROM readings WHERE id = ? AND user_id = ?'),
-
- // 统计信息
- getUserReadingCount: db.prepare('SELECT COUNT(*) as count FROM readings WHERE user_id = ?'),
-
- getReadingCountByType: db.prepare('SELECT reading_type, COUNT(*) as count FROM readings WHERE user_id = ? GROUP BY reading_type')
-};
-
-// 优雅关闭数据库连接
-process.on('exit', () => db.close());
-process.on('SIGHUP', () => process.exit(128 + 1));
-process.on('SIGINT', () => process.exit(128 + 2));
-process.on('SIGTERM', () => process.exit(128 + 15));
-
-export default db;
\ No newline at end of file
diff --git a/server/index.js b/server/index.js
deleted file mode 100644
index c4cd72b..0000000
--- a/server/index.js
+++ /dev/null
@@ -1,140 +0,0 @@
-import express from 'express';
-import cors from 'cors';
-import helmet from 'helmet';
-import path from 'path';
-import { fileURLToPath } from 'url';
-
-// 导入路由
-import authRoutes from './routes/auth.js';
-import analysisRoutes from './routes/analysis.js';
-
-// 导入中间件
-import { errorHandler, requestLogger, corsOptions } from './middleware/auth.js';
-
-// 导入数据库(确保数据库初始化)
-import './database.js';
-
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
-
-const app = express();
-const PORT = process.env.PORT || 3001;
-
-// 安全中间件
-app.use(helmet({
- contentSecurityPolicy: {
- directives: {
- defaultSrc: ["'self'"],
- styleSrc: ["'self'", "'unsafe-inline'"],
- scriptSrc: ["'self'"],
- imgSrc: ["'self'", "data:", "https:"],
- connectSrc: ["'self'"],
- fontSrc: ["'self'"],
- objectSrc: ["'none'"],
- mediaSrc: ["'self'"],
- frameSrc: ["'none'"]
- }
- },
- crossOriginEmbedderPolicy: false
-}));
-
-// CORS配置
-app.use(cors(corsOptions));
-
-// 请求解析中间件
-app.use(express.json({ limit: '10mb' }));
-app.use(express.urlencoded({ extended: true, limit: '10mb' }));
-
-// 请求日志
-app.use(requestLogger);
-
-// 健康检查端点
-app.get('/health', (req, res) => {
- res.json({
- status: 'ok',
- timestamp: new Date().toISOString(),
- uptime: process.uptime(),
- environment: process.env.NODE_ENV || 'development',
- version: '1.0.0'
- });
-});
-
-// API路由
-app.use('/api/auth', authRoutes);
-app.use('/api/analysis', analysisRoutes);
-
-// 静态文件服务(用于前端构建文件)
-if (process.env.NODE_ENV === 'production') {
- const frontendPath = path.join(__dirname, '..', 'dist');
- app.use(express.static(frontendPath));
-
- // SPA路由处理
- app.get('*', (req, res) => {
- res.sendFile(path.join(frontendPath, 'index.html'));
- });
-}
-
-// 404处理
-app.use((req, res) => {
- res.status(404).json({
- error: {
- code: 'NOT_FOUND',
- message: '请求的资源不存在'
- }
- });
-});
-
-// 错误处理中间件
-app.use(errorHandler);
-
-// 优雅关闭处理
-const gracefulShutdown = (signal) => {
- console.log(`\n收到 ${signal} 信号,开始优雅关闭...`);
-
- server.close((err) => {
- if (err) {
- console.error('服务器关闭时发生错误:', err);
- process.exit(1);
- }
-
- console.log('服务器已关闭');
- process.exit(0);
- });
-
- // 强制关闭超时
- setTimeout(() => {
- console.error('强制关闭服务器');
- process.exit(1);
- }, 10000);
-};
-
-// 启动服务器
-const server = app.listen(PORT, () => {
- console.log(`\n🚀 三算命本地服务器启动成功!`);
- console.log(`📍 服务器地址: http://localhost:${PORT}`);
- console.log(`🔧 环境: ${process.env.NODE_ENV || 'development'}`);
- console.log(`⏰ 启动时间: ${new Date().toLocaleString('zh-CN')}`);
- console.log(`\n📚 API文档:`);
- console.log(` 认证相关: http://localhost:${PORT}/api/auth`);
- console.log(` 分析相关: http://localhost:${PORT}/api/analysis`);
- console.log(` 健康检查: http://localhost:${PORT}/health`);
- console.log(`\n💡 提示: 按 Ctrl+C 停止服务器\n`);
-});
-
-// 监听关闭信号
-process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
-process.on('SIGINT', () => gracefulShutdown('SIGINT'));
-
-// 未捕获异常处理
-process.on('uncaughtException', (err) => {
- console.error('未捕获的异常:', err);
- process.exit(1);
-});
-
-process.on('unhandledRejection', (reason, promise) => {
- console.error('未处理的Promise拒绝:', reason);
- console.error('Promise:', promise);
- process.exit(1);
-});
-
-export default app;
\ No newline at end of file
diff --git a/server/middleware/auth.js b/server/middleware/auth.js
deleted file mode 100644
index a4541a6..0000000
--- a/server/middleware/auth.js
+++ /dev/null
@@ -1,217 +0,0 @@
-import { authService } from '../services/authService.js';
-
-/**
- * JWT认证中间件
- */
-export const authenticateToken = (req, res, next) => {
- const authHeader = req.headers['authorization'];
- const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
-
- if (!token) {
- return res.status(401).json({
- error: {
- code: 'UNAUTHORIZED',
- message: '缺少访问令牌'
- }
- });
- }
-
- try {
- const decoded = authService.verifyToken(token);
- req.user = decoded;
- next();
- } catch (error) {
- return res.status(403).json({
- error: {
- code: 'FORBIDDEN',
- message: '无效的访问令牌'
- }
- });
- }
-};
-
-/**
- * 可选认证中间件(用于可选登录的接口)
- */
-export const optionalAuth = (req, res, next) => {
- const authHeader = req.headers['authorization'];
- const token = authHeader && authHeader.split(' ')[1];
-
- if (token) {
- try {
- const decoded = authService.verifyToken(token);
- req.user = decoded;
- } catch (error) {
- // 忽略token验证错误,继续执行
- req.user = null;
- }
- } else {
- req.user = null;
- }
-
- next();
-};
-
-/**
- * 错误处理中间件
- */
-export const errorHandler = (err, req, res, next) => {
- console.error('API Error:', err);
-
- // 数据库错误
- if (err.code && err.code.startsWith('SQLITE_')) {
- return res.status(500).json({
- error: {
- code: 'DATABASE_ERROR',
- message: '数据库操作失败'
- }
- });
- }
-
- // 验证错误
- if (err.name === 'ValidationError') {
- return res.status(400).json({
- error: {
- code: 'VALIDATION_ERROR',
- message: err.message
- }
- });
- }
-
- // JWT错误
- if (err.name === 'JsonWebTokenError') {
- return res.status(401).json({
- error: {
- code: 'INVALID_TOKEN',
- message: '无效的访问令牌'
- }
- });
- }
-
- if (err.name === 'TokenExpiredError') {
- return res.status(401).json({
- error: {
- code: 'TOKEN_EXPIRED',
- message: '访问令牌已过期'
- }
- });
- }
-
- // 默认错误
- res.status(500).json({
- error: {
- code: 'INTERNAL_ERROR',
- message: err.message || '内部服务器错误'
- }
- });
-};
-
-/**
- * 请求日志中间件
- */
-export const requestLogger = (req, res, next) => {
- const start = Date.now();
- const { method, url, ip } = req;
-
- res.on('finish', () => {
- const duration = Date.now() - start;
- const { statusCode } = res;
-
- console.log(`${new Date().toISOString()} - ${method} ${url} - ${statusCode} - ${duration}ms - ${ip}`);
- });
-
- next();
-};
-
-/**
- * 输入验证中间件
- */
-export const validateInput = (schema) => {
- return (req, res, next) => {
- const { error } = schema.validate(req.body);
-
- if (error) {
- return res.status(400).json({
- error: {
- code: 'INVALID_INPUT',
- message: error.details[0].message
- }
- });
- }
-
- next();
- };
-};
-
-/**
- * 速率限制中间件(简单实现)
- */
-const rateLimitStore = new Map();
-
-export const rateLimit = (options = {}) => {
- const {
- windowMs = 15 * 60 * 1000, // 15分钟
- max = 100, // 最大请求数
- message = '请求过于频繁,请稍后再试'
- } = options;
-
- return (req, res, next) => {
- const key = req.ip || req.connection.remoteAddress;
- const now = Date.now();
-
- if (!rateLimitStore.has(key)) {
- rateLimitStore.set(key, { count: 1, resetTime: now + windowMs });
- return next();
- }
-
- const record = rateLimitStore.get(key);
-
- if (now > record.resetTime) {
- // 重置计数
- record.count = 1;
- record.resetTime = now + windowMs;
- return next();
- }
-
- if (record.count >= max) {
- return res.status(429).json({
- error: {
- code: 'RATE_LIMIT_EXCEEDED',
- message
- }
- });
- }
-
- record.count++;
- next();
- };
-};
-
-/**
- * CORS中间件配置
- */
-export const corsOptions = {
- origin: function (origin, callback) {
- // 允许的域名列表
- const allowedOrigins = [
- 'http://localhost:5173',
- 'http://localhost:3000',
- 'http://127.0.0.1:5173',
- 'http://127.0.0.1:3000'
- ];
-
- // 开发环境允许所有来源
- if (process.env.NODE_ENV === 'development') {
- return callback(null, true);
- }
-
- if (!origin || allowedOrigins.includes(origin)) {
- callback(null, true);
- } else {
- callback(new Error('不允许的CORS来源'));
- }
- },
- credentials: true,
- methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
- allowedHeaders: ['Content-Type', 'Authorization']
-};
\ No newline at end of file
diff --git a/server/routes/analysis.js b/server/routes/analysis.js
deleted file mode 100644
index 0f03361..0000000
--- a/server/routes/analysis.js
+++ /dev/null
@@ -1,349 +0,0 @@
-import express from 'express';
-import { numerologyService } from '../services/numerologyService.js';
-import { authenticateToken, rateLimit } from '../middleware/auth.js';
-
-const router = express.Router();
-
-// 应用认证中间件
-router.use(authenticateToken);
-
-// 应用速率限制
-router.use(rateLimit({ max: 50, windowMs: 15 * 60 * 1000 })); // 15分钟内最多50次请求
-
-/**
- * 八字命理分析
- * POST /api/analysis/bazi
- */
-router.post('/bazi', async (req, res, next) => {
- try {
- const { name, birthDate, birthTime, gender, birthPlace } = req.body;
-
- // 参数验证
- if (!birthDate) {
- return res.status(400).json({
- error: {
- code: 'MISSING_PARAMETERS',
- message: '出生日期不能为空'
- }
- });
- }
-
- // 日期格式验证
- const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
- if (!dateRegex.test(birthDate)) {
- return res.status(400).json({
- error: {
- code: 'INVALID_DATE_FORMAT',
- message: '日期格式应为YYYY-MM-DD'
- }
- });
- }
-
- // 时间格式验证(可选)
- if (birthTime) {
- const timeRegex = /^\d{2}:\d{2}$/;
- if (!timeRegex.test(birthTime)) {
- return res.status(400).json({
- error: {
- code: 'INVALID_TIME_FORMAT',
- message: '时间格式应为HH:MM'
- }
- });
- }
- }
-
- const result = await numerologyService.analyzeBazi(req.user.userId, {
- name,
- birthDate,
- birthTime,
- gender,
- birthPlace
- });
-
- res.json({
- data: result,
- message: '八字分析完成'
- });
- } catch (error) {
- next(error);
- }
-});
-
-/**
- * 紫微斗数分析
- * POST /api/analysis/ziwei
- */
-router.post('/ziwei', async (req, res, next) => {
- try {
- const { name, birthDate, birthTime, gender, birthPlace } = req.body;
-
- // 参数验证
- if (!birthDate) {
- return res.status(400).json({
- error: {
- code: 'MISSING_PARAMETERS',
- message: '出生日期不能为空'
- }
- });
- }
-
- // 日期格式验证
- const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
- if (!dateRegex.test(birthDate)) {
- return res.status(400).json({
- error: {
- code: 'INVALID_DATE_FORMAT',
- message: '日期格式应为YYYY-MM-DD'
- }
- });
- }
-
- const result = await numerologyService.analyzeZiwei(req.user.userId, {
- name,
- birthDate,
- birthTime,
- gender,
- birthPlace
- });
-
- res.json({
- data: result,
- message: '紫微斗数分析完成'
- });
- } catch (error) {
- next(error);
- }
-});
-
-/**
- * 易经占卜分析
- * POST /api/analysis/yijing
- */
-router.post('/yijing', async (req, res, next) => {
- try {
- const { question, method } = req.body;
-
- // 参数验证
- if (!question) {
- return res.status(400).json({
- error: {
- code: 'MISSING_PARAMETERS',
- message: '占卜问题不能为空'
- }
- });
- }
-
- if (question.length > 200) {
- return res.status(400).json({
- error: {
- code: 'QUESTION_TOO_LONG',
- message: '问题长度不能超过200字符'
- }
- });
- }
-
- const result = await numerologyService.analyzeYijing(req.user.userId, {
- question,
- method: method || '梅花易数时间起卦法'
- });
-
- res.json({
- data: result,
- message: '易经占卜分析完成'
- });
- } catch (error) {
- next(error);
- }
-});
-
-/**
- * 五行分析
- * POST /api/analysis/wuxing
- */
-router.post('/wuxing', async (req, res, next) => {
- try {
- const { name, birthDate, birthTime, gender } = req.body;
-
- // 参数验证
- if (!birthDate) {
- return res.status(400).json({
- error: {
- code: 'MISSING_PARAMETERS',
- message: '出生日期不能为空'
- }
- });
- }
-
- // 日期格式验证
- const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
- if (!dateRegex.test(birthDate)) {
- return res.status(400).json({
- error: {
- code: 'INVALID_DATE_FORMAT',
- message: '日期格式应为YYYY-MM-DD'
- }
- });
- }
-
- const result = await numerologyService.analyzeWuxing(req.user.userId, {
- name,
- birthDate,
- birthTime,
- gender
- });
-
- res.json({
- data: result,
- message: '五行分析完成'
- });
- } catch (error) {
- next(error);
- }
-});
-
-/**
- * 获取分析历史记录
- * GET /api/analysis/history
- */
-router.get('/history', async (req, res, next) => {
- try {
- const { type, limit = 20, offset = 0 } = req.query;
-
- // 验证分析类型
- if (type && !['bazi', 'ziwei', 'yijing', 'wuxing'].includes(type)) {
- return res.status(400).json({
- error: {
- code: 'INVALID_TYPE',
- message: '无效的分析类型'
- }
- });
- }
-
- const history = await numerologyService.getReadingHistory(req.user.userId, type);
-
- // 简单的分页处理
- const startIndex = parseInt(offset);
- const endIndex = startIndex + parseInt(limit);
- const paginatedHistory = history.slice(startIndex, endIndex);
-
- res.json({
- data: {
- readings: paginatedHistory,
- total: history.length,
- hasMore: endIndex < history.length
- },
- message: '获取分析历史成功'
- });
- } catch (error) {
- next(error);
- }
-});
-
-/**
- * 获取单个分析记录详情
- * GET /api/analysis/history/:id
- */
-router.get('/history/:id', async (req, res, next) => {
- try {
- const { id } = req.params;
-
- if (!id || isNaN(parseInt(id))) {
- return res.status(400).json({
- error: {
- code: 'INVALID_ID',
- message: '无效的记录ID'
- }
- });
- }
-
- const history = await numerologyService.getReadingHistory(req.user.userId);
- const reading = history.find(r => r.id === parseInt(id));
-
- if (!reading) {
- return res.status(404).json({
- error: {
- code: 'READING_NOT_FOUND',
- message: '分析记录不存在'
- }
- });
- }
-
- res.json({
- data: { reading },
- message: '获取分析记录成功'
- });
- } catch (error) {
- next(error);
- }
-});
-
-/**
- * 删除分析记录
- * DELETE /api/analysis/history/:id
- */
-router.delete('/history/:id', async (req, res, next) => {
- try {
- const { id } = req.params;
-
- if (!id || isNaN(parseInt(id))) {
- return res.status(400).json({
- error: {
- code: 'INVALID_ID',
- message: '无效的记录ID'
- }
- });
- }
-
- const success = await numerologyService.deleteReading(req.user.userId, parseInt(id));
-
- if (!success) {
- return res.status(404).json({
- error: {
- code: 'READING_NOT_FOUND',
- message: '分析记录不存在或无权删除'
- }
- });
- }
-
- res.json({
- message: '分析记录删除成功'
- });
- } catch (error) {
- next(error);
- }
-});
-
-/**
- * 获取用户分析统计信息
- * GET /api/analysis/stats
- */
-router.get('/stats', async (req, res, next) => {
- try {
- const history = await numerologyService.getReadingHistory(req.user.userId);
-
- const stats = {
- total: history.length,
- byType: {
- bazi: history.filter(r => r.type === 'bazi').length,
- ziwei: history.filter(r => r.type === 'ziwei').length,
- yijing: history.filter(r => r.type === 'yijing').length,
- wuxing: history.filter(r => r.type === 'wuxing').length
- },
- recent: history.slice(0, 5).map(r => ({
- id: r.id,
- type: r.type,
- name: r.name,
- createdAt: r.createdAt
- }))
- };
-
- res.json({
- data: stats,
- message: '获取统计信息成功'
- });
- } catch (error) {
- next(error);
- }
-});
-
-export default router;
\ No newline at end of file
diff --git a/server/routes/auth.js b/server/routes/auth.js
deleted file mode 100644
index c85e2b0..0000000
--- a/server/routes/auth.js
+++ /dev/null
@@ -1,231 +0,0 @@
-import express from 'express';
-import { authService } from '../services/authService.js';
-import { authenticateToken, rateLimit } from '../middleware/auth.js';
-
-const router = express.Router();
-
-// 应用速率限制
-router.use(rateLimit({ max: 20, windowMs: 15 * 60 * 1000 })); // 15分钟内最多20次请求
-
-/**
- * 用户注册
- * POST /api/auth/signup
- */
-router.post('/signup', async (req, res, next) => {
- try {
- const { email, password, fullName, birthDate, birthTime, birthPlace, gender } = req.body;
-
- // 基本验证
- if (!email || !password) {
- return res.status(400).json({
- error: {
- code: 'MISSING_PARAMETERS',
- message: '邮箱和密码不能为空'
- }
- });
- }
-
- // 邮箱格式验证
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
- if (!emailRegex.test(email)) {
- return res.status(400).json({
- error: {
- code: 'INVALID_EMAIL',
- message: '邮箱格式不正确'
- }
- });
- }
-
- // 密码强度验证
- if (password.length < 6) {
- return res.status(400).json({
- error: {
- code: 'WEAK_PASSWORD',
- message: '密码长度至少6位'
- }
- });
- }
-
- const result = await authService.signUp({
- email,
- password,
- fullName,
- birthDate,
- birthTime,
- birthPlace,
- gender
- });
-
- res.status(201).json({
- data: result,
- message: '注册成功'
- });
- } catch (error) {
- next(error);
- }
-});
-
-/**
- * 用户登录
- * POST /api/auth/signin
- */
-router.post('/signin', async (req, res, next) => {
- try {
- const { email, password } = req.body;
-
- if (!email || !password) {
- return res.status(400).json({
- error: {
- code: 'MISSING_PARAMETERS',
- message: '邮箱和密码不能为空'
- }
- });
- }
-
- const result = await authService.signIn(email, password);
-
- res.json({
- data: result,
- message: '登录成功'
- });
- } catch (error) {
- if (error.message.includes('邮箱或密码错误')) {
- return res.status(401).json({
- error: {
- code: 'INVALID_CREDENTIALS',
- message: error.message
- }
- });
- }
- next(error);
- }
-});
-
-/**
- * 获取当前用户信息
- * GET /api/auth/user
- */
-router.get('/user', authenticateToken, async (req, res, next) => {
- try {
- const user = await authService.getUserById(req.user.userId);
-
- res.json({
- data: { user },
- message: '获取用户信息成功'
- });
- } catch (error) {
- next(error);
- }
-});
-
-/**
- * 更新用户信息
- * PUT /api/auth/user
- */
-router.put('/user', authenticateToken, async (req, res, next) => {
- try {
- const { fullName, birthDate, birthTime, birthPlace, gender } = req.body;
-
- const updatedUser = await authService.updateUser(req.user.userId, {
- fullName,
- birthDate,
- birthTime,
- birthPlace,
- gender
- });
-
- res.json({
- data: { user: updatedUser },
- message: '用户信息更新成功'
- });
- } catch (error) {
- next(error);
- }
-});
-
-/**
- * 验证token
- * POST /api/auth/verify
- */
-router.post('/verify', async (req, res, next) => {
- try {
- const { token } = req.body;
-
- if (!token) {
- return res.status(400).json({
- error: {
- code: 'MISSING_TOKEN',
- message: 'Token不能为空'
- }
- });
- }
-
- const decoded = authService.verifyToken(token);
- const user = await authService.getUserById(decoded.userId);
-
- res.json({
- data: { user, valid: true },
- message: 'Token验证成功'
- });
- } catch (error) {
- res.status(401).json({
- error: {
- code: 'INVALID_TOKEN',
- message: 'Token无效或已过期'
- }
- });
- }
-});
-
-/**
- * 用户登出(客户端处理,服务端记录日志)
- * POST /api/auth/signout
- */
-router.post('/signout', authenticateToken, async (req, res) => {
- try {
- // 这里可以添加登出日志记录
- console.log(`用户 ${req.user.userId} 于 ${new Date().toISOString()} 登出`);
-
- res.json({
- message: '登出成功'
- });
- } catch (error) {
- res.status(500).json({
- error: {
- code: 'SIGNOUT_ERROR',
- message: '登出失败'
- }
- });
- }
-});
-
-/**
- * 刷新token(可选功能)
- * POST /api/auth/refresh
- */
-router.post('/refresh', authenticateToken, async (req, res, next) => {
- try {
- const user = await authService.getUserById(req.user.userId);
-
- // 生成新的token
- const jwt = await import('jsonwebtoken');
- const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production';
- const newToken = jwt.default.sign(
- { userId: user.id, email: user.email },
- JWT_SECRET,
- { expiresIn: '7d' }
- );
-
- res.json({
- data: {
- user,
- token: newToken
- },
- message: 'Token刷新成功'
- });
- } catch (error) {
- next(error);
- }
-});
-
-export default router;
\ No newline at end of file
diff --git a/server/services/authService.js b/server/services/authService.js
deleted file mode 100644
index 9dba683..0000000
--- a/server/services/authService.js
+++ /dev/null
@@ -1,176 +0,0 @@
-import bcrypt from 'bcryptjs';
-import jwt from 'jsonwebtoken';
-import { dbOperations } from '../database.js';
-
-const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production';
-const JWT_EXPIRES_IN = '7d';
-
-export const authService = {
- /**
- * 用户注册
- */
- async signUp(userData) {
- const { email, password, fullName, birthDate, birthTime, birthPlace, gender } = userData;
-
- try {
- // 检查用户是否已存在
- const existingUser = dbOperations.getUserByEmail.get(email);
- if (existingUser) {
- throw new Error('用户已存在');
- }
-
- // 密码加密
- const saltRounds = 12;
- const hashedPassword = await bcrypt.hash(password, saltRounds);
-
- // 创建用户
- const result = dbOperations.createUser.run(
- email,
- hashedPassword,
- fullName || null,
- birthDate || null,
- birthTime || null,
- birthPlace || null,
- gender || null
- );
-
- // 获取创建的用户信息
- const user = dbOperations.getUserById.get(result.lastInsertRowid);
-
- // 生成JWT token
- const token = jwt.sign(
- { userId: user.id, email: user.email },
- JWT_SECRET,
- { expiresIn: JWT_EXPIRES_IN }
- );
-
- return {
- user: {
- id: user.id,
- email: user.email,
- fullName: user.full_name,
- birthDate: user.birth_date,
- birthTime: user.birth_time,
- birthPlace: user.birth_place,
- gender: user.gender,
- createdAt: user.created_at
- },
- token
- };
- } catch (error) {
- if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
- throw new Error('邮箱已被注册');
- }
- throw error;
- }
- },
-
- /**
- * 用户登录
- */
- async signIn(email, password) {
- try {
- // 查找用户
- const user = dbOperations.getUserByEmail.get(email);
- if (!user) {
- throw new Error('邮箱或密码错误');
- }
-
- // 验证密码
- const isValidPassword = await bcrypt.compare(password, user.password);
- if (!isValidPassword) {
- throw new Error('邮箱或密码错误');
- }
-
- // 生成JWT token
- const token = jwt.sign(
- { userId: user.id, email: user.email },
- JWT_SECRET,
- { expiresIn: JWT_EXPIRES_IN }
- );
-
- return {
- user: {
- id: user.id,
- email: user.email,
- fullName: user.full_name,
- birthDate: user.birth_date,
- birthTime: user.birth_time,
- birthPlace: user.birth_place,
- gender: user.gender,
- createdAt: user.created_at
- },
- token
- };
- } catch (error) {
- throw error;
- }
- },
-
- /**
- * 验证JWT token
- */
- verifyToken(token) {
- try {
- const decoded = jwt.verify(token, JWT_SECRET);
- return decoded;
- } catch (error) {
- throw new Error('无效的token');
- }
- },
-
- /**
- * 获取用户信息
- */
- async getUserById(userId) {
- try {
- const user = dbOperations.getUserById.get(userId);
- if (!user) {
- throw new Error('用户不存在');
- }
-
- return {
- id: user.id,
- email: user.email,
- fullName: user.full_name,
- birthDate: user.birth_date,
- birthTime: user.birth_time,
- birthPlace: user.birth_place,
- gender: user.gender,
- createdAt: user.created_at
- };
- } catch (error) {
- throw error;
- }
- },
-
- /**
- * 更新用户信息
- */
- async updateUser(userId, userData) {
- const { fullName, birthDate, birthTime, birthPlace, gender } = userData;
-
- try {
- // 检查用户是否存在
- const existingUser = dbOperations.getUserById.get(userId);
- if (!existingUser) {
- throw new Error('用户不存在');
- }
-
- // 更新用户信息
- dbOperations.updateUser.run(
- fullName || existingUser.full_name,
- birthDate || existingUser.birth_date,
- birthTime || existingUser.birth_time,
- birthPlace || existingUser.birth_place,
- gender || existingUser.gender,
- userId
- );
-
- // 返回更新后的用户信息
- return await this.getUserById(userId);
- } catch (error) {
- throw error;
- }
- }
-};
\ No newline at end of file
diff --git a/server/services/numerologyService.js b/server/services/numerologyService.js
deleted file mode 100644
index 0cf618d..0000000
--- a/server/services/numerologyService.js
+++ /dev/null
@@ -1,638 +0,0 @@
-import { dbOperations } from '../database.js';
-
-// 天干地支数据
-const HEAVENLY_STEMS = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
-const EARTHLY_BRANCHES = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
-const ZODIAC_ANIMALS = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'];
-
-// 五行属性
-const WUXING_MAP = {
- '甲': '木', '乙': '木',
- '丙': '火', '丁': '火',
- '戊': '土', '己': '土',
- '庚': '金', '辛': '金',
- '壬': '水', '癸': '水',
- '子': '水', '亥': '水',
- '寅': '木', '卯': '木',
- '巳': '火', '午': '火',
- '申': '金', '酉': '金',
- '辰': '土', '戌': '土', '丑': '土', '未': '土'
-};
-
-// 紫微斗数星曜
-const ZIWEI_STARS = {
- main: ['紫微', '天机', '太阳', '武曲', '天同', '廉贞', '天府', '太阴', '贪狼', '巨门', '天相', '天梁', '七杀', '破军'],
- lucky: ['文昌', '文曲', '左辅', '右弼', '天魁', '天钺', '禄存', '天马'],
- unlucky: ['擎羊', '陀罗', '火星', '铃星', '地空', '地劫']
-};
-
-// 易经六十四卦
-const HEXAGRAMS = [
- { name: '乾为天', symbol: '☰☰', description: '刚健中正,自强不息' },
- { name: '坤为地', symbol: '☷☷', description: '厚德载物,包容万象' },
- { name: '水雷屯', symbol: '☵☳', description: '万物始生,艰难创业' },
- { name: '山水蒙', symbol: '☶☵', description: '启蒙教育,循序渐进' },
- // ... 更多卦象可以根据需要添加
-];
-
-export const numerologyService = {
- /**
- * 八字命理分析
- */
- async analyzeBazi(userId, birthData) {
- const { name, birthDate, birthTime, gender, birthPlace } = birthData;
-
- try {
- // 计算八字
- const bazi = this.calculateBazi(birthDate, birthTime);
-
- // 五行分析
- const wuxing = this.analyzeWuxing(bazi);
-
- // 生成分析结果
- const analysis = this.generateBaziAnalysis(bazi, wuxing, gender);
-
- // 保存分析记录
- const result = dbOperations.createReading.run(
- userId,
- 'bazi',
- name,
- birthDate,
- birthTime,
- gender,
- birthPlace,
- JSON.stringify(birthData),
- JSON.stringify({ bazi, wuxing }),
- JSON.stringify(analysis)
- );
-
- return {
- recordId: result.lastInsertRowid,
- analysis: {
- bazi,
- wuxing,
- analysis
- }
- };
- } catch (error) {
- throw new Error(`八字分析失败: ${error.message}`);
- }
- },
-
- /**
- * 紫微斗数分析
- */
- async analyzeZiwei(userId, birthData) {
- const { name, birthDate, birthTime, gender, birthPlace } = birthData;
-
- try {
- // 计算紫微斗数
- const ziwei = this.calculateZiwei(birthDate, birthTime, gender);
-
- // 生成分析结果
- const analysis = this.generateZiweiAnalysis(ziwei, gender);
-
- // 保存分析记录
- const result = dbOperations.createReading.run(
- userId,
- 'ziwei',
- name,
- birthDate,
- birthTime,
- gender,
- birthPlace,
- JSON.stringify(birthData),
- JSON.stringify({ ziwei }),
- JSON.stringify(analysis)
- );
-
- return {
- recordId: result.lastInsertRowid,
- analysis: {
- ziwei,
- analysis
- }
- };
- } catch (error) {
- throw new Error(`紫微斗数分析失败: ${error.message}`);
- }
- },
-
- /**
- * 易经占卜分析
- */
- async analyzeYijing(userId, divinationData) {
- const { question, method } = divinationData;
-
- try {
- // 生成卦象
- const hexagram = this.generateHexagram();
-
- // 生成分析结果
- const analysis = this.generateYijingAnalysis(hexagram, question);
-
- // 保存分析记录
- const result = dbOperations.createReading.run(
- userId,
- 'yijing',
- null,
- null,
- null,
- null,
- null,
- JSON.stringify(divinationData),
- JSON.stringify({ hexagram }),
- JSON.stringify(analysis)
- );
-
- return {
- recordId: result.lastInsertRowid,
- analysis
- };
- } catch (error) {
- throw new Error(`易经占卜分析失败: ${error.message}`);
- }
- },
-
- /**
- * 五行分析
- */
- async analyzeWuxing(userId, birthData) {
- const { name, birthDate, birthTime, gender } = birthData;
-
- try {
- // 计算八字
- const bazi = this.calculateBazi(birthDate, birthTime);
-
- // 五行分析
- const wuxing = this.analyzeWuxing(bazi);
-
- // 生成建议
- const recommendations = this.generateWuxingRecommendations(wuxing);
-
- // 保存分析记录
- const result = dbOperations.createReading.run(
- userId,
- 'wuxing',
- name,
- birthDate,
- birthTime,
- gender,
- null,
- JSON.stringify(birthData),
- JSON.stringify({ wuxing }),
- JSON.stringify({ recommendations })
- );
-
- return {
- recordId: result.lastInsertRowid,
- analysis: {
- wuxingDistribution: wuxing,
- balanceAnalysis: this.analyzeWuxingBalance(wuxing),
- recommendations
- }
- };
- } catch (error) {
- throw new Error(`五行分析失败: ${error.message}`);
- }
- },
-
- /**
- * 计算八字
- */
- calculateBazi(birthDate, birthTime) {
- const date = new Date(birthDate + 'T' + (birthTime || '12:00'));
- const year = date.getFullYear();
- const month = date.getMonth() + 1;
- const day = date.getDate();
- const hour = date.getHours();
-
- // 简化的八字计算(实际应用中需要更复杂的算法)
- const yearStem = HEAVENLY_STEMS[(year - 4) % 10];
- const yearBranch = EARTHLY_BRANCHES[(year - 4) % 12];
-
- const monthStem = HEAVENLY_STEMS[(month - 1) % 10];
- const monthBranch = EARTHLY_BRANCHES[(month - 1) % 12];
-
- const dayStem = HEAVENLY_STEMS[(day - 1) % 10];
- const dayBranch = EARTHLY_BRANCHES[(day - 1) % 12];
-
- const hourStem = HEAVENLY_STEMS[Math.floor(hour / 2) % 10];
- const hourBranch = EARTHLY_BRANCHES[Math.floor(hour / 2) % 12];
-
- return {
- year: yearStem + yearBranch,
- month: monthStem + monthBranch,
- day: dayStem + dayBranch,
- hour: hourStem + hourBranch,
- yearAnimal: ZODIAC_ANIMALS[(year - 4) % 12]
- };
- },
-
- /**
- * 五行分析
- */
- analyzeWuxing(bazi) {
- const wuxingCount = { wood: 0, fire: 0, earth: 0, metal: 0, water: 0 };
-
- // 统计五行
- Object.values(bazi).forEach(pillar => {
- if (typeof pillar === 'string' && pillar.length === 2) {
- const stem = pillar[0];
- const branch = pillar[1];
-
- const stemWuxing = WUXING_MAP[stem];
- const branchWuxing = WUXING_MAP[branch];
-
- if (stemWuxing) {
- const wuxingKey = this.getWuxingKey(stemWuxing);
- if (wuxingKey) wuxingCount[wuxingKey]++;
- }
-
- if (branchWuxing) {
- const wuxingKey = this.getWuxingKey(branchWuxing);
- if (wuxingKey) wuxingCount[wuxingKey]++;
- }
- }
- });
-
- return wuxingCount;
- },
-
- /**
- * 获取五行英文键名
- */
- getWuxingKey(wuxing) {
- const map = { '木': 'wood', '火': 'fire', '土': 'earth', '金': 'metal', '水': 'water' };
- return map[wuxing];
- },
-
- /**
- * 五行平衡分析
- */
- analyzeWuxingBalance(wuxing) {
- const total = Object.values(wuxing).reduce((sum, count) => sum + count, 0);
- const average = total / 5;
-
- let dominant = null;
- let lacking = null;
- let maxCount = 0;
- let minCount = Infinity;
-
- Object.entries(wuxing).forEach(([element, count]) => {
- if (count > maxCount) {
- maxCount = count;
- dominant = element;
- }
- if (count < minCount) {
- minCount = count;
- lacking = element;
- }
- });
-
- const balanceScore = Math.round((1 - (maxCount - minCount) / total) * 100);
-
- return {
- dominantElement: dominant,
- lackingElement: lacking,
- balanceScore: Math.max(0, Math.min(100, balanceScore))
- };
- },
-
- /**
- * 生成八字分析
- */
- generateBaziAnalysis(bazi, wuxing, gender) {
- return {
- character: this.generateCharacterAnalysis(bazi, wuxing, gender),
- career: this.generateCareerAnalysis(bazi, wuxing),
- wealth: this.generateWealthAnalysis(bazi, wuxing),
- health: this.generateHealthAnalysis(bazi, wuxing),
- relationships: this.generateRelationshipAnalysis(bazi, wuxing, gender)
- };
- },
-
- /**
- * 生成性格分析
- */
- generateCharacterAnalysis(bazi, wuxing, gender) {
- const traits = [];
-
- // 根据日干分析性格
- const dayStem = bazi.day[0];
- switch (dayStem) {
- case '甲':
- traits.push('性格刚直,有领导才能,喜欢挑战');
- break;
- case '乙':
- traits.push('性格温和,适应能力强,善于合作');
- break;
- case '丙':
- traits.push('性格开朗,热情洋溢,富有创造力');
- break;
- case '丁':
- traits.push('性格细腻,思维敏锐,注重细节');
- break;
- default:
- traits.push('性格特点需要结合具体情况分析');
- }
-
- // 根据五行平衡分析性格
- const balance = this.analyzeWuxingBalance(wuxing);
- if (balance.dominantElement === 'wood') {
- traits.push('木旺之人,性格积极向上,富有生命力');
- } else if (balance.dominantElement === 'fire') {
- traits.push('火旺之人,性格热情奔放,行动力强');
- }
-
- return traits.join(';');
- },
-
- /**
- * 生成事业分析
- */
- generateCareerAnalysis(bazi, wuxing) {
- const advice = [];
- const balance = this.analyzeWuxingBalance(wuxing);
-
- if (balance.dominantElement === 'wood') {
- advice.push('适合从事教育、文化、林业等与木相关的行业');
- } else if (balance.dominantElement === 'fire') {
- advice.push('适合从事能源、娱乐、餐饮等与火相关的行业');
- } else if (balance.dominantElement === 'earth') {
- advice.push('适合从事房地产、农业、建筑等与土相关的行业');
- } else if (balance.dominantElement === 'metal') {
- advice.push('适合从事金融、机械、汽车等与金相关的行业');
- } else if (balance.dominantElement === 'water') {
- advice.push('适合从事航运、水利、贸易等与水相关的行业');
- }
-
- return advice.join(';');
- },
-
- /**
- * 生成财运分析
- */
- generateWealthAnalysis(bazi, wuxing) {
- return '财运需要通过努力获得,建议理性投资,稳健理财';
- },
-
- /**
- * 生成健康分析
- */
- generateHealthAnalysis(bazi, wuxing) {
- const balance = this.analyzeWuxingBalance(wuxing);
- const advice = [];
-
- if (balance.lackingElement === 'wood') {
- advice.push('注意肝胆健康,多接触绿色植物');
- } else if (balance.lackingElement === 'fire') {
- advice.push('注意心脏健康,保持乐观心态');
- }
-
- return advice.length > 0 ? advice.join(';') : '身体健康状况良好,注意均衡饮食和适量运动';
- },
-
- /**
- * 生成感情分析
- */
- generateRelationshipAnalysis(bazi, wuxing, gender) {
- return '感情运势平稳,建议真诚待人,珍惜缘分';
- },
-
- /**
- * 计算紫微斗数
- */
- calculateZiwei(birthDate, birthTime, gender) {
- const date = new Date(birthDate + 'T' + (birthTime || '12:00'));
- const hour = date.getHours();
-
- // 简化的紫微斗数计算
- const mingGongIndex = Math.floor(hour / 2);
- const mingGong = EARTHLY_BRANCHES[mingGongIndex];
-
- // 随机分配主星(实际应用中需要复杂的计算)
- const mainStars = this.getRandomStars(ZIWEI_STARS.main, 2);
- const luckyStars = this.getRandomStars(ZIWEI_STARS.lucky, 3);
- const unluckyStars = this.getRandomStars(ZIWEI_STARS.unlucky, 2);
-
- // 生成十二宫位
- const twelvePalaces = this.generateTwelvePalaces(mingGongIndex);
-
- // 四化飞星
- const siHua = this.generateSiHua();
-
- return {
- mingGong,
- mingGongXing: mainStars,
- shiErGong: twelvePalaces,
- siHua,
- birthChart: {
- mingGongPosition: mingGong,
- mainStars,
- luckyStars,
- unluckyStars
- }
- };
- },
-
- /**
- * 随机获取星曜
- */
- getRandomStars(starArray, count) {
- const shuffled = [...starArray].sort(() => 0.5 - Math.random());
- return shuffled.slice(0, count);
- },
-
- /**
- * 生成十二宫位
- */
- generateTwelvePalaces(mingGongIndex) {
- const palaces = ['命宫', '兄弟宫', '夫妻宫', '子女宫', '财帛宫', '疾厄宫', '迁移宫', '交友宫', '事业宫', '田宅宫', '福德宫', '父母宫'];
- const result = {};
-
- palaces.forEach((palace, index) => {
- const branchIndex = (mingGongIndex + index) % 12;
- result[palace] = {
- branch: EARTHLY_BRANCHES[branchIndex],
- mainStars: this.getRandomStars(ZIWEI_STARS.main, 1),
- interpretation: `${palace}的详细解读内容`
- };
- });
-
- return result;
- },
-
- /**
- * 生成四化飞星
- */
- generateSiHua() {
- return {
- huaLu: { star: '廉贞', meaning: '财禄亨通,运势顺遂' },
- huaQuan: { star: '破军', meaning: '权力地位,事业有成' },
- huaKe: { star: '武曲', meaning: '贵人相助,学业有成' },
- huaJi: { star: '太阳', meaning: '需要谨慎,防范风险' }
- };
- },
-
- /**
- * 生成紫微斗数分析
- */
- generateZiweiAnalysis(ziwei, gender) {
- return {
- character: {
- overview: '根据命宫主星分析,您的性格特点突出',
- personalityTraits: '具有领导能力,做事果断,富有责任感'
- },
- career: {
- suitableIndustries: ['管理', '金融', '教育'],
- careerAdvice: '适合从事需要决策和领导的工作'
- },
- wealth: {
- wealthPattern: '财运稳定,通过努力可以获得不错的收入'
- },
- health: {
- constitution: '体质较好,注意劳逸结合',
- wellnessAdvice: '保持规律作息,适量运动'
- },
- relationships: {
- marriageFortune: '感情运势平稳,婚姻美满',
- spouseCharacteristics: '伴侣性格温和,相处和谐'
- }
- };
- },
-
- /**
- * 生成卦象
- */
- generateHexagram() {
- const randomIndex = Math.floor(Math.random() * HEXAGRAMS.length);
- const hexagram = HEXAGRAMS[randomIndex];
-
- return {
- name: hexagram.name,
- symbol: hexagram.symbol,
- description: hexagram.description,
- upperTrigram: hexagram.symbol.substring(0, 1),
- lowerTrigram: hexagram.symbol.substring(1, 2)
- };
- },
-
- /**
- * 生成易经分析
- */
- generateYijingAnalysis(hexagram, question) {
- return {
- basicInfo: {
- divinationData: {
- question,
- method: '梅花易数时间起卦法',
- divinationTime: new Date().toISOString()
- },
- hexagramInfo: {
- mainHexagram: hexagram.name,
- hexagramDescription: hexagram.description,
- upperTrigram: hexagram.upperTrigram,
- lowerTrigram: hexagram.lowerTrigram,
- detailedInterpretation: `${hexagram.name}卦象显示${hexagram.description}`
- }
- },
- detailedAnalysis: {
- hexagramAnalysis: {
- primaryMeaning: '此卦象征着新的开始和机遇',
- judgment: '吉',
- image: '天行健,君子以自强不息'
- },
- changingLinesAnalysis: {
- changingLinePosition: '六二',
- lineMeaning: '见龙在田,利见大人'
- },
- changingHexagram: {
- name: '天风姤',
- meaning: '变化中蕴含新的机遇',
- transformationInsight: '顺应变化,把握时机'
- }
- },
- lifeGuidance: {
- overallFortune: '整体运势向好,宜积极进取',
- careerGuidance: '事业发展顺利,可以大胆尝试',
- relationshipGuidance: '人际关系和谐,感情稳定',
- wealthGuidance: '财运亨通,投资需谨慎'
- },
- divinationWisdom: {
- keyMessage: '天道酬勤,自强不息',
- actionAdvice: '保持积极心态,勇于面对挑战',
- philosophicalInsight: '变化是永恒的,适应变化才能成功'
- }
- };
- },
-
- /**
- * 生成五行建议
- */
- generateWuxingRecommendations(wuxing) {
- const balance = this.analyzeWuxingBalance(wuxing);
- const recommendations = {
- colors: [],
- directions: [],
- careerFields: [],
- lifestyleAdvice: ''
- };
-
- if (balance.lackingElement === 'wood') {
- recommendations.colors = ['绿色', '青色'];
- recommendations.directions = ['东方'];
- recommendations.careerFields = ['教育', '文化', '林业'];
- recommendations.lifestyleAdvice = '多接触自然,种植绿色植物';
- } else if (balance.lackingElement === 'fire') {
- recommendations.colors = ['红色', '橙色'];
- recommendations.directions = ['南方'];
- recommendations.careerFields = ['能源', '娱乐', '餐饮'];
- recommendations.lifestyleAdvice = '保持乐观心态,多参加社交活动';
- }
-
- return recommendations;
- },
-
- /**
- * 获取用户分析历史
- */
- async getReadingHistory(userId, type = null) {
- try {
- let readings;
- if (type) {
- readings = dbOperations.getReadingsByUserIdAndType.all(userId, type);
- } else {
- readings = dbOperations.getReadingsByUserId.all(userId);
- }
-
- return readings.map(reading => ({
- id: reading.id,
- type: reading.reading_type,
- name: reading.name,
- birthDate: reading.birth_date,
- birthTime: reading.birth_time,
- gender: reading.gender,
- birthPlace: reading.birth_place,
- status: reading.status,
- createdAt: reading.created_at,
- results: reading.results ? JSON.parse(reading.results) : null,
- analysis: reading.analysis ? JSON.parse(reading.analysis) : null
- }));
- } catch (error) {
- throw new Error(`获取分析历史失败: ${error.message}`);
- }
- },
-
- /**
- * 删除分析记录
- */
- async deleteReading(userId, readingId) {
- try {
- const result = dbOperations.deleteReading.run(readingId, userId);
- return result.changes > 0;
- } catch (error) {
- throw new Error(`删除分析记录失败: ${error.message}`);
- }
- }
-};
\ No newline at end of file
diff --git a/src/contexts/AuthContext.tsx b/src/contexts/AuthContext.tsx
index fc57b21..0368409 100644
--- a/src/contexts/AuthContext.tsx
+++ b/src/contexts/AuthContext.tsx
@@ -1,5 +1,5 @@
import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
-import { User } from '../lib/localApi';
+import { User } from '@supabase/supabase-js';
import { supabase } from '../lib/supabase';
interface AuthContextType {
@@ -25,26 +25,19 @@ export function AuthProvider({ children }: AuthProviderProps) {
async function loadUser() {
setLoading(true);
try {
- const response = await supabase.auth.getUser();
- if (response.data?.user) {
- setUser(response.data.user);
- } else {
- setUser(null);
- }
- } catch (error) {
- console.error('加载用户信息失败:', error);
- setUser(null);
+ const { data: { user } } = await supabase.auth.getUser();
+ setUser(user);
} finally {
setLoading(false);
}
}
loadUser();
- // Set up auth listener - 本地API版本
+ // Set up auth listener - KEEP SIMPLE, avoid any async operations in callback
const { data: { subscription } } = supabase.auth.onAuthStateChange(
(_event, session) => {
+ // NEVER use any async operations in callback
setUser(session?.user || null);
- setLoading(false);
}
);
@@ -53,25 +46,18 @@ export function AuthProvider({ children }: AuthProviderProps) {
// Auth methods
async function signIn(email: string, password: string) {
- const response = await supabase.auth.signInWithPassword({ email, password });
- if (response.data?.user) {
- setUser(response.data.user);
- }
- return response;
+ return await supabase.auth.signInWithPassword({ email, password });
}
async function signUp(email: string, password: string) {
- const response = await supabase.auth.signUp({ email, password });
- if (response.data?.user) {
- setUser(response.data.user);
- }
- return response;
+ return await supabase.auth.signUp({
+ email,
+ password,
+ });
}
async function signOut() {
- const response = await supabase.auth.signOut();
- setUser(null);
- return response;
+ return await supabase.auth.signOut();
}
return (
diff --git a/src/lib/localApi.ts b/src/lib/localApi.ts
deleted file mode 100644
index 5ebaebf..0000000
--- a/src/lib/localApi.ts
+++ /dev/null
@@ -1,322 +0,0 @@
-// 本地API客户端,替换Supabase
-
-const API_BASE_URL = 'http://localhost:3001/api';
-
-// 存储token的key
-const TOKEN_KEY = 'numerology_token';
-
-// API响应类型
-interface ApiResponse {
- data?: T;
- error?: {
- code: string;
- message: string;
- };
- message?: string;
-}
-
-// 用户类型
-export interface User {
- id: number;
- email: string;
- fullName?: string;
- birthDate?: string;
- birthTime?: string;
- birthPlace?: string;
- gender?: 'male' | 'female';
- createdAt: string;
-}
-
-// 认证响应类型
-interface AuthResponse {
- user: User;
- token: string;
-}
-
-// 分析记录类型
-export interface Reading {
- id: number;
- type: 'bazi' | 'ziwei' | 'yijing' | 'wuxing';
- name?: string;
- birthDate?: string;
- birthTime?: string;
- gender?: 'male' | 'female';
- birthPlace?: string;
- status: string;
- createdAt: string;
- results?: any;
- analysis?: any;
-}
-
-class LocalApiClient {
- private baseUrl: string;
-
- constructor(baseUrl: string = API_BASE_URL) {
- this.baseUrl = baseUrl;
- }
-
- // 获取存储的token
- private getToken(): string | null {
- return localStorage.getItem(TOKEN_KEY);
- }
-
- // 设置token
- private setToken(token: string): void {
- localStorage.setItem(TOKEN_KEY, token);
- }
-
- // 清除token
- private clearToken(): void {
- localStorage.removeItem(TOKEN_KEY);
- }
-
- // 通用请求方法
- private async request(
- endpoint: string,
- options: RequestInit = {}
- ): Promise> {
- const url = `${this.baseUrl}${endpoint}`;
- const token = this.getToken();
-
- const config: RequestInit = {
- headers: {
- 'Content-Type': 'application/json',
- ...(token && { Authorization: `Bearer ${token}` }),
- ...options.headers,
- },
- ...options,
- };
-
- try {
- const response = await fetch(url, config);
- const data = await response.json();
-
- if (!response.ok) {
- return { error: data.error || { code: 'UNKNOWN_ERROR', message: '请求失败' } };
- }
-
- return data;
- } catch (error) {
- console.error('API请求错误:', error);
- return {
- error: {
- code: 'NETWORK_ERROR',
- message: '网络连接失败,请检查本地服务器是否启动'
- }
- };
- }
- }
-
- // 认证相关方法
- auth = {
- // 用户注册
- signUp: async (userData: {
- email: string;
- password: string;
- fullName?: string;
- birthDate?: string;
- birthTime?: string;
- birthPlace?: string;
- gender?: 'male' | 'female';
- }): Promise> => {
- const response = await this.request('/auth/signup', {
- method: 'POST',
- body: JSON.stringify(userData),
- });
-
- if (response.data?.token) {
- this.setToken(response.data.token);
- }
-
- return response;
- },
-
- // 用户登录
- signInWithPassword: async (credentials: {
- email: string;
- password: string;
- }): Promise> => {
- const response = await this.request('/auth/signin', {
- method: 'POST',
- body: JSON.stringify(credentials),
- });
-
- if (response.data?.token) {
- this.setToken(response.data.token);
- }
-
- return response;
- },
-
- // 用户登出
- signOut: async (): Promise => {
- const response = await this.request('/auth/signout', {
- method: 'POST',
- });
-
- this.clearToken();
- return response;
- },
-
- // 获取当前用户
- getUser: async (): Promise> => {
- return await this.request<{ user: User }>('/auth/user');
- },
-
- // 验证token
- verifyToken: async (token?: string): Promise> => {
- return await this.request<{ user: User; valid: boolean }>('/auth/verify', {
- method: 'POST',
- body: JSON.stringify({ token: token || this.getToken() }),
- });
- },
-
- // 更新用户信息
- updateUser: async (userData: Partial): Promise> => {
- return await this.request<{ user: User }>('/auth/user', {
- method: 'PUT',
- body: JSON.stringify(userData),
- });
- },
-
- // 监听认证状态变化(模拟Supabase的onAuthStateChange)
- onAuthStateChange: (callback: (event: string, session: { user: User } | null) => void) => {
- // 简单实现:检查token是否存在
- const checkAuth = async () => {
- const token = this.getToken();
- if (token) {
- const response = await this.auth.verifyToken(token);
- if (response.data?.valid && response.data.user) {
- callback('SIGNED_IN', { user: response.data.user });
- } else {
- this.clearToken();
- callback('SIGNED_OUT', null);
- }
- } else {
- callback('SIGNED_OUT', null);
- }
- };
-
- // 立即检查一次
- checkAuth();
-
- // 返回取消订阅的函数
- return {
- data: {
- subscription: {
- unsubscribe: () => {
- // 本地实现不需要取消订阅
- }
- }
- }
- };
- }
- };
-
- // 分析功能相关方法
- functions = {
- // 调用分析函数
- invoke: async (functionName: string, options: { body: any }): Promise => {
- const endpointMap: { [key: string]: string } = {
- 'bazi-analyzer': '/analysis/bazi',
- 'ziwei-analyzer': '/analysis/ziwei',
- 'yijing-analyzer': '/analysis/yijing',
- 'bazi-wuxing-analysis': '/analysis/wuxing',
- 'bazi-details': '/analysis/bazi',
- 'reading-history': '/analysis/history'
- };
-
- const endpoint = endpointMap[functionName];
- if (!endpoint) {
- return {
- error: {
- code: 'FUNCTION_NOT_FOUND',
- message: `未知的分析函数: ${functionName}`
- }
- };
- }
-
- // 特殊处理历史记录请求
- if (functionName === 'reading-history') {
- if (options.body.action === 'delete') {
- return await this.request(`${endpoint}/${options.body.readingId}`, {
- method: 'DELETE'
- });
- } else {
- const queryParams = new URLSearchParams();
- if (options.body.type) queryParams.append('type', options.body.type);
- if (options.body.limit) queryParams.append('limit', options.body.limit.toString());
- if (options.body.offset) queryParams.append('offset', options.body.offset.toString());
-
- return await this.request(`${endpoint}?${queryParams.toString()}`);
- }
- }
-
- return await this.request(endpoint, {
- method: 'POST',
- body: JSON.stringify(options.body),
- });
- }
- };
-
- // 数据库操作(模拟Supabase的数据库操作)
- from = (table: string) => {
- return {
- select: (columns: string = '*') => ({
- eq: (column: string, value: any) => ({
- single: async () => {
- // 根据表名和操作类型调用相应的API
- if (table === 'user_profiles') {
- return await this.auth.getUser();
- }
- return { data: null, error: null };
- }
- }),
- order: (column: string, options?: { ascending: boolean }) => ({
- limit: (count: number) => ({
- async all() {
- if (table === 'numerology_readings') {
- const response = await this.functions.invoke('reading-history', {
- body: { limit: count }
- });
- return { data: response.data?.readings || [], error: response.error };
- }
- return { data: [], error: null };
- }
- })
- })
- }),
-
- update: (data: any) => ({
- eq: (column: string, value: any) => ({
- select: () => ({
- single: async () => {
- if (table === 'user_profiles') {
- return await this.auth.updateUser(data);
- }
- return { data: null, error: null };
- }
- })
- })
- }),
-
- insert: (data: any) => ({
- select: () => ({
- single: async () => {
- // 插入操作通常通过分析API完成
- return { data: null, error: null };
- }
- })
- })
- };
- };
-}
-
-// 创建全局实例
-export const localApi = new LocalApiClient();
-
-// 导出兼容Supabase的接口
-export const supabase = localApi;
-
-// 默认导出
-export default localApi;
\ No newline at end of file
diff --git a/src/lib/supabase.ts b/src/lib/supabase.ts
index be63d5d..ed10b1f 100644
--- a/src/lib/supabase.ts
+++ b/src/lib/supabase.ts
@@ -1,8 +1,10 @@
-// 本地化改造:使用本地API替代Supabase
-import { localApi } from './localApi';
+import { createClient } from '@supabase/supabase-js'
-// 导出本地API客户端,保持与原Supabase客户端相同的接口
-export const supabase = localApi;
+const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
+const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
-// 为了向后兼容,也可以导出为默认
-export default localApi;
\ No newline at end of file
+if (!supabaseUrl || !supabaseAnonKey) {
+ throw new Error('Missing Supabase environment variables')
+}
+
+export const supabase = createClient(supabaseUrl, supabaseAnonKey)
\ No newline at end of file
diff --git a/src/pages/AnalysisPage.tsx b/src/pages/AnalysisPage.tsx
index 8b5d7ab..2d639d2 100644
--- a/src/pages/AnalysisPage.tsx
+++ b/src/pages/AnalysisPage.tsx
@@ -35,17 +35,20 @@ const AnalysisPage: React.FC = () => {
if (!user) return;
try {
- const response = await supabase.auth.getUser();
-
- if (response.data?.user) {
- const userData = response.data.user;
- setProfile(userData);
+ const { data, error } = await supabase
+ .from('user_profiles')
+ .select('*')
+ .eq('user_id', user.id)
+ .maybeSingle();
+
+ if (data) {
+ setProfile(data);
setFormData({
- name: userData.fullName || '',
- birth_date: userData.birthDate || '',
- birth_time: userData.birthTime || '',
- gender: userData.gender || 'male',
- birth_place: userData.birthPlace || '',
+ name: data.full_name || '',
+ birth_date: data.birth_date || '',
+ birth_time: data.birth_time || '',
+ gender: data.gender || 'male',
+ birth_place: data.birth_location || '',
question: ''
});
}
diff --git a/src/pages/ProfilePage.tsx b/src/pages/ProfilePage.tsx
index aa027dc..c610d2f 100644
--- a/src/pages/ProfilePage.tsx
+++ b/src/pages/ProfilePage.tsx
@@ -30,18 +30,25 @@ const ProfilePage: React.FC = () => {
if (!user) return;
try {
- const response = await supabase.auth.getUser();
-
- if (response.data?.user) {
- const userData = response.data.user;
- setProfile(userData);
+ const { data, error } = await supabase
+ .from('user_profiles')
+ .select('*')
+ .eq('user_id', user.id)
+ .maybeSingle();
+
+ if (error && error.code !== 'PGRST116') {
+ throw error;
+ }
+
+ if (data) {
+ setProfile(data);
setFormData({
- full_name: userData.fullName || '',
- birth_date: userData.birthDate || '',
- birth_time: userData.birthTime || '',
- birth_location: userData.birthPlace || '',
- gender: userData.gender || 'male',
- username: userData.email || ''
+ full_name: data.full_name || '',
+ birth_date: data.birth_date || '',
+ birth_time: data.birth_time || '',
+ birth_location: data.birth_location || '',
+ gender: data.gender || 'male',
+ username: data.username || ''
});
}
} catch (error: any) {
@@ -57,24 +64,39 @@ const ProfilePage: React.FC = () => {
setLoading(true);
try {
- const updateData = {
- fullName: formData.full_name,
- birthDate: formData.birth_date,
- birthTime: formData.birth_time,
- birthPlace: formData.birth_location,
- gender: formData.gender as 'male' | 'female'
+ const profileData = {
+ user_id: user.id,
+ ...formData,
+ updated_at: new Date().toISOString()
};
- const response = await supabase.auth.updateUser(updateData);
-
- if (response.error) {
- throw response.error;
+ let result;
+ if (profile) {
+ // 更新现有档案
+ result = await supabase
+ .from('user_profiles')
+ .update(profileData)
+ .eq('user_id', user.id)
+ .select()
+ .maybeSingle();
+ } else {
+ // 创建新档案
+ result = await supabase
+ .from('user_profiles')
+ .insert([{
+ ...profileData,
+ created_at: new Date().toISOString()
+ }])
+ .select()
+ .maybeSingle();
}
- if (response.data?.user) {
- setProfile(response.data.user);
- toast.success('档案保存成功!');
+ if (result.error) {
+ throw result.error;
}
+
+ setProfile(result.data);
+ toast.success('档案保存成功!');
} catch (error: any) {
console.error('保存档案失败:', error);
toast.error('保存档案失败:' + error.message);
diff --git a/supabase.exe b/supabase.exe
new file mode 100644
index 0000000..59d7f03
Binary files /dev/null and b/supabase.exe differ
diff --git a/supabase.tar.gz b/supabase.tar.gz
new file mode 100644
index 0000000..6a64f22
Binary files /dev/null and b/supabase.tar.gz differ
diff --git a/supabase/.gitignore b/supabase/.gitignore
deleted file mode 100644
index ad9264f..0000000
--- a/supabase/.gitignore
+++ /dev/null
@@ -1,8 +0,0 @@
-# Supabase
-.branches
-.temp
-
-# dotenvx
-.env.keys
-.env.local
-.env.*.local
diff --git a/supabase/.temp/cli-latest b/supabase/.temp/cli-latest
new file mode 100644
index 0000000..322987f
--- /dev/null
+++ b/supabase/.temp/cli-latest
@@ -0,0 +1 @@
+v2.34.3
\ No newline at end of file
diff --git a/supabase/.temp/gotrue-version b/supabase/.temp/gotrue-version
new file mode 100644
index 0000000..debbfea
--- /dev/null
+++ b/supabase/.temp/gotrue-version
@@ -0,0 +1 @@
+v2.177.0
\ No newline at end of file
diff --git a/supabase/.temp/pooler-url b/supabase/.temp/pooler-url
new file mode 100644
index 0000000..eec4062
--- /dev/null
+++ b/supabase/.temp/pooler-url
@@ -0,0 +1 @@
+postgresql://postgres.myiabzmycehtxxyybqfo:[YOUR-PASSWORD]@aws-0-us-east-1.pooler.supabase.com:6543/postgres
\ No newline at end of file
diff --git a/supabase/.temp/postgres-version b/supabase/.temp/postgres-version
new file mode 100644
index 0000000..59758ce
--- /dev/null
+++ b/supabase/.temp/postgres-version
@@ -0,0 +1 @@
+17.4.1.069
\ No newline at end of file
diff --git a/supabase/.temp/project-ref b/supabase/.temp/project-ref
new file mode 100644
index 0000000..54ac15c
--- /dev/null
+++ b/supabase/.temp/project-ref
@@ -0,0 +1 @@
+myiabzmycehtxxyybqfo
\ No newline at end of file
diff --git a/supabase/.temp/rest-version b/supabase/.temp/rest-version
new file mode 100644
index 0000000..c518e9a
--- /dev/null
+++ b/supabase/.temp/rest-version
@@ -0,0 +1 @@
+v13.0.4
\ No newline at end of file
diff --git a/supabase/.temp/storage-version b/supabase/.temp/storage-version
new file mode 100644
index 0000000..04f8825
--- /dev/null
+++ b/supabase/.temp/storage-version
@@ -0,0 +1 @@
+custom-metadata
\ No newline at end of file
diff --git a/supabase/config.toml b/supabase/config.toml
deleted file mode 100644
index 41969b3..0000000
--- a/supabase/config.toml
+++ /dev/null
@@ -1,334 +0,0 @@
-# For detailed configuration reference documentation, visit:
-# https://supabase.com/docs/guides/local-development/cli/config
-# A string used to distinguish different Supabase projects on the same host. Defaults to the
-# working directory name when running `supabase init`.
-project_id = "myiabzmycehtxxyybqfo"
-
-[api]
-enabled = true
-# Port to use for the API URL.
-port = 54321
-# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API
-# endpoints. `public` and `graphql_public` schemas are included by default.
-schemas = ["public", "graphql_public"]
-# Extra schemas to add to the search_path of every request.
-extra_search_path = ["public", "extensions"]
-# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size
-# for accidental or malicious requests.
-max_rows = 1000
-
-[api.tls]
-# Enable HTTPS endpoints locally using a self-signed certificate.
-enabled = false
-
-[db]
-# Port to use for the local database URL.
-port = 54322
-# Port used by db diff command to initialize the shadow database.
-shadow_port = 54320
-# The database major version to use. This has to be the same as your remote database's. Run `SHOW
-# server_version;` on the remote database to check.
-major_version = 17
-
-[db.pooler]
-enabled = false
-# Port to use for the local connection pooler.
-port = 54329
-# Specifies when a server connection can be reused by other clients.
-# Configure one of the supported pooler modes: `transaction`, `session`.
-pool_mode = "transaction"
-# How many server connections to allow per user/database pair.
-default_pool_size = 20
-# Maximum number of client connections allowed.
-max_client_conn = 100
-
-# [db.vault]
-# secret_key = "env(SECRET_VALUE)"
-
-[db.migrations]
-# If disabled, migrations will be skipped during a db push or reset.
-enabled = true
-# Specifies an ordered list of schema files that describe your database.
-# Supports glob patterns relative to supabase directory: "./schemas/*.sql"
-schema_paths = []
-
-[db.seed]
-# If enabled, seeds the database after migrations during a db reset.
-enabled = true
-# Specifies an ordered list of seed files to load during db reset.
-# Supports glob patterns relative to supabase directory: "./seeds/*.sql"
-sql_paths = ["./seed.sql"]
-
-[db.network_restrictions]
-# Enable management of network restrictions.
-enabled = false
-# List of IPv4 CIDR blocks allowed to connect to the database.
-# Defaults to allow all IPv4 connections. Set empty array to block all IPs.
-allowed_cidrs = ["0.0.0.0/0"]
-# List of IPv6 CIDR blocks allowed to connect to the database.
-# Defaults to allow all IPv6 connections. Set empty array to block all IPs.
-allowed_cidrs_v6 = ["::/0"]
-
-[realtime]
-enabled = true
-# Bind realtime via either IPv4 or IPv6. (default: IPv4)
-# ip_version = "IPv6"
-# The maximum length in bytes of HTTP request headers. (default: 4096)
-# max_header_length = 4096
-
-[studio]
-enabled = true
-# Port to use for Supabase Studio.
-port = 54323
-# External URL of the API server that frontend connects to.
-api_url = "http://127.0.0.1"
-# OpenAI API Key to use for Supabase AI in the Supabase Studio.
-openai_api_key = "env(OPENAI_API_KEY)"
-
-# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they
-# are monitored, and you can view the emails that would have been sent from the web interface.
-[inbucket]
-enabled = true
-# Port to use for the email testing server web interface.
-port = 54324
-# Uncomment to expose additional ports for testing user applications that send emails.
-# smtp_port = 54325
-# pop3_port = 54326
-# admin_email = "admin@email.com"
-# sender_name = "Admin"
-
-[storage]
-enabled = true
-# The maximum file size allowed (e.g. "5MB", "500KB").
-file_size_limit = "50MiB"
-
-# Image transformation API is available to Supabase Pro plan.
-# [storage.image_transformation]
-# enabled = true
-
-# Uncomment to configure local storage buckets
-# [storage.buckets.images]
-# public = false
-# file_size_limit = "50MiB"
-# allowed_mime_types = ["image/png", "image/jpeg"]
-# objects_path = "./images"
-
-[auth]
-enabled = true
-# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used
-# in emails.
-site_url = "http://127.0.0.1:3000"
-# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
-additional_redirect_urls = ["https://127.0.0.1:3000"]
-# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).
-jwt_expiry = 3600
-# Path to JWT signing key. DO NOT commit your signing keys file to git.
-# signing_keys_path = "./signing_keys.json"
-# If disabled, the refresh token will never expire.
-enable_refresh_token_rotation = true
-# Allows refresh tokens to be reused after expiry, up to the specified interval in seconds.
-# Requires enable_refresh_token_rotation = true.
-refresh_token_reuse_interval = 10
-# Allow/disallow new user signups to your project.
-enable_signup = true
-# Allow/disallow anonymous sign-ins to your project.
-enable_anonymous_sign_ins = false
-# Allow/disallow testing manual linking of accounts
-enable_manual_linking = false
-# Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.
-minimum_password_length = 6
-# Passwords that do not meet the following requirements will be rejected as weak. Supported values
-# are: `letters_digits`, `lower_upper_letters_digits`, `lower_upper_letters_digits_symbols`
-password_requirements = ""
-
-[auth.rate_limit]
-# Number of emails that can be sent per hour. Requires auth.email.smtp to be enabled.
-email_sent = 2
-# Number of SMS messages that can be sent per hour. Requires auth.sms to be enabled.
-sms_sent = 30
-# Number of anonymous sign-ins that can be made per hour per IP address. Requires enable_anonymous_sign_ins = true.
-anonymous_users = 30
-# Number of sessions that can be refreshed in a 5 minute interval per IP address.
-token_refresh = 150
-# Number of sign up and sign-in requests that can be made in a 5 minute interval per IP address (excludes anonymous users).
-sign_in_sign_ups = 30
-# Number of OTP / Magic link verifications that can be made in a 5 minute interval per IP address.
-token_verifications = 30
-# Number of Web3 logins that can be made in a 5 minute interval per IP address.
-web3 = 30
-
-# Configure one of the supported captcha providers: `hcaptcha`, `turnstile`.
-# [auth.captcha]
-# enabled = true
-# provider = "hcaptcha"
-# secret = ""
-
-[auth.email]
-# Allow/disallow new user signups via email to your project.
-enable_signup = true
-# If enabled, a user will be required to confirm any email change on both the old, and new email
-# addresses. If disabled, only the new email is required to confirm.
-double_confirm_changes = true
-# If enabled, users need to confirm their email address before signing in.
-enable_confirmations = false
-# If enabled, users will need to reauthenticate or have logged in recently to change their password.
-secure_password_change = false
-# Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.
-max_frequency = "1s"
-# Number of characters used in the email OTP.
-otp_length = 6
-# Number of seconds before the email OTP expires (defaults to 1 hour).
-otp_expiry = 3600
-
-# Use a production-ready SMTP server
-# [auth.email.smtp]
-# enabled = true
-# host = "smtp.sendgrid.net"
-# port = 587
-# user = "apikey"
-# pass = "env(SENDGRID_API_KEY)"
-# admin_email = "admin@email.com"
-# sender_name = "Admin"
-
-# Uncomment to customize email template
-# [auth.email.template.invite]
-# subject = "You have been invited"
-# content_path = "./supabase/templates/invite.html"
-
-[auth.sms]
-# Allow/disallow new user signups via SMS to your project.
-enable_signup = false
-# If enabled, users need to confirm their phone number before signing in.
-enable_confirmations = false
-# Template for sending OTP to users
-template = "Your code is {{ .Code }}"
-# Controls the minimum amount of time that must pass before sending another sms otp.
-max_frequency = "5s"
-
-# Use pre-defined map of phone number to OTP for testing.
-# [auth.sms.test_otp]
-# 4152127777 = "123456"
-
-# Configure logged in session timeouts.
-# [auth.sessions]
-# Force log out after the specified duration.
-# timebox = "24h"
-# Force log out if the user has been inactive longer than the specified duration.
-# inactivity_timeout = "8h"
-
-# This hook runs before a new user is created and allows developers to reject the request based on the incoming user object.
-# [auth.hook.before_user_created]
-# enabled = true
-# uri = "pg-functions://postgres/auth/before-user-created-hook"
-
-# This hook runs before a token is issued and allows you to add additional claims based on the authentication method used.
-# [auth.hook.custom_access_token]
-# enabled = true
-# uri = "pg-functions:////"
-
-# Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`.
-[auth.sms.twilio]
-enabled = false
-account_sid = ""
-message_service_sid = ""
-# DO NOT commit your Twilio auth token to git. Use environment variable substitution instead:
-auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)"
-
-# Multi-factor-authentication is available to Supabase Pro plan.
-[auth.mfa]
-# Control how many MFA factors can be enrolled at once per user.
-max_enrolled_factors = 10
-
-# Control MFA via App Authenticator (TOTP)
-[auth.mfa.totp]
-enroll_enabled = false
-verify_enabled = false
-
-# Configure MFA via Phone Messaging
-[auth.mfa.phone]
-enroll_enabled = false
-verify_enabled = false
-otp_length = 6
-template = "Your code is {{ .Code }}"
-max_frequency = "5s"
-
-# Configure MFA via WebAuthn
-# [auth.mfa.web_authn]
-# enroll_enabled = true
-# verify_enabled = true
-
-# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`,
-# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`,
-# `twitter`, `slack`, `spotify`, `workos`, `zoom`.
-[auth.external.apple]
-enabled = false
-client_id = ""
-# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead:
-secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)"
-# Overrides the default auth redirectUrl.
-redirect_uri = ""
-# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure,
-# or any other third-party OIDC providers.
-url = ""
-# If enabled, the nonce check will be skipped. Required for local sign in with Google auth.
-skip_nonce_check = false
-
-# Allow Solana wallet holders to sign in to your project via the Sign in with Solana (SIWS, EIP-4361) standard.
-# You can configure "web3" rate limit in the [auth.rate_limit] section and set up [auth.captcha] if self-hosting.
-[auth.web3.solana]
-enabled = false
-
-# Use Firebase Auth as a third-party provider alongside Supabase Auth.
-[auth.third_party.firebase]
-enabled = false
-# project_id = "my-firebase-project"
-
-# Use Auth0 as a third-party provider alongside Supabase Auth.
-[auth.third_party.auth0]
-enabled = false
-# tenant = "my-auth0-tenant"
-# tenant_region = "us"
-
-# Use AWS Cognito (Amplify) as a third-party provider alongside Supabase Auth.
-[auth.third_party.aws_cognito]
-enabled = false
-# user_pool_id = "my-user-pool-id"
-# user_pool_region = "us-east-1"
-
-# Use Clerk as a third-party provider alongside Supabase Auth.
-[auth.third_party.clerk]
-enabled = false
-# Obtain from https://clerk.com/setup/supabase
-# domain = "example.clerk.accounts.dev"
-
-[edge_runtime]
-enabled = true
-# Configure one of the supported request policies: `oneshot`, `per_worker`.
-# Use `oneshot` for hot reload, or `per_worker` for load testing.
-policy = "oneshot"
-# Port to attach the Chrome inspector for debugging edge functions.
-inspector_port = 8083
-# The Deno major version to use.
-deno_version = 1
-
-# [edge_runtime.secrets]
-# secret_key = "env(SECRET_VALUE)"
-
-[analytics]
-enabled = true
-port = 54327
-# Configure one of the supported backends: `postgres`, `bigquery`.
-backend = "postgres"
-
-# Experimental features may be deprecated any time
-[experimental]
-# Configures Postgres storage engine to use OrioleDB (S3)
-orioledb_version = ""
-# Configures S3 bucket URL, eg. .s3-.amazonaws.com
-s3_host = "env(S3_HOST)"
-# Configures S3 bucket region, eg. us-east-1
-s3_region = "env(S3_REGION)"
-# Configures AWS_ACCESS_KEY_ID for S3 bucket
-s3_access_key = "env(S3_ACCESS_KEY)"
-# Configures AWS_SECRET_ACCESS_KEY for S3 bucket
-s3_secret_key = "env(S3_SECRET_KEY)"
diff --git a/supabase/functions/bazi-analyzer/index.ts b/supabase/functions/bazi-analyzer/index.ts
deleted file mode 100644
index 8bab27b..0000000
--- a/supabase/functions/bazi-analyzer/index.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-// Supabase Edge Function: Bazi Analyzer
-// This function analyzes Chinese Four Pillars (Bazi) astrology
-
-import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
-import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
-
-const corsHeaders = {
- 'Access-Control-Allow-Origin': '*',
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
-}
-
-interface BaziRequest {
- birthDate: string
- birthTime: string
- gender: 'male' | 'female'
- location?: string
-}
-
-interface BaziResponse {
- success: boolean
- data?: {
- fourPillars: {
- year: { heavenlyStem: string; earthlyBranch: string }
- month: { heavenlyStem: string; earthlyBranch: string }
- day: { heavenlyStem: string; earthlyBranch: string }
- hour: { heavenlyStem: string; earthlyBranch: string }
- }
- elements: {
- wood: number
- fire: number
- earth: number
- metal: number
- water: number
- }
- analysis: {
- personality: string
- career: string
- health: string
- relationships: string
- }
- }
- error?: string
-}
-
-serve(async (req) => {
- // Handle CORS preflight requests
- if (req.method === 'OPTIONS') {
- return new Response('ok', { headers: corsHeaders })
- }
-
- try {
- // Initialize Supabase client
- const supabaseClient = createClient(
- Deno.env.get('SUPABASE_URL') ?? '',
- Deno.env.get('SUPABASE_ANON_KEY') ?? '',
- {
- global: {
- headers: { Authorization: req.headers.get('Authorization')! },
- },
- }
- )
-
- // Get the current user
- const {
- data: { user },
- } = await supabaseClient.auth.getUser()
-
- if (!user) {
- return new Response(
- JSON.stringify({ success: false, error: 'Unauthorized' }),
- {
- status: 401,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- }
- )
- }
-
- // Parse request body
- const { birthDate, birthTime, gender, location }: BaziRequest = await req.json()
-
- if (!birthDate || !birthTime || !gender) {
- return new Response(
- JSON.stringify({ success: false, error: 'Missing required fields' }),
- {
- status: 400,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- }
- )
- }
-
- // TODO: Implement actual Bazi calculation logic
- // For now, return mock data
- const mockAnalysis: BaziResponse = {
- success: true,
- data: {
- fourPillars: {
- year: { heavenlyStem: '甲', earthlyBranch: '子' },
- month: { heavenlyStem: '乙', earthlyBranch: '丑' },
- day: { heavenlyStem: '丙', earthlyBranch: '寅' },
- hour: { heavenlyStem: '丁', earthlyBranch: '卯' },
- },
- elements: {
- wood: 2,
- fire: 1,
- earth: 1,
- metal: 0,
- water: 1,
- },
- analysis: {
- personality: '性格温和,具有创造力,善于沟通。',
- career: '适合从事创意、教育或咨询相关工作。',
- health: '注意肝胆和心血管健康。',
- relationships: '人际关系良好,容易获得他人信任。',
- },
- },
- }
-
- // Save analysis to database
- const { error: insertError } = await supabaseClient
- .from('analysis_history')
- .insert({
- user_id: user.id,
- analysis_type: 'bazi',
- input_data: { birthDate, birthTime, gender, location },
- result_data: mockAnalysis.data,
- })
-
- if (insertError) {
- console.error('Error saving analysis:', insertError)
- }
-
- return new Response(JSON.stringify(mockAnalysis), {
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- })
- } catch (error) {
- console.error('Error in bazi-analyzer:', error)
- return new Response(
- JSON.stringify({ success: false, error: 'Internal server error' }),
- {
- status: 500,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- }
- )
- }
-})
\ No newline at end of file
diff --git a/supabase/functions/ziwei-analyzer/index.ts b/supabase/functions/ziwei-analyzer/index.ts
deleted file mode 100644
index 986389d..0000000
--- a/supabase/functions/ziwei-analyzer/index.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-// Supabase Edge Function: Ziwei Analyzer
-// This function analyzes Ziwei Doushu (Purple Star Astrology)
-
-import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
-import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
-
-const corsHeaders = {
- 'Access-Control-Allow-Origin': '*',
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
-}
-
-interface ZiweiRequest {
- birthDate: string
- birthTime: string
- gender: 'male' | 'female'
- location?: string
-}
-
-interface ZiweiResponse {
- success: boolean
- data?: {
- palaces: {
- ming: { position: string; stars: string[] }
- xiong: { position: string; stars: string[] }
- cai: { position: string; stars: string[] }
- guan: { position: string; stars: string[] }
- tian: { position: string; stars: string[] }
- fu: { position: string; stars: string[] }
- zi: { position: string; stars: string[] }
- nu: { position: string; stars: string[] }
- qian: { position: string; stars: string[] }
- ji: { position: string; stars: string[] }
- tian2: { position: string; stars: string[] }
- xiang: { position: string; stars: string[] }
- }
- mainStars: string[]
- luckyStars: string[]
- unluckyStars: string[]
- analysis: {
- personality: string
- career: string
- wealth: string
- relationships: string
- health: string
- }
- }
- error?: string
-}
-
-serve(async (req) => {
- // Handle CORS preflight requests
- if (req.method === 'OPTIONS') {
- return new Response('ok', { headers: corsHeaders })
- }
-
- try {
- // Initialize Supabase client
- const supabaseClient = createClient(
- Deno.env.get('SUPABASE_URL') ?? '',
- Deno.env.get('SUPABASE_ANON_KEY') ?? '',
- {
- global: {
- headers: { Authorization: req.headers.get('Authorization')! },
- },
- }
- )
-
- // Get the current user
- const {
- data: { user },
- } = await supabaseClient.auth.getUser()
-
- if (!user) {
- return new Response(
- JSON.stringify({ success: false, error: 'Unauthorized' }),
- {
- status: 401,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- }
- )
- }
-
- // Parse request body
- const { birthDate, birthTime, gender, location }: ZiweiRequest = await req.json()
-
- if (!birthDate || !birthTime || !gender) {
- return new Response(
- JSON.stringify({ success: false, error: 'Missing required fields' }),
- {
- status: 400,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- }
- )
- }
-
- // TODO: Implement actual Ziwei calculation logic
- // For now, return mock data
- const mockAnalysis: ZiweiResponse = {
- success: true,
- data: {
- palaces: {
- ming: { position: '子', stars: ['紫微', '天府'] },
- xiong: { position: '丑', stars: ['太阳', '巨门'] },
- cai: { position: '寅', stars: ['天机', '太阴'] },
- guan: { position: '卯', stars: ['天同', '天梁'] },
- tian: { position: '辰', stars: ['七杀'] },
- fu: { position: '巳', stars: ['破军'] },
- zi: { position: '午', stars: ['廉贞', '贪狼'] },
- nu: { position: '未', stars: ['天相'] },
- qian: { position: '申', stars: ['天马'] },
- ji: { position: '酉', stars: ['文昌'] },
- tian2: { position: '戌', stars: ['文曲'] },
- xiang: { position: '亥', stars: ['左辅', '右弼'] },
- },
- mainStars: ['紫微', '天府', '太阳', '巨门', '天机', '太阴'],
- luckyStars: ['文昌', '文曲', '左辅', '右弼', '天马'],
- unluckyStars: ['擎羊', '陀罗', '火星', '铃星'],
- analysis: {
- personality: '性格高贵,具有领导才能,喜欢掌控全局。',
- career: '适合从事管理、政治或高端服务业。',
- wealth: '财运稳定,有贵人相助,投资需谨慎。',
- relationships: '人际关系复杂,需要平衡各方利益。',
- health: '注意心脏和血压问题,保持规律作息。',
- },
- },
- }
-
- // Save analysis to database
- const { error: insertError } = await supabaseClient
- .from('analysis_history')
- .insert({
- user_id: user.id,
- analysis_type: 'ziwei',
- input_data: { birthDate, birthTime, gender, location },
- result_data: mockAnalysis.data,
- })
-
- if (insertError) {
- console.error('Error saving analysis:', insertError)
- }
-
- return new Response(JSON.stringify(mockAnalysis), {
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- })
- } catch (error) {
- console.error('Error in ziwei-analyzer:', error)
- return new Response(
- JSON.stringify({ success: false, error: 'Internal server error' }),
- {
- status: 500,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- }
- )
- }
-})
\ No newline at end of file
diff --git a/supabase/seed.sql b/supabase/seed.sql
deleted file mode 100644
index d4f07a8..0000000
--- a/supabase/seed.sql
+++ /dev/null
@@ -1,82 +0,0 @@
--- Supabase AI Numerology Project Seed Data
--- This file contains initial data for the numerology analysis platform
-
--- Enable necessary extensions
-CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-CREATE EXTENSION IF NOT EXISTS "pgcrypto";
-
--- Create profiles table if it doesn't exist
-CREATE TABLE IF NOT EXISTS public.profiles (
- id UUID REFERENCES auth.users(id) ON DELETE CASCADE PRIMARY KEY,
- username TEXT UNIQUE,
- full_name TEXT,
- avatar_url TEXT,
- birth_date DATE,
- birth_time TIME,
- birth_location TEXT,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
-);
-
--- Create analysis_history table if it doesn't exist
-CREATE TABLE IF NOT EXISTS public.analysis_history (
- id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
- user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
- analysis_type TEXT NOT NULL CHECK (analysis_type IN ('bazi', 'ziwei', 'yijing', 'wuxing')),
- input_data JSONB NOT NULL,
- result_data JSONB NOT NULL,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
-);
-
--- Enable Row Level Security
-ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
-ALTER TABLE public.analysis_history ENABLE ROW LEVEL SECURITY;
-
--- Create policies for profiles table
-CREATE POLICY "Users can view own profile" ON public.profiles
- FOR SELECT USING (auth.uid() = id);
-
-CREATE POLICY "Users can update own profile" ON public.profiles
- FOR UPDATE USING (auth.uid() = id);
-
-CREATE POLICY "Users can insert own profile" ON public.profiles
- FOR INSERT WITH CHECK (auth.uid() = id);
-
--- Create policies for analysis_history table
-CREATE POLICY "Users can view own analysis history" ON public.analysis_history
- FOR SELECT USING (auth.uid() = user_id);
-
-CREATE POLICY "Users can insert own analysis history" ON public.analysis_history
- FOR INSERT WITH CHECK (auth.uid() = user_id);
-
--- Create indexes for better performance
-CREATE INDEX IF NOT EXISTS idx_analysis_history_user_id ON public.analysis_history(user_id);
-CREATE INDEX IF NOT EXISTS idx_analysis_history_type ON public.analysis_history(analysis_type);
-CREATE INDEX IF NOT EXISTS idx_analysis_history_created_at ON public.analysis_history(created_at DESC);
-
--- Insert some sample data (optional)
--- Note: This would only work if there are existing users
--- INSERT INTO public.profiles (id, username, full_name)
--- VALUES ('00000000-0000-0000-0000-000000000000', 'demo_user', 'Demo User')
--- ON CONFLICT (id) DO NOTHING;
-
--- Create a function to automatically create a profile when a user signs up
-CREATE OR REPLACE FUNCTION public.handle_new_user()
-RETURNS TRIGGER AS $$
-BEGIN
- INSERT INTO public.profiles (id, username, full_name)
- VALUES (NEW.id, NEW.email, NEW.raw_user_meta_data->>'full_name');
- RETURN NEW;
-END;
-$$ LANGUAGE plpgsql SECURITY DEFINER;
-
--- Create trigger to automatically create profile on user signup
-DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users;
-CREATE TRIGGER on_auth_user_created
- AFTER INSERT ON auth.users
- FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
-
--- Grant necessary permissions
-GRANT USAGE ON SCHEMA public TO anon, authenticated;
-GRANT ALL ON public.profiles TO anon, authenticated;
-GRANT ALL ON public.analysis_history TO anon, authenticated;
\ No newline at end of file
diff --git a/supabase_latest.tar.gz b/supabase_latest.tar.gz
new file mode 100644
index 0000000..6a64f22
Binary files /dev/null and b/supabase_latest.tar.gz differ