Compare commits
102 Commits
2645d2afe5
...
fix/logout
| Author | SHA1 | Date | |
|---|---|---|---|
| b764ff7ea3 | |||
| 86db3e1868 | |||
| 3133a2f10c | |||
| 8a653b684e | |||
| a77aecba75 | |||
| f355eaac4d | |||
| b69abe0fdb | |||
| 9dbaf95839 | |||
| e04d572f27 | |||
| 321b1ea585 | |||
| 73a041d9c8 | |||
| 3912e2d122 | |||
| 4826c00e27 | |||
| 2a823e5bac | |||
| 4d5c9874a9 | |||
| 0dd2cc00d3 | |||
| 9f25da6232 | |||
| d1723797e0 | |||
| e459a52b5b | |||
| 472b554cd0 | |||
| 765bc0facc | |||
| 2417ea2525 | |||
| 4a3fadb048 | |||
| 1044873336 | |||
| 03a112c734 | |||
| 9be123e927 | |||
| 95368049fe | |||
| e0526f93b3 | |||
| 751ef9d07d | |||
| e3285f0961 | |||
| 1018c1db11 | |||
| 5b5b73bba8 | |||
| 5d8f1f1e1f | |||
| 2469f15656 | |||
| 309dee9848 | |||
| 50756528ee | |||
| 26a47aaf23 | |||
| fc16436ebd | |||
| 029071dbab | |||
| 3a65cb7209 | |||
| 3d95db6cae | |||
| 4e0039d5ad | |||
| f580aa3eee | |||
| 2983036388 | |||
| 0c19153156 | |||
| 66766197a4 | |||
| 31b46d59b6 | |||
| cc79ae1211 | |||
| dcf516f2de | |||
| c8de1ad229 | |||
| 533cd2a0bd | |||
| de74ffe638 | |||
| 4761253d73 | |||
| 65239abc53 | |||
| 19f4ab8abe | |||
| 96504ed1d7 | |||
| 5eba04a1fa | |||
| 4d5e3c46e7 | |||
| 3bbe437616 | |||
| edc053ae0e | |||
| b9681141af | |||
| dee4b1649a | |||
| 955512d344 | |||
| 81ec5987b3 | |||
| 70413971e3 | |||
| 6804835e85 | |||
| 2088019ed7 | |||
| 86be739667 | |||
| 4655040153 | |||
| d68f5b35ee | |||
| cd833a6232 | |||
| 43f57c55f5 | |||
| f89cfff20b | |||
| 6563a6f7d2 | |||
| 2bec4a2d26 | |||
| eaab1276a2 | |||
| a4b79ebe65 | |||
| 7fd52f7a86 | |||
| f884bff452 | |||
| 9c85ed21b3 | |||
| a27c30ea7c | |||
| f88521c9be | |||
| c115c47e61 | |||
| 56d0c9b469 | |||
| 4fbd18c952 | |||
| ec25aebdd9 | |||
| 0d0a563fab | |||
| bc27863930 | |||
| 9628a3357e | |||
| 34c671f9f3 | |||
| 7dbcd2778e | |||
| 81efad83f9 | |||
| 8443f1a564 | |||
| cd65fd35be | |||
| 9c1c71d21a | |||
| 67ccf1771f | |||
| 22b60c1716 | |||
| b515cf162b | |||
| d6058c8d02 | |||
| 2ee0c7c241 | |||
| 3424fd1fd0 | |||
| 7ba1e28370 |
@@ -4,20 +4,19 @@ on:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: test
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Unit tests
|
||||
run: cd frontend && npm ci && npx vitest run
|
||||
- name: Build check
|
||||
run: cd frontend && npm run build
|
||||
|
||||
deploy:
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Unit tests
|
||||
run: cd frontend && npm ci && npm run test:unit
|
||||
|
||||
- name: Build & Deploy
|
||||
run: |
|
||||
rsync -az --exclude node_modules --exclude .git --exclude .venv . oci:~/oil-calculator/
|
||||
ssh oci "
|
||||
cd ~/oil-calculator &&
|
||||
docker build -t registry.oci.euphon.net/oil-calculator:latest . &&
|
||||
docker push registry.oci.euphon.net/oil-calculator:latest &&
|
||||
sudo k3s kubectl rollout restart deploy/oil-calculator -n oil-calculator
|
||||
"
|
||||
- name: Deploy Production
|
||||
run: python3 scripts/deploy-preview.py deploy-prod
|
||||
|
||||
@@ -3,188 +3,48 @@ on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, closed]
|
||||
|
||||
env:
|
||||
REGISTRY: registry.oci.euphon.net
|
||||
BASE_DOMAIN: oil.oci.euphon.net
|
||||
|
||||
jobs:
|
||||
test:
|
||||
if: github.event.action != 'closed'
|
||||
runs-on: test
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Unit tests
|
||||
run: cd frontend && npm ci && npx vitest run
|
||||
|
||||
deploy-preview:
|
||||
if: github.event.action != 'closed'
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Unit tests
|
||||
run: cd frontend && npm ci && npm run test:unit
|
||||
|
||||
- name: Deploy Preview Environment
|
||||
- name: Deploy Preview
|
||||
run: python3 scripts/deploy-preview.py deploy ${{ github.event.pull_request.number }}
|
||||
- name: Comment PR
|
||||
env:
|
||||
GIT_TOKEN: ${{ secrets.GIT_TOKEN }}
|
||||
run: |
|
||||
PR_ID="${{ github.event.pull_request.number }}"
|
||||
NS="oil-pr-${PR_ID}"
|
||||
HOST="pr-${PR_ID}.${BASE_DOMAIN}"
|
||||
IMAGE="${REGISTRY}/oil-calculator:pr-${PR_ID}"
|
||||
|
||||
# Sync source to oci build server
|
||||
rsync -az --exclude node_modules --exclude .git --exclude .venv \
|
||||
. oci:/tmp/oil-pr-${PR_ID}-build/
|
||||
|
||||
ssh oci bash -s "${PR_ID}" "${NS}" "${HOST}" "${IMAGE}" << 'DEPLOY_SCRIPT'
|
||||
set -e
|
||||
PR_ID="$1"; NS="$2"; HOST="$3"; IMAGE="$4"
|
||||
|
||||
cd /tmp/oil-pr-${PR_ID}-build
|
||||
|
||||
# Copy production DB into build context so it's baked into image
|
||||
PROD_POD=$(sudo k3s kubectl get pods -n oil-calculator -l app=oil-calculator \
|
||||
--field-selector=status.phase=Running -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || echo "")
|
||||
if [ -n "$PROD_POD" ]; then
|
||||
sudo k3s kubectl cp "oil-calculator/${PROD_POD}:/data/oil_calculator.db" /tmp/pr-${PR_ID}.db
|
||||
mkdir -p data
|
||||
cp /tmp/pr-${PR_ID}.db data/oil_calculator.db
|
||||
fi
|
||||
|
||||
# Build image (with DB baked in)
|
||||
cat > Dockerfile.preview << 'DEOF'
|
||||
FROM node:20-slim AS frontend-build
|
||||
WORKDIR /build
|
||||
COPY frontend/package.json frontend/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM python:3.12-slim
|
||||
WORKDIR /app
|
||||
COPY backend/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY backend/ ./backend/
|
||||
COPY --from=frontend-build /build/dist ./frontend/
|
||||
# Bake production DB copy into image
|
||||
COPY data/oil_calculator.db /data/oil_calculator.db
|
||||
ENV DB_PATH=/data/oil_calculator.db
|
||||
ENV FRONTEND_DIR=/app/frontend
|
||||
EXPOSE 8000
|
||||
CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
DEOF
|
||||
|
||||
docker build -f Dockerfile.preview -t "${IMAGE}" .
|
||||
docker push "${IMAGE}"
|
||||
|
||||
# Create namespace
|
||||
sudo k3s kubectl create namespace "${NS}" --dry-run=client -o yaml | sudo k3s kubectl apply -f -
|
||||
|
||||
# Copy regcred from production namespace
|
||||
sudo k3s kubectl get secret regcred -n oil-calculator -o json | \
|
||||
sed "s/\"namespace\":\"oil-calculator\"/\"namespace\":\"${NS}\"/" | \
|
||||
sudo k3s kubectl apply -f -
|
||||
|
||||
# Deploy pod + service + ingress (no PVC needed, DB is in image)
|
||||
cat << EOYAML | sudo k3s kubectl apply -f -
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: oil-calculator
|
||||
namespace: ${NS}
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: oil-calculator
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: oil-calculator
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- name: regcred
|
||||
containers:
|
||||
- name: app
|
||||
image: ${IMAGE}
|
||||
ports:
|
||||
- containerPort: 8000
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 256Mi
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: oil-calculator
|
||||
namespace: ${NS}
|
||||
spec:
|
||||
selector:
|
||||
app: oil-calculator
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 8000
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: oil-calculator
|
||||
namespace: ${NS}
|
||||
annotations:
|
||||
traefik.ingress.kubernetes.io/router.tls.certresolver: le
|
||||
spec:
|
||||
ingressClassName: traefik
|
||||
tls:
|
||||
- hosts:
|
||||
- ${HOST}
|
||||
rules:
|
||||
- host: ${HOST}
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: oil-calculator
|
||||
port:
|
||||
number: 80
|
||||
EOYAML
|
||||
|
||||
# Wait for rollout
|
||||
sudo k3s kubectl rollout status deploy/oil-calculator -n "${NS}" --timeout=120s
|
||||
|
||||
# Cleanup build dir
|
||||
rm -rf /tmp/oil-pr-${PR_ID}-build /tmp/pr-${PR_ID}.db
|
||||
|
||||
echo "Preview deployed: https://${HOST}"
|
||||
DEPLOY_SCRIPT
|
||||
|
||||
- name: Comment PR with preview URL
|
||||
run: |
|
||||
PR_ID="${{ github.event.pull_request.number }}"
|
||||
HOST="pr-${PR_ID}.${BASE_DOMAIN}"
|
||||
curl -s -X POST \
|
||||
curl -sf -X POST \
|
||||
"https://git.euphon.cloud/api/v1/repos/${{ github.repository }}/issues/${PR_ID}/comments" \
|
||||
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
|
||||
-H "Authorization: token ${GIT_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"body\": \"🚀 Preview deployed: https://${HOST}\n\nDB is a copy of production. Changes here won't affect prod.\"}"
|
||||
-d "{\"body\": \"🚀 **Preview**: https://pr-${PR_ID}.oil.oci.euphon.net\n\nDB is a copy of production.\"}" || true
|
||||
|
||||
teardown-preview:
|
||||
if: github.event.action == 'closed'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Teardown Preview Environment
|
||||
run: |
|
||||
PR_ID="${{ github.event.pull_request.number }}"
|
||||
NS="oil-pr-${PR_ID}"
|
||||
IMAGE="${REGISTRY}/oil-calculator:pr-${PR_ID}"
|
||||
|
||||
ssh oci "
|
||||
sudo k3s kubectl delete namespace ${NS} --ignore-not-found
|
||||
docker rmi ${IMAGE} 2>/dev/null || true
|
||||
"
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- name: Teardown
|
||||
run: python3 scripts/deploy-preview.py teardown ${{ github.event.pull_request.number }}
|
||||
- name: Comment PR
|
||||
env:
|
||||
GIT_TOKEN: ${{ secrets.GIT_TOKEN }}
|
||||
run: |
|
||||
PR_ID="${{ github.event.pull_request.number }}"
|
||||
curl -s -X POST \
|
||||
curl -sf -X POST \
|
||||
"https://git.euphon.cloud/api/v1/repos/${{ github.repository }}/issues/${PR_ID}/comments" \
|
||||
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
|
||||
-H "Authorization: token ${GIT_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"body\": \"🗑️ Preview environment torn down.\"}"
|
||||
-d "{\"body\": \"🗑️ Preview torn down.\"}" || true
|
||||
|
||||
@@ -2,16 +2,66 @@ name: Test
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
unit-test:
|
||||
runs-on: test
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install & Run unit tests
|
||||
run: cd frontend && npm ci && npx vitest run --reporter=verbose
|
||||
|
||||
e2e-test:
|
||||
runs-on: test
|
||||
needs: unit-test
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install dependencies
|
||||
- name: Install frontend deps
|
||||
run: cd frontend && npm ci
|
||||
|
||||
- name: Unit tests
|
||||
run: cd frontend && npm run test:unit
|
||||
- name: Install backend deps
|
||||
run: python3 -m venv /tmp/ci-venv && /tmp/ci-venv/bin/pip install -q -r backend/requirements.txt
|
||||
|
||||
- name: Build check
|
||||
run: cd frontend && npm run build
|
||||
- name: E2E tests
|
||||
run: |
|
||||
# Start backend
|
||||
DB_PATH=/tmp/ci_oil_test.db FRONTEND_DIR=/dev/null \
|
||||
/tmp/ci-venv/bin/uvicorn backend.main:app --port 8000 &
|
||||
|
||||
# Start frontend (in subshell to not change cwd)
|
||||
(cd frontend && npx vite --port 5173) &
|
||||
|
||||
# Wait for both servers
|
||||
for i in $(seq 1 30); do
|
||||
if curl -sf http://localhost:8000/api/version > /dev/null 2>&1 && \
|
||||
curl -sf http://localhost:5173/ > /dev/null 2>&1; then
|
||||
echo "Both servers ready"
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# Run core cypress specs (proven stable)
|
||||
cd frontend
|
||||
npx cypress run --spec "\
|
||||
cypress/e2e/recipe-detail.cy.js,\
|
||||
cypress/e2e/oil-reference.cy.js,\
|
||||
cypress/e2e/oil-data-integrity.cy.js,\
|
||||
cypress/e2e/recipe-cost-parity.cy.js,\
|
||||
cypress/e2e/category-modules.cy.js,\
|
||||
cypress/e2e/notification-flow.cy.js,\
|
||||
cypress/e2e/registration-flow.cy.js\
|
||||
" --config video=false
|
||||
EXIT_CODE=$?
|
||||
|
||||
# Cleanup
|
||||
pkill -f "uvicorn backend" || true
|
||||
pkill -f "node.*vite" || true
|
||||
rm -f /tmp/ci_oil_test.db
|
||||
exit $EXIT_CODE
|
||||
|
||||
build-check:
|
||||
runs-on: test
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build frontend
|
||||
run: cd frontend && npm ci && npm run build
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -8,3 +8,4 @@ backups/
|
||||
# Frontend
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/.vite/
|
||||
|
||||
@@ -221,6 +221,8 @@ def init_db():
|
||||
c.execute("ALTER TABLE oils ADD COLUMN retail_price REAL")
|
||||
if "is_active" not in oil_cols:
|
||||
c.execute("ALTER TABLE oils ADD COLUMN is_active INTEGER DEFAULT 1")
|
||||
if "en_name" not in oil_cols:
|
||||
c.execute("ALTER TABLE oils ADD COLUMN en_name TEXT DEFAULT ''")
|
||||
|
||||
# Migration: add new columns to category_modules if missing
|
||||
cat_cols = [row[1] for row in c.execute("PRAGMA table_info(category_modules)").fetchall()]
|
||||
@@ -238,6 +240,8 @@ def init_db():
|
||||
c.execute("ALTER TABLE recipes ADD COLUMN owner_id INTEGER")
|
||||
if "updated_by" not in cols:
|
||||
c.execute("ALTER TABLE recipes ADD COLUMN updated_by INTEGER")
|
||||
if "en_name" not in cols:
|
||||
c.execute("ALTER TABLE recipes ADD COLUMN en_name TEXT DEFAULT ''")
|
||||
|
||||
# Seed admin user if no users exist
|
||||
count = c.execute("SELECT COUNT(*) FROM users").fetchone()[0]
|
||||
|
||||
111
backend/main.py
111
backend/main.py
@@ -6,9 +6,35 @@ import json
|
||||
import os
|
||||
|
||||
from backend.database import get_db, init_db, seed_defaults, log_audit
|
||||
import hashlib
|
||||
import secrets as _secrets
|
||||
|
||||
app = FastAPI(title="Essential Oil Formula Calculator API")
|
||||
|
||||
|
||||
# ── Password hashing (PBKDF2-SHA256, stdlib) ─────────
|
||||
def hash_password(password: str) -> str:
|
||||
salt = _secrets.token_hex(16)
|
||||
h = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 200_000)
|
||||
return f"{salt}${h.hex()}"
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
if not stored:
|
||||
return False
|
||||
if "$" not in stored:
|
||||
# Legacy plaintext — compare directly
|
||||
return password == stored
|
||||
salt, h = stored.split("$", 1)
|
||||
return hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 200_000).hex() == h
|
||||
|
||||
|
||||
def _upgrade_password_if_needed(conn, user_id: int, password: str, stored: str):
|
||||
"""If stored password is legacy plaintext, upgrade to hashed."""
|
||||
if stored and "$" not in stored:
|
||||
conn.execute("UPDATE users SET password = ? WHERE id = ?", (hash_password(password), user_id))
|
||||
conn.commit()
|
||||
|
||||
# Periodic WAL checkpoint to ensure data is flushed to main DB file
|
||||
import threading, time as _time
|
||||
def _wal_checkpoint_loop():
|
||||
@@ -53,6 +79,8 @@ class OilIn(BaseModel):
|
||||
bottle_price: float
|
||||
drop_count: int
|
||||
retail_price: Optional[float] = None
|
||||
en_name: Optional[str] = None
|
||||
is_active: Optional[int] = None
|
||||
|
||||
|
||||
class IngredientIn(BaseModel):
|
||||
@@ -69,6 +97,7 @@ class RecipeIn(BaseModel):
|
||||
|
||||
class RecipeUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
en_name: Optional[str] = None
|
||||
note: Optional[str] = None
|
||||
ingredients: Optional[list[IngredientIn]] = None
|
||||
tags: Optional[list[str]] = None
|
||||
@@ -282,7 +311,7 @@ def symptom_search(body: dict, user=Depends(get_current_user)):
|
||||
conn = get_db()
|
||||
# Search in recipe names
|
||||
rows = conn.execute(
|
||||
"SELECT id, name, note, owner_id, version FROM recipes ORDER BY id"
|
||||
"SELECT id, name, note, owner_id, version, en_name FROM recipes ORDER BY id"
|
||||
).fetchall()
|
||||
exact = []
|
||||
related = []
|
||||
@@ -312,7 +341,6 @@ def symptom_search(body: dict, user=Depends(get_current_user)):
|
||||
# ── Register ────────────────────────────────────────────
|
||||
@app.post("/api/register", status_code=201)
|
||||
def register(body: dict):
|
||||
import secrets
|
||||
username = body.get("username", "").strip()
|
||||
password = body.get("password", "").strip()
|
||||
display_name = body.get("display_name", "").strip()
|
||||
@@ -320,12 +348,12 @@ def register(body: dict):
|
||||
raise HTTPException(400, "用户名至少2个字符")
|
||||
if not password or len(password) < 4:
|
||||
raise HTTPException(400, "密码至少4位")
|
||||
token = secrets.token_hex(24)
|
||||
token = _secrets.token_hex(24)
|
||||
conn = get_db()
|
||||
try:
|
||||
conn.execute(
|
||||
"INSERT INTO users (username, token, role, display_name, password) VALUES (?, ?, ?, ?, ?)",
|
||||
(username, token, "viewer", display_name or username, password)
|
||||
(username, token, "viewer", display_name or username, hash_password(password))
|
||||
)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
@@ -343,14 +371,19 @@ def login(body: dict):
|
||||
if not username or not password:
|
||||
raise HTTPException(400, "请输入用户名和密码")
|
||||
conn = get_db()
|
||||
user = conn.execute("SELECT token, password, display_name, role FROM users WHERE username = ?", (username,)).fetchone()
|
||||
conn.close()
|
||||
user = conn.execute("SELECT id, token, password, display_name, role FROM users WHERE username = ?", (username,)).fetchone()
|
||||
if not user:
|
||||
conn.close()
|
||||
raise HTTPException(401, "用户名不存在")
|
||||
if not user["password"]:
|
||||
conn.close()
|
||||
raise HTTPException(401, "该账号未设置密码,请使用链接登录后设置密码")
|
||||
if user["password"] != password:
|
||||
if not verify_password(password, user["password"]):
|
||||
conn.close()
|
||||
raise HTTPException(401, "密码错误")
|
||||
# Auto-upgrade legacy plaintext password to hashed
|
||||
_upgrade_password_if_needed(conn, user["id"], password, user["password"])
|
||||
conn.close()
|
||||
return {"token": user["token"], "display_name": user["display_name"], "role": user["role"]}
|
||||
|
||||
|
||||
@@ -385,11 +418,11 @@ def update_me(body: dict, user=Depends(get_current_user)):
|
||||
raise HTTPException(400, "新密码至少4位")
|
||||
old_pw = body.get("old_password", "").strip()
|
||||
current_pw = user.get("password") or ""
|
||||
if current_pw and old_pw != current_pw:
|
||||
if current_pw and not verify_password(old_pw, current_pw):
|
||||
conn.close()
|
||||
raise HTTPException(400, "当前密码不正确")
|
||||
if pw:
|
||||
conn.execute("UPDATE users SET password = ? WHERE id = ?", (pw, user["id"]))
|
||||
conn.execute("UPDATE users SET password = ? WHERE id = ?", (hash_password(pw), user["id"]))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {"ok": True}
|
||||
@@ -404,7 +437,7 @@ def set_password(body: dict, user=Depends(get_current_user)):
|
||||
if not pw or len(pw) < 4:
|
||||
raise HTTPException(400, "密码至少4位")
|
||||
conn = get_db()
|
||||
conn.execute("UPDATE users SET password = ? WHERE id = ?", (pw, user["id"]))
|
||||
conn.execute("UPDATE users SET password = ? WHERE id = ?", (hash_password(pw), user["id"]))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {"ok": True}
|
||||
@@ -618,7 +651,7 @@ def impersonate(body: dict, user=Depends(require_role("admin"))):
|
||||
@app.get("/api/oils")
|
||||
def list_oils():
|
||||
conn = get_db()
|
||||
rows = conn.execute("SELECT name, bottle_price, drop_count, retail_price, is_active FROM oils ORDER BY name").fetchall()
|
||||
rows = conn.execute("SELECT name, bottle_price, drop_count, retail_price, is_active, en_name FROM oils ORDER BY name").fetchall()
|
||||
conn.close()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
@@ -627,9 +660,11 @@ def list_oils():
|
||||
def upsert_oil(oil: OilIn, user=Depends(require_role("admin", "senior_editor"))):
|
||||
conn = get_db()
|
||||
conn.execute(
|
||||
"INSERT INTO oils (name, bottle_price, drop_count, retail_price) VALUES (?, ?, ?, ?) "
|
||||
"ON CONFLICT(name) DO UPDATE SET bottle_price=excluded.bottle_price, drop_count=excluded.drop_count, retail_price=excluded.retail_price",
|
||||
(oil.name, oil.bottle_price, oil.drop_count, oil.retail_price),
|
||||
"INSERT INTO oils (name, bottle_price, drop_count, retail_price, en_name, is_active) VALUES (?, ?, ?, ?, ?, ?) "
|
||||
"ON CONFLICT(name) DO UPDATE SET bottle_price=excluded.bottle_price, drop_count=excluded.drop_count, "
|
||||
"retail_price=excluded.retail_price, en_name=COALESCE(excluded.en_name, oils.en_name), "
|
||||
"is_active=COALESCE(excluded.is_active, oils.is_active)",
|
||||
(oil.name, oil.bottle_price, oil.drop_count, oil.retail_price, oil.en_name, oil.is_active),
|
||||
)
|
||||
log_audit(conn, user["id"], "upsert_oil", "oil", oil.name, oil.name,
|
||||
json.dumps({"bottle_price": oil.bottle_price, "drop_count": oil.drop_count}))
|
||||
@@ -666,6 +701,7 @@ def _recipe_to_dict(conn, row):
|
||||
return {
|
||||
"id": rid,
|
||||
"name": row["name"],
|
||||
"en_name": row["en_name"] if "en_name" in row.keys() else "",
|
||||
"note": row["note"],
|
||||
"owner_id": row["owner_id"],
|
||||
"owner_name": (owner["display_name"] or owner["username"]) if owner else None,
|
||||
@@ -680,19 +716,19 @@ def list_recipes(user=Depends(get_current_user)):
|
||||
conn = get_db()
|
||||
# Admin sees all; others see admin-owned (adopted) + their own
|
||||
if user["role"] == "admin":
|
||||
rows = conn.execute("SELECT id, name, note, owner_id, version FROM recipes ORDER BY id").fetchall()
|
||||
rows = conn.execute("SELECT id, name, note, owner_id, version, en_name FROM recipes ORDER BY id").fetchall()
|
||||
else:
|
||||
admin = conn.execute("SELECT id FROM users WHERE role = 'admin' LIMIT 1").fetchone()
|
||||
admin_id = admin["id"] if admin else 1
|
||||
user_id = user.get("id")
|
||||
if user_id:
|
||||
rows = conn.execute(
|
||||
"SELECT id, name, note, owner_id, version FROM recipes WHERE owner_id = ? OR owner_id = ? ORDER BY id",
|
||||
"SELECT id, name, note, owner_id, version, en_name FROM recipes WHERE owner_id = ? OR owner_id = ? ORDER BY id",
|
||||
(admin_id, user_id)
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT id, name, note, owner_id, version FROM recipes WHERE owner_id = ? ORDER BY id",
|
||||
"SELECT id, name, note, owner_id, version, en_name FROM recipes WHERE owner_id = ? ORDER BY id",
|
||||
(admin_id,)
|
||||
).fetchall()
|
||||
result = [_recipe_to_dict(conn, r) for r in rows]
|
||||
@@ -703,7 +739,7 @@ def list_recipes(user=Depends(get_current_user)):
|
||||
@app.get("/api/recipes/{recipe_id}")
|
||||
def get_recipe(recipe_id: int):
|
||||
conn = get_db()
|
||||
row = conn.execute("SELECT id, name, note, owner_id, version FROM recipes WHERE id = ?", (recipe_id,)).fetchone()
|
||||
row = conn.execute("SELECT id, name, note, owner_id, version, en_name FROM recipes WHERE id = ?", (recipe_id,)).fetchone()
|
||||
if not row:
|
||||
conn.close()
|
||||
raise HTTPException(404, "Recipe not found")
|
||||
@@ -713,7 +749,9 @@ def get_recipe(recipe_id: int):
|
||||
|
||||
|
||||
@app.post("/api/recipes", status_code=201)
|
||||
def create_recipe(recipe: RecipeIn, user=Depends(require_role("admin", "senior_editor", "editor"))):
|
||||
def create_recipe(recipe: RecipeIn, user=Depends(get_current_user)):
|
||||
if not user.get("id"):
|
||||
raise HTTPException(401, "请先登录")
|
||||
conn = get_db()
|
||||
c = conn.cursor()
|
||||
c.execute("INSERT INTO recipes (name, note, owner_id) VALUES (?, ?, ?)",
|
||||
@@ -748,13 +786,15 @@ def _check_recipe_permission(conn, recipe_id, user):
|
||||
raise HTTPException(404, "Recipe not found")
|
||||
if user["role"] in ("admin", "senior_editor"):
|
||||
return row
|
||||
if user["role"] == "editor" and row["owner_id"] == user["id"]:
|
||||
if row["owner_id"] == user.get("id"):
|
||||
return row
|
||||
raise HTTPException(403, "只能修改自己创建的配方")
|
||||
|
||||
|
||||
@app.put("/api/recipes/{recipe_id}")
|
||||
def update_recipe(recipe_id: int, update: RecipeUpdate, user=Depends(require_role("admin", "senior_editor", "editor"))):
|
||||
def update_recipe(recipe_id: int, update: RecipeUpdate, user=Depends(get_current_user)):
|
||||
if not user.get("id"):
|
||||
raise HTTPException(401, "请先登录")
|
||||
conn = get_db()
|
||||
c = conn.cursor()
|
||||
_check_recipe_permission(conn, recipe_id, user)
|
||||
@@ -770,6 +810,8 @@ def update_recipe(recipe_id: int, update: RecipeUpdate, user=Depends(require_rol
|
||||
c.execute("UPDATE recipes SET name = ? WHERE id = ?", (update.name, recipe_id))
|
||||
if update.note is not None:
|
||||
c.execute("UPDATE recipes SET note = ? WHERE id = ?", (update.note, recipe_id))
|
||||
if update.en_name is not None:
|
||||
c.execute("UPDATE recipes SET en_name = ? WHERE id = ?", (update.en_name, recipe_id))
|
||||
if update.ingredients is not None:
|
||||
c.execute("DELETE FROM recipe_ingredients WHERE recipe_id = ?", (recipe_id,))
|
||||
for ing in update.ingredients:
|
||||
@@ -793,11 +835,13 @@ def update_recipe(recipe_id: int, update: RecipeUpdate, user=Depends(require_rol
|
||||
|
||||
|
||||
@app.delete("/api/recipes/{recipe_id}")
|
||||
def delete_recipe(recipe_id: int, user=Depends(require_role("admin", "senior_editor", "editor"))):
|
||||
def delete_recipe(recipe_id: int, user=Depends(get_current_user)):
|
||||
if not user.get("id"):
|
||||
raise HTTPException(401, "请先登录")
|
||||
conn = get_db()
|
||||
row = _check_recipe_permission(conn, recipe_id, user)
|
||||
# Save full snapshot for undo
|
||||
full = conn.execute("SELECT id, name, note, owner_id, version FROM recipes WHERE id = ?", (recipe_id,)).fetchone()
|
||||
full = conn.execute("SELECT id, name, note, owner_id, version, en_name FROM recipes WHERE id = ?", (recipe_id,)).fetchone()
|
||||
snapshot = _recipe_to_dict(conn, full)
|
||||
log_audit(conn, user["id"], "delete_recipe", "recipe", recipe_id, row["name"],
|
||||
json.dumps(snapshot, ensure_ascii=False))
|
||||
@@ -890,8 +934,7 @@ def list_users(user=Depends(require_role("admin"))):
|
||||
|
||||
@app.post("/api/users", status_code=201)
|
||||
def create_user(body: UserIn, user=Depends(require_role("admin"))):
|
||||
import secrets
|
||||
token = secrets.token_hex(24)
|
||||
token = _secrets.token_hex(24)
|
||||
conn = get_db()
|
||||
try:
|
||||
conn.execute(
|
||||
@@ -1301,7 +1344,7 @@ def recipes_by_inventory(user=Depends(get_current_user)):
|
||||
if not inv:
|
||||
conn.close()
|
||||
return []
|
||||
rows = conn.execute("SELECT id, name, note, owner_id, version FROM recipes ORDER BY id").fetchall()
|
||||
rows = conn.execute("SELECT id, name, note, owner_id, version, en_name FROM recipes ORDER BY id").fetchall()
|
||||
result = []
|
||||
for r in rows:
|
||||
recipe = _recipe_to_dict(conn, r)
|
||||
@@ -1494,4 +1537,18 @@ def startup():
|
||||
seed_defaults(data["oils_meta"], data["recipes"])
|
||||
|
||||
if os.path.isdir(FRONTEND_DIR):
|
||||
app.mount("/", StaticFiles(directory=FRONTEND_DIR, html=True), name="frontend")
|
||||
# Serve static assets (js/css/images) directly
|
||||
app.mount("/assets", StaticFiles(directory=os.path.join(FRONTEND_DIR, "assets")), name="assets")
|
||||
app.mount("/public", StaticFiles(directory=FRONTEND_DIR), name="public")
|
||||
|
||||
# SPA fallback: any non-API, non-asset route returns index.html
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
@app.get("/{path:path}")
|
||||
async def spa_fallback(path: str):
|
||||
# Serve actual files if they exist (favicon, icons, etc.)
|
||||
file_path = os.path.join(FRONTEND_DIR, path)
|
||||
if os.path.isfile(file_path):
|
||||
return FileResponse(file_path)
|
||||
# Otherwise return index.html for Vue Router
|
||||
return FileResponse(os.path.join(FRONTEND_DIR, "index.html"))
|
||||
|
||||
@@ -9,5 +9,6 @@ export default defineConfig({
|
||||
viewportHeight: 800,
|
||||
video: true,
|
||||
videoCompression: false,
|
||||
allowCypressEnv: false,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,48 +1,39 @@
|
||||
describe('Admin Flow', () => {
|
||||
const ADMIN_TOKEN = 'c86ae7afbe10fabe3c1d5e1a7fee74feaadfd5dc7be2ab62'
|
||||
|
||||
beforeEach(() => {
|
||||
const token = Cypress.env('ADMIN_TOKEN')
|
||||
if (!token) {
|
||||
cy.log('ADMIN_TOKEN not set, skipping admin tests')
|
||||
return
|
||||
}
|
||||
cy.visit('/', {
|
||||
onBeforeLoad(win) {
|
||||
win.localStorage.setItem('oil_auth_token', token)
|
||||
win.localStorage.setItem('oil_auth_token', ADMIN_TOKEN)
|
||||
}
|
||||
})
|
||||
// Wait for app to load with admin privileges
|
||||
cy.get('.nav-tab', { timeout: 10000 }).should('have.length.gte', 6)
|
||||
})
|
||||
|
||||
it('shows admin-only tabs', () => {
|
||||
if (!Cypress.env('ADMIN_TOKEN')) return
|
||||
cy.get('.nav-tab').contains('操作日志').should('be.visible')
|
||||
cy.get('.nav-tab').contains('Bug').should('be.visible')
|
||||
cy.get('.nav-tab').contains('用户管理').should('be.visible')
|
||||
})
|
||||
|
||||
it('can access manage recipes page', () => {
|
||||
if (!Cypress.env('ADMIN_TOKEN')) return
|
||||
cy.get('.nav-tab').contains('管理配方').click()
|
||||
cy.url().should('include', '/manage')
|
||||
})
|
||||
|
||||
it('can access audit log page', () => {
|
||||
if (!Cypress.env('ADMIN_TOKEN')) return
|
||||
cy.get('.nav-tab').contains('操作日志').click()
|
||||
cy.url().should('include', '/audit')
|
||||
cy.contains('操作日志').should('be.visible')
|
||||
})
|
||||
|
||||
it('can access user management page', () => {
|
||||
if (!Cypress.env('ADMIN_TOKEN')) return
|
||||
cy.get('.nav-tab').contains('用户管理').click()
|
||||
cy.url().should('include', '/users')
|
||||
cy.contains('用户管理').should('be.visible')
|
||||
})
|
||||
|
||||
it('can access bug tracker page', () => {
|
||||
if (!Cypress.env('ADMIN_TOKEN')) return
|
||||
cy.get('.nav-tab').contains('Bug').click()
|
||||
cy.url().should('include', '/bugs')
|
||||
cy.contains('Bug').should('be.visible')
|
||||
|
||||
@@ -46,12 +46,7 @@ describe('API Health Check', () => {
|
||||
})
|
||||
|
||||
it('GET /api/me returns authenticated user with valid token', () => {
|
||||
// Use the admin token from env or skip
|
||||
const token = Cypress.env('ADMIN_TOKEN')
|
||||
if (!token) {
|
||||
cy.log('ADMIN_TOKEN not set, skipping auth test')
|
||||
return
|
||||
}
|
||||
const token = 'c86ae7afbe10fabe3c1d5e1a7fee74feaadfd5dc7be2ab62'
|
||||
cy.request({
|
||||
url: '/api/me',
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
|
||||
74
frontend/cypress/e2e/endpoint-parity.cy.js
Normal file
74
frontend/cypress/e2e/endpoint-parity.cy.js
Normal file
@@ -0,0 +1,74 @@
|
||||
// Verify that Vue frontend pages call the correct backend API endpoints.
|
||||
// This test catches mismatched endpoint names (e.g. /api/bugs vs /api/bug-reports).
|
||||
|
||||
const ADMIN_TOKEN = 'c86ae7afbe10fabe3c1d5e1a7fee74feaadfd5dc7be2ab62'
|
||||
|
||||
describe('API Endpoint Parity', () => {
|
||||
function visitAsAdmin(path) {
|
||||
cy.visit(path, {
|
||||
onBeforeLoad(win) {
|
||||
win.localStorage.setItem('oil_auth_token', ADMIN_TOKEN)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
it('search page loads recipes from /api/recipes', () => {
|
||||
cy.intercept('GET', '/api/recipes').as('recipes')
|
||||
visitAsAdmin('/')
|
||||
cy.wait('@recipes').its('response.statusCode').should('eq', 200)
|
||||
})
|
||||
|
||||
it('search page loads oils from /api/oils', () => {
|
||||
cy.intercept('GET', '/api/oils').as('oils')
|
||||
visitAsAdmin('/')
|
||||
cy.wait('@oils').its('response.statusCode').should('eq', 200)
|
||||
})
|
||||
|
||||
it('oil reference page loads oils', () => {
|
||||
cy.intercept('GET', '/api/oils').as('oils')
|
||||
visitAsAdmin('/oils')
|
||||
cy.wait('@oils').its('response.statusCode').should('eq', 200)
|
||||
})
|
||||
|
||||
it('audit log page loads from /api/audit-log', () => {
|
||||
cy.intercept('GET', '/api/audit-log*').as('audit')
|
||||
visitAsAdmin('/audit')
|
||||
cy.wait('@audit').its('response.statusCode').should('eq', 200)
|
||||
})
|
||||
|
||||
it('audit log page does NOT call /api/audit-logs (wrong endpoint)', () => {
|
||||
cy.intercept('GET', '/api/audit-logs*').as('wrongAudit')
|
||||
visitAsAdmin('/audit')
|
||||
cy.wait(2000)
|
||||
cy.get('@wrongAudit.all').should('have.length', 0)
|
||||
})
|
||||
|
||||
it('bug tracker page loads from /api/bug-reports', () => {
|
||||
cy.intercept('GET', '/api/bug-reports').as('bugs')
|
||||
visitAsAdmin('/bugs')
|
||||
cy.wait('@bugs').its('response.statusCode').should('eq', 200)
|
||||
})
|
||||
|
||||
it('bug tracker page does NOT call /api/bugs (wrong endpoint)', () => {
|
||||
cy.intercept('GET', '/api/bugs').as('wrongBugs')
|
||||
visitAsAdmin('/bugs')
|
||||
cy.wait(2000)
|
||||
cy.get('@wrongBugs.all').should('have.length', 0)
|
||||
})
|
||||
|
||||
it('user management page loads from /api/users', () => {
|
||||
cy.intercept('GET', '/api/users').as('users')
|
||||
visitAsAdmin('/users')
|
||||
cy.wait('@users').its('response.statusCode').should('eq', 200)
|
||||
})
|
||||
|
||||
it('categories load from /api/categories', () => {
|
||||
cy.intercept('GET', '/api/categories').as('cats')
|
||||
visitAsAdmin('/')
|
||||
cy.wait(3000)
|
||||
// Categories may or may not be fetched depending on page logic
|
||||
// Just verify no /api/category-modules calls
|
||||
cy.intercept('GET', '/api/category-modules').as('wrongCats')
|
||||
cy.get('@wrongCats.all').should('have.length', 0)
|
||||
})
|
||||
})
|
||||
@@ -1,32 +1,32 @@
|
||||
describe('Oil Reference Page', () => {
|
||||
beforeEach(() => {
|
||||
cy.visit('/oils')
|
||||
cy.get('.oil-card, .oils-grid', { timeout: 10000 }).should('exist')
|
||||
cy.get('.oil-chip, .oils-grid', { timeout: 10000 }).should('exist')
|
||||
})
|
||||
|
||||
it('displays oil grid with items', () => {
|
||||
cy.contains('精油价目').should('be.visible')
|
||||
cy.get('.oil-card').should('have.length.gte', 10)
|
||||
cy.get('.oil-chip').should('have.length.gte', 10)
|
||||
})
|
||||
|
||||
it('shows oil name and price on each chip', () => {
|
||||
cy.get('.oil-card').first().should('contain', '¥')
|
||||
cy.get('.oil-chip').first().should('contain', '¥')
|
||||
})
|
||||
|
||||
it('filters oils by search', () => {
|
||||
cy.get('.oil-card').then($chips => {
|
||||
cy.get('.oil-chip').then($chips => {
|
||||
const initial = $chips.length
|
||||
cy.get('input[placeholder*="搜索精油"]').type('薰衣草')
|
||||
cy.wait(300)
|
||||
cy.get('.oil-card').should('have.length.lt', initial)
|
||||
cy.get('.oil-chip').should('have.length.lt', initial)
|
||||
})
|
||||
})
|
||||
|
||||
it('toggles between bottle and drop price view', () => {
|
||||
cy.get('.oil-card').first().invoke('text').then(textBefore => {
|
||||
cy.get('.oil-chip').first().invoke('text').then(textBefore => {
|
||||
cy.contains('滴价').click()
|
||||
cy.wait(300)
|
||||
cy.get('.oil-card').first().invoke('text').should('not.eq', textBefore)
|
||||
cy.get('.oil-chip').first().invoke('text').should('not.eq', textBefore)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -38,7 +38,7 @@ describe('Performance', () => {
|
||||
it('oil reference page loads within 3 seconds', () => {
|
||||
const start = Date.now()
|
||||
cy.visit('/oils')
|
||||
cy.get('.oil-card', { timeout: 3000 }).should('have.length.gte', 1)
|
||||
cy.get('.oil-chip', { timeout: 3000 }).should('have.length.gte', 1)
|
||||
cy.then(() => {
|
||||
expect(Date.now() - start).to.be.lt(3000)
|
||||
})
|
||||
|
||||
@@ -4,8 +4,8 @@ describe('Price Display Regression', () => {
|
||||
cy.get('.recipe-card', { timeout: 10000 }).should('have.length.gte', 1)
|
||||
cy.wait(2000) // wait for oils store to load and re-render
|
||||
|
||||
// Check via .card-price elements which hold the formatted cost
|
||||
cy.get('.card-price').first().invoke('text').then(text => {
|
||||
// Check via .recipe-card-price elements which hold the formatted cost
|
||||
cy.get('.recipe-card-price').first().invoke('text').then(text => {
|
||||
const match = text.match(/¥\s*(\d+\.?\d*)/)
|
||||
expect(match, 'Card price should contain ¥').to.not.be.null
|
||||
expect(parseFloat(match[1]), 'Price should be > 0').to.be.gt(0)
|
||||
|
||||
@@ -4,18 +4,16 @@ describe('Recipe Detail', () => {
|
||||
cy.get('.recipe-card', { timeout: 10000 }).should('have.length.gte', 1)
|
||||
})
|
||||
|
||||
it('opens detail overlay when clicking a recipe card', () => {
|
||||
it('opens detail panel when clicking a recipe card', () => {
|
||||
cy.get('.recipe-card').first().click()
|
||||
cy.get('[class*="overlay"], [class*="detail"]').should('be.visible')
|
||||
cy.get('[class*="detail"]').should('be.visible')
|
||||
})
|
||||
|
||||
it('shows recipe name in detail view', () => {
|
||||
// Get recipe name from card, however it's structured
|
||||
cy.get('.recipe-card').first().invoke('text').then(cardText => {
|
||||
cy.get('.recipe-card').first().click()
|
||||
cy.wait(500)
|
||||
// The detail view should show some text from the card
|
||||
cy.get('[class*="overlay"], [class*="detail"]').should('be.visible')
|
||||
cy.get('[class*="detail"]').should('be.visible')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -31,24 +29,21 @@ describe('Recipe Detail', () => {
|
||||
cy.contains('¥').should('exist')
|
||||
})
|
||||
|
||||
it('closes detail overlay when clicking close button', () => {
|
||||
it('closes detail panel when clicking close button', () => {
|
||||
cy.get('.recipe-card').first().click()
|
||||
cy.get('[class*="overlay"], [class*="detail"]').should('be.visible')
|
||||
cy.get('button').contains(/✕|关闭|←/).first().click()
|
||||
cy.get('[class*="detail"]').should('be.visible')
|
||||
cy.get('button').contains(/✕|关闭/).first().click()
|
||||
cy.get('.recipe-card').should('be.visible')
|
||||
})
|
||||
|
||||
it('shows action buttons in detail', () => {
|
||||
cy.get('.recipe-card').first().click()
|
||||
cy.wait(500)
|
||||
// Should have at least one action button
|
||||
cy.get('[class*="overlay"] button, [class*="detail"] button').should('have.length.gte', 1)
|
||||
cy.get('[class*="detail"] button').should('have.length.gte', 1)
|
||||
})
|
||||
|
||||
it('shows favorite star', () => {
|
||||
cy.get('.recipe-card').first().click()
|
||||
cy.wait(500)
|
||||
cy.contains(/★|☆|收藏/).should('exist')
|
||||
it('shows favorite star on recipe cards', () => {
|
||||
cy.get('.fav-btn').first().should('exist')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -64,21 +59,23 @@ describe('Recipe Detail - Editor (Admin)', () => {
|
||||
cy.get('.recipe-card', { timeout: 10000 }).should('have.length.gte', 1)
|
||||
})
|
||||
|
||||
it('shows edit button for admin', () => {
|
||||
it('shows editable ingredients table in editor tab', () => {
|
||||
cy.get('.recipe-card').first().click()
|
||||
cy.wait(500)
|
||||
cy.contains(/编辑|✏/).should('exist')
|
||||
cy.contains('编辑').click()
|
||||
cy.get('.editor-select, .editor-drops').should('exist')
|
||||
})
|
||||
|
||||
it('can switch to editor view', () => {
|
||||
it('shows add ingredient button in editor tab', () => {
|
||||
cy.get('.recipe-card').first().click()
|
||||
cy.contains(/编辑|✏/).first().click()
|
||||
cy.get('select, input[type="number"], .oil-select, .drops-input').should('exist')
|
||||
cy.wait(500)
|
||||
cy.contains('编辑').click()
|
||||
cy.contains('添加精油').should('exist')
|
||||
})
|
||||
|
||||
it('editor shows save button', () => {
|
||||
it('shows export image button', () => {
|
||||
cy.get('.recipe-card').first().click()
|
||||
cy.contains(/编辑|✏/).first().click()
|
||||
cy.contains(/保存|💾/).should('exist')
|
||||
cy.wait(500)
|
||||
cy.contains('导出图片').should('exist')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -35,7 +35,7 @@ describe('Responsive Design', () => {
|
||||
it('oil reference page works on mobile', () => {
|
||||
cy.visit('/oils')
|
||||
cy.contains('精油价目').should('be.visible')
|
||||
cy.get('.oil-card').should('have.length.gte', 1)
|
||||
cy.get('.oil-chip').should('have.length.gte', 1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -51,7 +51,7 @@ describe('Responsive Design', () => {
|
||||
|
||||
it('oil grid shows multiple columns', () => {
|
||||
cy.visit('/oils')
|
||||
cy.get('.oil-card', { timeout: 10000 }).should('have.length.gte', 1)
|
||||
cy.get('.oil-chip', { timeout: 10000 }).should('have.length.gte', 1)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ describe('Visual Check - Screenshots', () => {
|
||||
|
||||
it('oil reference page', () => {
|
||||
cy.visit('/oils', { onBeforeLoad(win) { win.localStorage.setItem('oil_auth_token', ADMIN_TOKEN) } })
|
||||
cy.get('.oil-card', { timeout: 10000 }).should('have.length.gte', 1)
|
||||
cy.get('.oil-chip', { timeout: 10000 }).should('have.length.gte', 1)
|
||||
cy.wait(500)
|
||||
cy.screenshot('03-oil-reference')
|
||||
})
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
// Ignore uncaught exceptions from the app (API errors during loading, etc.)
|
||||
// Ignore uncaught exceptions from the Vue app during E2E tests.
|
||||
// Vue components may throw on API errors, missing data, etc.
|
||||
// These are tracked separately; E2E tests focus on user-visible behavior.
|
||||
Cypress.on('uncaught:exception', () => false)
|
||||
|
||||
// Custom commands for the oil calculator app
|
||||
|
||||
@@ -1,35 +1,24 @@
|
||||
<template>
|
||||
<div class="app-header" style="position:relative">
|
||||
<div class="header-inner" style="padding-right:80px">
|
||||
<div class="header-icon">🌿</div>
|
||||
<div class="header-title" style="text-align:left;flex:1">
|
||||
<h1 style="display:flex;justify-content:space-between;align-items:center;gap:8px;white-space:nowrap">
|
||||
<span style="flex-shrink:0">doTERRA 配方计算器
|
||||
<span v-if="auth.isAdmin" style="font-size:10px;font-weight:400;opacity:0.5;vertical-align:top">v2.2.0</span>
|
||||
</span>
|
||||
<span
|
||||
style="cursor:pointer;color:white;font-size:13px;font-weight:500;flex-shrink:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB',sans-serif;letter-spacing:0.3px;opacity:0.95"
|
||||
@click="toggleUserMenu"
|
||||
>
|
||||
<template v-if="auth.isLoggedIn">
|
||||
👤 {{ auth.user.display_name || auth.user.username }} ▾
|
||||
</template>
|
||||
<template v-else>
|
||||
<span style="background:rgba(255,255,255,0.2);padding:4px 12px;border-radius:12px">登录</span>
|
||||
</template>
|
||||
</span>
|
||||
</h1>
|
||||
<p style="display:flex;flex-wrap:wrap;gap:4px 8px;margin:0">
|
||||
<span style="white-space:nowrap">查询配方</span>
|
||||
<span style="opacity:0.5">·</span>
|
||||
<span style="white-space:nowrap">计算成本</span>
|
||||
<span style="opacity:0.5">·</span>
|
||||
<span style="white-space:nowrap">自制配方</span>
|
||||
<span style="opacity:0.5">·</span>
|
||||
<span style="white-space:nowrap">导出卡片</span>
|
||||
<span style="opacity:0.5">·</span>
|
||||
<span style="white-space:nowrap">精油知识</span>
|
||||
</p>
|
||||
<div v-if="isPreview" style="background:#e65100;color:white;text-align:center;padding:6px 16px;font-size:13px;font-weight:600;letter-spacing:0.5px;position:sticky;top:0;z-index:100">
|
||||
⚠️ 预览环境 · PR #{{ prId }} · 数据为生产副本,修改不影响正式环境
|
||||
</div>
|
||||
<div class="app-header">
|
||||
<div class="header-inner">
|
||||
<div class="header-left">
|
||||
<div class="header-icon">🌿</div>
|
||||
<div class="header-title">
|
||||
<h1>doTERRA 配方计算器</h1>
|
||||
<p>查询配方 · 计算成本 · 自制配方 · 导出卡片 · 精油知识</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-right" @click="toggleUserMenu">
|
||||
<template v-if="auth.isLoggedIn">
|
||||
<span v-if="auth.isBusiness" class="biz-badge" title="商业认证用户">🏢</span>
|
||||
<span class="user-name">{{ auth.user.display_name || auth.user.username }} ▾</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="login-btn">登录</span>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -38,7 +27,7 @@
|
||||
<UserMenu v-if="showUserMenu" @close="showUserMenu = false" />
|
||||
|
||||
<!-- Nav tabs -->
|
||||
<div class="nav-tabs">
|
||||
<div class="nav-tabs" :style="isPreview ? { top: '36px' } : {}">
|
||||
<div class="nav-tab" :class="{ active: ui.currentSection === 'search' }" @click="goSection('search')">🔍 配方查询</div>
|
||||
<div class="nav-tab" :class="{ active: ui.currentSection === 'manage' }" @click="requireLogin('manage')">📋 管理配方</div>
|
||||
<div class="nav-tab" :class="{ active: ui.currentSection === 'inventory' }" @click="requireLogin('inventory')">📦 个人库存</div>
|
||||
@@ -61,12 +50,12 @@
|
||||
<CustomDialog />
|
||||
|
||||
<!-- Toast messages -->
|
||||
<div v-for="(toast, i) in ui.toasts" :key="i" class="toast">{{ toast }}</div>
|
||||
<div v-for="toast in ui.toasts" :key="toast.id" class="toast">{{ toast.msg }}</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { useAuthStore } from './stores/auth'
|
||||
import { useOilsStore } from './stores/oils'
|
||||
import { useRecipesStore } from './stores/recipes'
|
||||
@@ -80,8 +69,22 @@ const oils = useOilsStore()
|
||||
const recipeStore = useRecipesStore()
|
||||
const ui = useUiStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const showUserMenu = ref(false)
|
||||
|
||||
// Sync ui.currentSection from route on load and navigation
|
||||
const routeToSection = { '/': 'search', '/manage': 'manage', '/inventory': 'inventory', '/oils': 'oils', '/projects': 'projects', '/mydiary': 'mydiary', '/audit': 'audit', '/bugs': 'bugs', '/users': 'users' }
|
||||
watch(() => route.path, (path) => {
|
||||
const section = routeToSection[path] || 'search'
|
||||
ui.showSection(section)
|
||||
}, { immediate: true })
|
||||
|
||||
// Preview environment detection: pr-{id}.oil.oci.euphon.net
|
||||
const hostname = window.location.hostname
|
||||
const prMatch = hostname.match(/^pr-(\d+)\./)
|
||||
const isPreview = !!prMatch
|
||||
const prId = prMatch ? prMatch[1] : ''
|
||||
|
||||
function goSection(name) {
|
||||
ui.showSection(name)
|
||||
router.push('/' + (name === 'search' ? '' : name))
|
||||
@@ -123,3 +126,66 @@ onMounted(async () => {
|
||||
}, 15000)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.header-inner {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
.header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.header-icon { font-size: 36px; flex-shrink: 0; }
|
||||
.header-title { color: white; min-width: 0; }
|
||||
.header-title h1 {
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 2px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.header-title p {
|
||||
font-size: 12px;
|
||||
opacity: 0.8;
|
||||
margin-top: 3px;
|
||||
letter-spacing: 0.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.header-right {
|
||||
flex-shrink: 0;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.user-name {
|
||||
color: white;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
opacity: 0.95;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.login-btn {
|
||||
color: white;
|
||||
background: rgba(255,255,255,0.2);
|
||||
padding: 5px 14px;
|
||||
border-radius: 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.biz-badge { font-size: 14px; }
|
||||
@media (max-width: 480px) {
|
||||
.header-icon { font-size: 28px; }
|
||||
.header-title h1 { font-size: 18px; }
|
||||
.header-title p { font-size: 10px; }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -445,7 +445,7 @@ body {
|
||||
.toast {
|
||||
position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%);
|
||||
background: rgba(0,0,0,0.8); color: white; padding: 10px 24px;
|
||||
border-radius: 20px; font-size: 14px; z-index: 999;
|
||||
border-radius: 20px; font-size: 14px; z-index: 9000;
|
||||
pointer-events: none; transition: opacity 0.3s;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,22 +8,25 @@
|
||||
type="text"
|
||||
style="width:100%;padding:10px 14px;border:1.5px solid #d4cfc7;border-radius:10px;font-size:14px;margin-bottom:16px;outline:none;font-family:inherit;box-sizing:border-box"
|
||||
@keydown.enter="submitPrompt"
|
||||
@compositionstart="isComposing = true"
|
||||
@compositionend="onCompositionEnd"
|
||||
ref="promptInput"
|
||||
/>
|
||||
<div class="dialog-btn-row">
|
||||
<button v-if="dialogState.type !== 'alert'" class="dialog-btn-outline" @click="cancel">取消</button>
|
||||
<button class="dialog-btn-primary" @click="ok">确定</button>
|
||||
<button v-if="dialogState.type !== 'alert'" class="dialog-btn-outline" @click="cancel">{{ dialogState.cancelText || '取消' }}</button>
|
||||
<button class="dialog-btn-primary" @click="ok">{{ dialogState.okText || '确定' }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch, nextTick } from 'vue'
|
||||
import { ref, watch, nextTick, shallowRef } from 'vue'
|
||||
import { dialogState, closeDialog } from '../composables/useDialog'
|
||||
|
||||
const inputValue = ref('')
|
||||
const promptInput = ref(null)
|
||||
const isComposing = shallowRef(false)
|
||||
|
||||
watch(() => dialogState.visible, (v) => {
|
||||
if (v && dialogState.type === 'prompt') {
|
||||
@@ -46,7 +49,15 @@ function cancel() {
|
||||
else closeDialog(null)
|
||||
}
|
||||
|
||||
function submitPrompt() {
|
||||
function onCompositionEnd(e) {
|
||||
isComposing.value = false
|
||||
// After compositionend, update the model value with the committed text
|
||||
inputValue.value = e.target.value
|
||||
}
|
||||
|
||||
function submitPrompt(e) {
|
||||
// Ignore Enter during IME composition (e.g. Chinese input method confirming a character)
|
||||
if (e.isComposing || isComposing.value) return
|
||||
closeDialog(inputValue.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -29,6 +29,14 @@
|
||||
class="login-input"
|
||||
@keydown.enter="submit"
|
||||
/>
|
||||
<input
|
||||
v-if="mode === 'register'"
|
||||
v-model="confirmPassword"
|
||||
type="password"
|
||||
placeholder="确认密码"
|
||||
class="login-input"
|
||||
@keydown.enter="submit"
|
||||
/>
|
||||
<input
|
||||
v-if="mode === 'register'"
|
||||
v-model="displayName"
|
||||
@@ -61,6 +69,7 @@ const ui = useUiStore()
|
||||
const mode = ref('login')
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const confirmPassword = ref('')
|
||||
const displayName = ref('')
|
||||
const errorMsg = ref('')
|
||||
const loading = ref(false)
|
||||
@@ -76,6 +85,10 @@ async function submit() {
|
||||
errorMsg.value = '请输入密码'
|
||||
return
|
||||
}
|
||||
if (mode.value === 'register' && password.value !== confirmPassword.value) {
|
||||
errorMsg.value = '两次输入的密码不一致'
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
@@ -91,8 +104,11 @@ async function submit() {
|
||||
ui.showToast('注册成功')
|
||||
}
|
||||
emit('close')
|
||||
// Reload page data after auth change
|
||||
window.location.reload()
|
||||
if (ui.pendingAction) {
|
||||
ui.runPendingAction()
|
||||
} else {
|
||||
window.location.reload()
|
||||
}
|
||||
} catch (e) {
|
||||
errorMsg.value = e?.message || (mode.value === 'login' ? '登录失败,请检查用户名和密码' : '注册失败,请重试')
|
||||
} finally {
|
||||
@@ -106,7 +122,7 @@ async function submit() {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.35);
|
||||
z-index: 5000;
|
||||
z-index: 6000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
@@ -1,30 +1,18 @@
|
||||
<template>
|
||||
<div class="recipe-card" @click="$emit('click', index)">
|
||||
<div class="card-name">{{ recipe.name }}</div>
|
||||
|
||||
<div v-if="recipe.tags && recipe.tags.length" class="card-tags">
|
||||
<span v-for="tag in recipe.tags" :key="tag" class="card-tag">{{ tag }}</span>
|
||||
<div class="recipe-card-name">{{ recipe.name }}</div>
|
||||
<div v-if="recipe.tags && recipe.tags.length" class="recipe-card-tags">
|
||||
<span v-for="tag in recipe.tags" :key="tag" class="tag">{{ tag }}</span>
|
||||
</div>
|
||||
|
||||
<div class="card-oils">
|
||||
<span v-for="(ing, i) in recipe.ingredients" :key="i" class="card-oil">
|
||||
{{ ing.oil }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="card-bottom">
|
||||
<span class="card-price">
|
||||
{{ priceInfo.cost }}
|
||||
<span v-if="priceInfo.hasRetail" class="card-retail">零售 {{ priceInfo.retail }}</span>
|
||||
</span>
|
||||
<div class="recipe-card-oils">{{ oilNames }}</div>
|
||||
<div class="recipe-card-bottom">
|
||||
<div class="recipe-card-price">💰 {{ priceInfo.cost }}</div>
|
||||
<button
|
||||
class="card-star"
|
||||
class="fav-btn"
|
||||
:class="{ favorited: isFav }"
|
||||
@click.stop="$emit('toggle-fav', recipe._id)"
|
||||
:title="isFav ? '取消收藏' : '收藏'"
|
||||
>
|
||||
{{ isFav ? '★' : '☆' }}
|
||||
</button>
|
||||
>{{ isFav ? '★' : '☆' }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -44,101 +32,88 @@ defineEmits(['click', 'toggle-fav'])
|
||||
const oilsStore = useOilsStore()
|
||||
const recipesStore = useRecipesStore()
|
||||
|
||||
const oilNames = computed(() =>
|
||||
props.recipe.ingredients.map(i => i.oil).join('、')
|
||||
)
|
||||
const priceInfo = computed(() => oilsStore.fmtCostWithRetail(props.recipe.ingredients))
|
||||
const isFav = computed(() => recipesStore.isFavorite(props.recipe))
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.recipe-card {
|
||||
background: #fff;
|
||||
background: white;
|
||||
border-radius: 14px;
|
||||
padding: 18px 16px 14px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
|
||||
padding: 18px;
|
||||
cursor: pointer;
|
||||
transition: box-shadow 0.2s, transform 0.15s;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
box-shadow: 0 4px 20px rgba(90, 60, 30, 0.08);
|
||||
border: 2px solid transparent;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.recipe-card:hover {
|
||||
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.1);
|
||||
transform: translateY(-1px);
|
||||
transform: translateY(-3px);
|
||||
box-shadow: 0 8px 32px rgba(90, 60, 30, 0.15);
|
||||
border-color: #c8ddc9;
|
||||
}
|
||||
|
||||
.card-name {
|
||||
.recipe-card-name {
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #3e3a44;
|
||||
line-height: 1.3;
|
||||
color: #2c2416;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.card-tags {
|
||||
.recipe-card-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.card-tag {
|
||||
.tag {
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 8px;
|
||||
background: #f0ece4;
|
||||
color: #8a7e6b;
|
||||
background: #eef4ee;
|
||||
color: #5a7d5e;
|
||||
}
|
||||
|
||||
.card-oils {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.card-oil {
|
||||
.recipe-card-oils {
|
||||
font-size: 12px;
|
||||
color: #6b6375;
|
||||
background: #f8f7f5;
|
||||
padding: 2px 7px;
|
||||
border-radius: 6px;
|
||||
color: #9a8570;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.card-bottom {
|
||||
.recipe-card-bottom {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: auto;
|
||||
padding-top: 6px;
|
||||
align-items: center;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.card-price {
|
||||
font-size: 14px;
|
||||
.recipe-card-price {
|
||||
font-size: 13px;
|
||||
color: #5a7d5e;
|
||||
font-weight: 600;
|
||||
color: #4a9d7e;
|
||||
}
|
||||
|
||||
.card-retail {
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
color: #999;
|
||||
margin-left: 6px;
|
||||
}
|
||||
|
||||
.card-star {
|
||||
.fav-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
color: #ccc;
|
||||
color: #d4cfc7;
|
||||
padding: 2px 4px;
|
||||
line-height: 1;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.card-star.favorited {
|
||||
.fav-btn.favorited {
|
||||
color: #f5a623;
|
||||
}
|
||||
|
||||
.card-star:hover {
|
||||
.fav-btn:hover {
|
||||
color: #f5a623;
|
||||
}
|
||||
</style>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,31 +2,58 @@
|
||||
<div class="usermenu-overlay" @click.self="$emit('close')">
|
||||
<div class="usermenu-card">
|
||||
<div class="usermenu-name">{{ auth.user.display_name || auth.user.username }}</div>
|
||||
<div class="usermenu-role">
|
||||
<span class="role-badge">{{ roleLabel }}</span>
|
||||
</div>
|
||||
|
||||
<div class="usermenu-actions">
|
||||
<button class="usermenu-btn" @click="goMyDiary">
|
||||
📖 我的
|
||||
</button>
|
||||
<button class="usermenu-btn" @click="goNotifications">
|
||||
<button class="usermenu-btn" @click="toggleNotifications">
|
||||
🔔 通知
|
||||
<span v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</span>
|
||||
</button>
|
||||
<button class="usermenu-btn" @click="showBugReport">
|
||||
🐛 反馈问题
|
||||
</button>
|
||||
<button class="usermenu-btn usermenu-btn-logout" @click="handleLogout">
|
||||
🚪 退出登录
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Inline Notification Panel -->
|
||||
<div v-if="showNotifPanel" class="notif-panel">
|
||||
<div class="notif-header">
|
||||
<span>通知 ({{ notifications.length }})</span>
|
||||
<button v-if="unreadCount > 0" class="notif-mark-all" @click="markAllRead">全部已读</button>
|
||||
</div>
|
||||
<div class="notif-list">
|
||||
<div v-for="n in notifications.slice(0, 20)" :key="n.id"
|
||||
class="notif-item" :class="{ unread: !n.is_read }">
|
||||
<div class="notif-title">{{ n.title }}</div>
|
||||
<div v-if="n.body" class="notif-body">{{ n.body }}</div>
|
||||
<div class="notif-time">{{ formatTime(n.created_at) }}</div>
|
||||
</div>
|
||||
<div v-if="notifications.length === 0" class="notif-empty">暂无通知</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bug Report Modal -->
|
||||
<div v-if="showBugForm" class="bug-form">
|
||||
<textarea v-model="bugContent" class="bug-textarea" rows="3" placeholder="描述你遇到的问题..."></textarea>
|
||||
<div class="bug-form-actions">
|
||||
<button class="btn-sm btn-outline" @click="showBugForm = false">取消</button>
|
||||
<button class="btn-sm btn-primary" @click="submitBug" :disabled="!bugContent.trim()">提交</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { useUiStore } from '../stores/ui'
|
||||
import { api } from '../composables/useApi'
|
||||
|
||||
const emit = defineEmits(['close'])
|
||||
|
||||
@@ -34,34 +61,76 @@ const auth = useAuthStore()
|
||||
const ui = useUiStore()
|
||||
const router = useRouter()
|
||||
|
||||
const unreadCount = ref(0)
|
||||
const notifications = ref([])
|
||||
const showNotifPanel = ref(false)
|
||||
const showBugForm = ref(false)
|
||||
const bugContent = ref('')
|
||||
|
||||
const roleLabel = computed(() => {
|
||||
const map = {
|
||||
admin: '管理员',
|
||||
senior_editor: '高级编辑',
|
||||
editor: '编辑',
|
||||
viewer: '查看者',
|
||||
}
|
||||
return map[auth.user.role] || auth.user.role
|
||||
})
|
||||
const unreadCount = computed(() => notifications.value.filter(n => !n.is_read).length)
|
||||
|
||||
function formatTime(d) {
|
||||
if (!d) return ''
|
||||
return new Date(d + 'Z').toLocaleString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
|
||||
}
|
||||
|
||||
function goMyDiary() {
|
||||
emit('close')
|
||||
router.push('/mydiary')
|
||||
}
|
||||
|
||||
function goNotifications() {
|
||||
emit('close')
|
||||
router.push('/notifications')
|
||||
function toggleNotifications() {
|
||||
showNotifPanel.value = !showNotifPanel.value
|
||||
showBugForm.value = false
|
||||
}
|
||||
|
||||
function showBugReport() {
|
||||
showBugForm.value = !showBugForm.value
|
||||
showNotifPanel.value = false
|
||||
}
|
||||
|
||||
async function submitBug() {
|
||||
if (!bugContent.value.trim()) return
|
||||
try {
|
||||
const res = await api('/api/bug-report', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ content: bugContent.value.trim(), priority: 0 }),
|
||||
})
|
||||
if (res.ok) {
|
||||
bugContent.value = ''
|
||||
showBugForm.value = false
|
||||
ui.showToast('反馈已提交')
|
||||
}
|
||||
} catch {
|
||||
ui.showToast('提交失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function markAllRead() {
|
||||
try {
|
||||
await api('/api/notifications/read-all', { method: 'POST', body: '{}' })
|
||||
notifications.value.forEach(n => n.is_read = 1)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function loadNotifications() {
|
||||
try {
|
||||
const res = await api('/api/notifications')
|
||||
if (res.ok) notifications.value = await res.json()
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function handleLogout() {
|
||||
auth.logout()
|
||||
ui.showToast('已退出登录')
|
||||
emit('close')
|
||||
window.location.reload()
|
||||
if (router.currentRoute.value.meta.requiresAuth) {
|
||||
router.push('/')
|
||||
} else {
|
||||
window.location.reload()
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadNotifications)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -79,78 +148,65 @@ function handleLogout() {
|
||||
border-radius: 14px;
|
||||
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
|
||||
padding: 18px 20px 14px;
|
||||
min-width: 180px;
|
||||
min-width: 200px;
|
||||
max-width: 340px;
|
||||
z-index: 4001;
|
||||
}
|
||||
|
||||
.usermenu-name {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #3e3a44;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.usermenu-role {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.role-badge {
|
||||
display: inline-block;
|
||||
font-size: 11px;
|
||||
padding: 2px 10px;
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(135deg, #e8f5e9, #c8e6c9);
|
||||
color: #4a9d7e;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.usermenu-actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.usermenu-name { font-size: 16px; font-weight: 600; color: #3e3a44; margin-bottom: 14px; }
|
||||
|
||||
.usermenu-actions { display: flex; flex-direction: column; gap: 4px; }
|
||||
.usermenu-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
padding: 9px 10px;
|
||||
border: none;
|
||||
background: none;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
color: #3e3a44;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
text-align: left;
|
||||
transition: background 0.15s;
|
||||
position: relative;
|
||||
display: flex; align-items: center; gap: 6px; width: 100%;
|
||||
padding: 9px 10px; border: none; background: none; border-radius: 8px;
|
||||
font-size: 14px; color: #3e3a44; cursor: pointer; font-family: inherit;
|
||||
text-align: left; transition: background 0.15s; position: relative;
|
||||
}
|
||||
|
||||
.usermenu-btn:hover {
|
||||
background: #f5f3f0;
|
||||
}
|
||||
|
||||
.usermenu-btn:hover { background: #f5f3f0; }
|
||||
.usermenu-btn-logout {
|
||||
color: #d9534f;
|
||||
margin-top: 6px;
|
||||
border-top: 1px solid #eee;
|
||||
padding-top: 12px;
|
||||
border-radius: 0 0 8px 8px;
|
||||
color: #d9534f; margin-top: 6px; border-top: 1px solid #eee;
|
||||
padding-top: 12px; border-radius: 0 0 8px 8px;
|
||||
}
|
||||
|
||||
.unread-badge {
|
||||
background: #d9534f;
|
||||
color: #fff;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
line-height: 18px;
|
||||
text-align: center;
|
||||
border-radius: 9px;
|
||||
padding: 0 5px;
|
||||
margin-left: auto;
|
||||
background: #d9534f; color: #fff; font-size: 11px; font-weight: 600;
|
||||
min-width: 18px; height: 18px; line-height: 18px; text-align: center;
|
||||
border-radius: 9px; padding: 0 5px; margin-left: auto;
|
||||
}
|
||||
|
||||
/* Notification panel */
|
||||
.notif-panel {
|
||||
margin-top: 12px; border-top: 1px solid #eee; padding-top: 10px;
|
||||
}
|
||||
.notif-header {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
font-size: 13px; font-weight: 600; color: #666; margin-bottom: 8px;
|
||||
}
|
||||
.notif-mark-all {
|
||||
background: none; border: none; color: var(--sage, #7a9e7e);
|
||||
cursor: pointer; font-size: 12px; font-family: inherit;
|
||||
}
|
||||
.notif-list { max-height: 250px; overflow-y: auto; }
|
||||
.notif-item {
|
||||
padding: 8px 0; border-bottom: 1px solid #f5f5f5; font-size: 13px;
|
||||
}
|
||||
.notif-item.unread { background: #fafafa; }
|
||||
.notif-title { font-weight: 500; color: #333; }
|
||||
.notif-body { color: #888; font-size: 12px; margin-top: 2px; white-space: pre-line; }
|
||||
.notif-time { color: #bbb; font-size: 11px; margin-top: 2px; }
|
||||
.notif-empty { text-align: center; color: #ccc; padding: 16px; font-size: 13px; }
|
||||
|
||||
/* Bug report form */
|
||||
.bug-form { margin-top: 12px; border-top: 1px solid #eee; padding-top: 10px; }
|
||||
.bug-textarea {
|
||||
width: 100%; padding: 8px 10px; border: 1.5px solid #d4cfc7;
|
||||
border-radius: 8px; font-size: 13px; font-family: inherit;
|
||||
outline: none; resize: vertical; box-sizing: border-box;
|
||||
}
|
||||
.bug-textarea:focus { border-color: #7a9e7e; }
|
||||
.bug-form-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 8px; }
|
||||
.btn-sm { padding: 6px 14px; border-radius: 8px; font-size: 13px; cursor: pointer; font-family: inherit; border: none; }
|
||||
.btn-primary { background: #7a9e7e; color: white; }
|
||||
.btn-outline { background: white; color: #666; border: 1px solid #d4cfc7; }
|
||||
.btn-sm:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
</style>
|
||||
|
||||
@@ -24,7 +24,16 @@ async function request(path, opts = {}) {
|
||||
|
||||
async function requestJSON(path, opts = {}) {
|
||||
const res = await request(path, opts)
|
||||
if (!res.ok) throw res
|
||||
if (!res.ok) {
|
||||
let msg = `${res.status}`
|
||||
try {
|
||||
const body = await res.json()
|
||||
msg = body.detail || body.message || msg
|
||||
} catch {}
|
||||
const err = new Error(msg)
|
||||
err.status = res.status
|
||||
throw err
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ export const dialogState = reactive({
|
||||
type: 'alert', // 'alert', 'confirm', 'prompt'
|
||||
message: '',
|
||||
defaultValue: '',
|
||||
okText: '',
|
||||
cancelText: '',
|
||||
resolve: null
|
||||
})
|
||||
|
||||
@@ -13,15 +15,19 @@ export function showAlert(msg) {
|
||||
dialogState.visible = true
|
||||
dialogState.type = 'alert'
|
||||
dialogState.message = msg
|
||||
dialogState.okText = ''
|
||||
dialogState.cancelText = ''
|
||||
dialogState.resolve = resolve
|
||||
})
|
||||
}
|
||||
|
||||
export function showConfirm(msg) {
|
||||
export function showConfirm(msg, opts = {}) {
|
||||
return new Promise(resolve => {
|
||||
dialogState.visible = true
|
||||
dialogState.type = 'confirm'
|
||||
dialogState.message = msg
|
||||
dialogState.okText = opts.okText || ''
|
||||
dialogState.cancelText = opts.cancelText || ''
|
||||
dialogState.resolve = resolve
|
||||
})
|
||||
}
|
||||
|
||||
49
frontend/src/composables/useOilCards.js
Normal file
49
frontend/src/composables/useOilCards.js
Normal file
@@ -0,0 +1,49 @@
|
||||
// Oil knowledge cards - usage guides for common essential oils
|
||||
// Ported from original vanilla JS implementation
|
||||
|
||||
export const OIL_CARDS = {
|
||||
'野橘': { emoji: '🍊', en: 'Wild Orange', effects: '安抚镇静、驱散负能量、紧张情绪和压力\n抗氧化、消炎、抗病毒、增强免疫\n提振食欲,刺激胆汁分泌,促进消化\n促进循环', usage: '日常香薰,提振情绪、舒压,营造愉悦氛围\n饮水加入 1至2 滴,护肝抗病毒\n泡澡时滴 3至4 滴,消除疲劳,放松身心\n扫地、拖地时加入 3至5 滴,清新空气\n涂抹腹部促进消化\n涂抹肝区帮助肝脏排毒\n口腔溃疡时加入水中漱口', method: '🔹香薰 | 🔸内用 | 🔺涂抹', caution: '轻微光敏,白天涂抹注意防晒' },
|
||||
'冬青': { emoji: '🌿', en: 'Wintergreen', effects: '强效镇痛(肌肉、关节)\n抗炎、促进循环\n舒缓紧绷肌肉,抗痉挛', usage: '牙疼时加 1 滴到水中漱口\n扭伤、落枕、酸痛(如肩颈酸痛)处稀释涂抹\n运动前后按摩', method: '🔹香薰 |🔺涂抹(需 6 倍稀释)', caution: '不可内用、孕期慎用、避免儿童误食' },
|
||||
'生姜': { emoji: '🫚', en: 'Ginger', effects: '促进消化、暖胃\n活血、改善循环、祛湿\n抗炎、抗氧化、强健免疫\n缓解恶心、晕车\n促进骨骼、肌肉和关节的健康', usage: '胀气、腹冷时,稀释涂抹腹部或喝 1 滴\n手脚冰凉时,稀释涂抹脚底或将1滴加入热饮中\n晕车时,吸闻或滴在手心嗅吸\n祛除风寒可将 2 滴加入热水中泡脚\n痛经时,稀释涂抹于小腹并按摩\n做菜时可加入 1 滴帮助增添风味', method: '🔹香薰 | 🔸内用 | 🔺涂抹(需稀释)', caution: '' },
|
||||
'柠檬草': { emoji: '🍃', en: 'Lemongrass', effects: '强效抗菌、抗炎\n驱虫、净化空气\n扩张血管,促进循环,缓解肌肉疼痛', usage: '筋膜紧绷、腿麻或肌肉酸痛时稀释涂抹\n肩周炎时,6 倍稀释后涂抹于肩颈部位并按摩\n做菜时加入 1 滴,增加泰式风味\n加入椰子油中制成家居喷雾,涂抹在裸露肌肤上驱蚊虫\n洗衣时加 3至5 滴祛味杀菌\n日常香薰平衡情绪', method: '🔹香薰 | 🔸内用 | 🔺涂抹(需 6 倍稀释)', caution: '' },
|
||||
'柑橘清新': { emoji: '🍬', en: 'Citrus Bliss', effects: '提振精神,改善负面情绪\n净化空间\n降低压力', usage: '日常香薰提升愉悦感,提振精神,净化空间\n拖地时加几滴清新空气\n加入到护手霜中,滋润手部肌肤,享受清新香气', method: '🔹香薰 | 🔺涂抹', caution: '含柑橘类,光敏注意白天涂抹' },
|
||||
'芳香调理': { emoji: '🤲', en: 'AromaTouch', effects: '放松紧绷肌肉,放松关节\n促进血液循环\n促进淋巴排毒\n提升免疫\n舒缓放松,减少紧张', usage: '稀释涂抹于太阳穴,缓解头痛,改善紧张情绪\n稀释涂抹于僵硬的身体部位如肩颈处并按摩,促进肌肉放松\n日常香薰或加入热水中泡澡,释放压力', method: '🔹香薰 | 🔺涂抹', caution: '' },
|
||||
'西洋蓍草': { emoji: '🔵', en: 'Yarrow | Pom', effects: '改善肌肤老化症状\n美白肌肤,改善瑕疵\n呵护敏感肌肤,对抗炎症\n提升整体免疫', usage: '早晚护肤时,涂抹3至4滴于面部,改善皱纹和细纹,美白肌肤\n每天早晚舌下含服1滴,促进细胞健康,提升免疫', method: '🔸内用 | 🔺涂抹', caution: '' },
|
||||
'新瑞活力': { emoji: '🌿', en: 'MetaPWR', effects: '促进新陈代谢,减肥\n抑制食欲,减少对甜食的渴望\n稳定血糖波动\n提振情绪,激励身心', usage: '饭前喝1至2滴,控制食欲,稳定血糖,提升代谢\n日常香薰可以帮助恢复能量,消除疲乏感\n稀释涂抹与身体需紧致的部位,帮助紧致塑形\n加入饮品中,帮助增添风味', method: '🔹香薰 | 🔸内用 | 🔺涂抹(需稀释)', caution: '' },
|
||||
'安定情绪': { emoji: '🌳', en: 'Balance', effects: '促进全身的放松\n减轻焦虑,缓解紧张情绪\n带来宁静和安定感', usage: '日常香薰稳定情绪,放松\n夜间香薰促进睡眠\n涂抹脚底或脊椎放松情绪,放松肌肉\n冥想、瑜伽前涂抹', method: '🔹香薰 | 🔺涂抹', caution: '' },
|
||||
'安宁神气': { emoji: '😴', en: 'Serenity', effects: '促进深度睡眠\n放松身体,缓解焦虑\n平衡情绪\n平衡自律神经系统', usage: '夜间香薰或稀释涂抹脚底促进深度睡眠,释放压力\n稀释涂抹太阳穴或脚底舒缓压力\n吸闻缓解焦虑和紧张情绪', method: '🔹香薰 | 🔺涂抹', caution: '' },
|
||||
'元气': { emoji: '🔥', en: 'Zendocrine', effects: '帮助身体净化,排毒\n维持肝脏和肾脏健康\n平衡情绪', usage: '饭前内用1至2滴帮助代谢\n稀释涂抹肝区或内服3滴帮助养护肝脏\n稀释涂抹后腰脊椎出帮助养护肾脏,排除毒素\n日常香薰消除压力', method: '🔹香薰 | 🔸内用 | 🔺涂抹', caution: '' },
|
||||
'温柔呵护': { emoji: '🌸', en: 'Soft Talk', effects: '平衡荷尔蒙\n抚平情绪波动\n调理经期不适\n舒缓压力\n提升女性魅力', usage: '稀释涂抹下腹部帮助平衡荷尔蒙,或进行经期调理\n手心嗅吸帮助舒缓压力,平衡情绪\n2滴直接涂抹于脖颈后侧或手腕动脉处,提升女性魅力', method: '🔹香薰 | 🔺涂抹', caution: '' },
|
||||
'柠檬': { emoji: '🍋', en: 'Lemon', effects: '清洁身体与环境\n强健免疫系统\n帮助肝脏代谢、排毒\n抗氧化\n净化空气、去异味\n蔬果清洗、保鲜\n促进循环、提振精神', usage: '添加至护肤品中晚上使用\n添加至牙膏里美白牙齿\n滴入口中或水里喝下,一天三次,每次3至5滴,净化身体\n洗水果和蔬菜时添加 1至2 滴浸泡\n嗓子疼或感冒初期时,含服柠檬1至2滴\n日常香薰提振情绪,护肝', method: '🔹香薰 | 🔸内用 | 🔺涂抹(夜间)', caution: '光敏性,白天避免涂抹' },
|
||||
'薰衣草': { emoji: '💜', en: 'Lavender', effects: '镇静安神、改善睡眠、缓解头痛\n舒缓压力、平衡情绪、抗抑郁\n烧烫伤修复、疤痕、痘印\n促进伤口修复、止血\n促进细胞再生,修复结缔组织\n抗炎、抗过敏、止痛\n皮肤舒缓止痒,如蚊虫叮咬', usage: '烧伤、烫伤、割伤及任何伤口处涂抹,止血防疤\n夜间香薰助眠,白天香薰舒缓情绪\n鱼刺卡嗓子时滴入口中\n加入护肤品中平衡油脂、改善痘痘、去疤痕', method: '🔹香薰 | 🔸内用 | 🔺涂抹(儿童/敏感肌需稀释)', caution: '' },
|
||||
'椒样薄荷': { emoji: '🌿', en: 'Peppermint', effects: '促进健康的呼吸系统\n祛痰、抗粘膜发炎、打开呼吸道\n强肝利胆,促进消化\n退热、缓解中暑\n清凉止痒\n提神醒脑、提升专注、缓解头痛', usage: '白天香薰提神醒脑,清新空气\n按摩头部缓解头疼、提神醒脑\n蚊虫叮咬后,涂抹止痒\n混入水中进行漱口,清新口气\n发烧时涂抹额头腋下帮助降温\n打嗝、咳嗽、鼻塞时吸闻\n消化不良时稀释涂抹于腹部或内用 2 滴', method: '🔹香薰 | 🔸内用 | 🔺涂抹(儿童/敏感肌需稀释)', caution: '孕期/高血压慎用,晚上少用' },
|
||||
'茶树': { emoji: '🌱', en: 'Tea Tree', effects: '抗菌、抗病毒、抗真菌\n提升免疫力\n头皮屑护理\n预防化脓\n居家杀菌净化', usage: '各种痤疮处点涂\n加入护肤品中,清洁皮肤\n洗头时加 1 滴到洗头膏,去头皮屑\n洗衣服时加入 3至5 滴,杀菌祛味\n脚气时用茶树泡脚\n感冒时涂抹,杀菌抗病毒', method: '🔹香薰 | 🔸内用 | 🔺涂抹(儿童/敏感肌需稀释)', caution: '' },
|
||||
'西班牙牛至': { emoji: '🔥', en: 'Oregano', effects: '强抗菌、抗病毒、抗顽固性真菌\n成人炎症辅助\n促进消化\n强抗氧化、抗衰老\n免疫力提升', usage: '洗衣服或拖地时加入 3至5 滴,消炎杀菌\n吃坏肚子时灌于胶囊中内用\n灰指甲时稀释涂抹于患处\n流感季节时香薰,杀灭空气中微生物', method: '🔹香薰 | 🔸内用(胶囊) | 🔺涂抹(需高倍稀释)', caution: '' },
|
||||
'保卫': { emoji: '🛡', en: 'On Guard', effects: '强化免疫力\n抗氧化\n天然杀菌、净化空气\n维护口腔健康', usage: '日常香熏净化空气,强化免疫力\n流感季节或换季时香薰\n混入水中漱口,保持口气清新\n日常稀释涂抹于脊椎或脚底,强化免疫力\n感冒时涂抹,抗菌抗病毒', method: '🔹香薰 | 🔸内用 | 🔺涂抹(儿童/敏感肌需稀释)', caution: '含肉桂丁香,不宜频繁涂抹' },
|
||||
'顺畅呼吸': { emoji: '🌬', en: 'Breathe', effects: '帮助缓解鼻炎、感冒等呼吸道不适\n促进呼吸系统健康\n净化空气', usage: '日常香薰,强健呼吸系统,净化空气\n咳嗽、鼻塞时香薰、吸闻、涂抹于鼻翼、喉咙或肺部\n打鼾、哮喘、鼻炎可日常吸闻\n运动前吸闻,扩张呼吸道', method: '🔹香薰 | 🔺涂抹(儿童/敏感肌需稀释)', caution: '' },
|
||||
'乐活': { emoji: '🍃', en: 'DigestZen', effects: '促进消化\n缓解胀气、消化不良、便秘等胃肠不适', usage: '便秘时,稀释涂抹肚脐周围并顺时针揉腹\n喝酒前后各喝2滴,解酒护肝\n晕车时吸闻或稀释涂抹肚脐周围\n拉肚子时逆时针揉腹', method: '🔹熏香 | 🔸内用 | 🔺涂抹(儿童/敏感肌需稀释)', caution: '' },
|
||||
'舒缓': { emoji: '🌿', en: 'Deep Blue', effects: '缓解肌肉酸痛\n抗痉挛,抗炎', usage: '肌肉酸痛、扭伤、挫伤、肩颈紧绷、落枕、关节疼痛时稀释涂抹于患处', method: '🔺涂抹(需稀释)', caution: '' },
|
||||
'乳香': { emoji: '👑', en: 'Frankincense', effects: '促进伤口愈合,促进细胞健康\n抗氧化、抗发炎、抗衰老、淡纹\n活血行气\n疏通血管\n滋养大脑神经', usage: '加入护肤品中,淡斑,抗衰\n稀释后涂抹大眼眶,改善视力\n早晚舌下含服 2 滴,提高血氧含量\n夜间香薰,滋养大脑,安眠\n任何情况下,想不起来用什么就用乳香', method: '🔹香薰 | 🔸内用 | 🔺涂抹', caution: '' },
|
||||
}
|
||||
|
||||
export const OIL_CARD_ALIAS = {
|
||||
'仕女呵护': '温柔呵护',
|
||||
'薄荷呵护': '椒样薄荷',
|
||||
'牛至呵护': '西班牙牛至',
|
||||
}
|
||||
|
||||
export function getOilCard(name) {
|
||||
if (OIL_CARDS[name]) return OIL_CARDS[name]
|
||||
if (OIL_CARD_ALIAS[name] && OIL_CARDS[OIL_CARD_ALIAS[name]]) return OIL_CARDS[OIL_CARD_ALIAS[name]]
|
||||
const base = name.replace(/呵护$/, '')
|
||||
if (base !== name && OIL_CARDS[base]) return OIL_CARDS[base]
|
||||
return null
|
||||
}
|
||||
|
||||
export function setOilCard(name, card) {
|
||||
if (card && (card.effects || card.usage)) {
|
||||
OIL_CARDS[name] = card
|
||||
} else {
|
||||
delete OIL_CARDS[name]
|
||||
}
|
||||
}
|
||||
@@ -14,14 +14,27 @@ const OIL_EN = {
|
||||
'柠檬草': 'Lemongrass', '杜松浆果': 'Juniper Berry', '甜橙': 'Wild Orange',
|
||||
'香茅': 'Citronella', '薄荷': 'Peppermint', '扁柏': 'Arborvitae',
|
||||
'古巴香脂': 'Copaiba', '椰子油': 'Coconut Oil',
|
||||
'芳香调理': 'AromaTouch', '保卫复方': 'On Guard',
|
||||
'乐活复方': 'Balance', '舒缓复方': 'Past Tense',
|
||||
'净化复方': 'Purify', '呼吸复方': 'Breathe',
|
||||
'舒压复方': 'Adaptiv', '多特瑞': 'doTERRA',
|
||||
'芳香调理': 'AromaTouch', '保卫复方': 'On Guard', '保卫': 'On Guard',
|
||||
'乐活复方': 'Balance', '乐活': 'DigestZen',
|
||||
'舒缓复方': 'Past Tense', '舒缓': 'Deep Blue',
|
||||
'净化复方': 'Purify', '净化清新': 'Purify',
|
||||
'呼吸复方': 'Breathe', '顺畅呼吸': 'Breathe',
|
||||
'舒压复方': 'Adaptiv', '安定情绪': 'Balance',
|
||||
'安宁神气': 'Serenity', '多特瑞': 'doTERRA',
|
||||
'野橘': 'Wild Orange', '柑橘清新': 'Citrus Bliss',
|
||||
'新瑞活力': 'MetaPWR', '元气': 'Zendocrine',
|
||||
'温柔呵护': 'ClaryCalm', '西洋蓍草': 'Yarrow|Pom',
|
||||
'西班牙牛至': 'Oregano',
|
||||
}
|
||||
|
||||
export function oilEn(name) {
|
||||
return OIL_EN[name] || ''
|
||||
if (OIL_EN[name]) return OIL_EN[name]
|
||||
// Try without common suffixes
|
||||
const base = name.replace(/复方$|呵护$/, '')
|
||||
if (base !== name && OIL_EN[base]) return OIL_EN[base]
|
||||
// Try adding suffixes
|
||||
if (OIL_EN[name + '复方']) return OIL_EN[name + '复方']
|
||||
return ''
|
||||
}
|
||||
|
||||
export function recipeNameEn(name) {
|
||||
|
||||
38
frontend/src/composables/useSaveImage.js
Normal file
38
frontend/src/composables/useSaveImage.js
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Save image — on mobile use navigator.share (same as recipe card),
|
||||
* on desktop trigger download.
|
||||
*/
|
||||
|
||||
const isMobile = () => /iPhone|iPad|iPod|Android/i.test(navigator.userAgent)
|
||||
|
||||
/**
|
||||
* Save from a data URL.
|
||||
* Mobile: navigator.share({files}) → system share sheet (save to photos / AirDrop etc)
|
||||
* Desktop: download link.
|
||||
*/
|
||||
export async function saveImageFromUrl(dataUrl, filename) {
|
||||
// Try navigator.share with files (works on iOS Safari, Chrome mobile)
|
||||
if (navigator.share && navigator.canShare) {
|
||||
try {
|
||||
const res = await fetch(dataUrl)
|
||||
const blob = await res.blob()
|
||||
const file = new File([blob], filename + '.png', { type: 'image/png' })
|
||||
if (navigator.canShare({ files: [file] })) {
|
||||
await navigator.share({ files: [file] })
|
||||
return 'shared'
|
||||
}
|
||||
} catch (e) {
|
||||
// User cancelled share or share failed, fall through to download
|
||||
if (e.name === 'AbortError') return 'cancelled'
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: direct download
|
||||
const a = document.createElement('a')
|
||||
a.href = dataUrl
|
||||
a.download = filename + '.png'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
setTimeout(() => a.remove(), 100)
|
||||
return 'downloaded'
|
||||
}
|
||||
@@ -10,11 +10,13 @@ const routes = [
|
||||
path: '/manage',
|
||||
name: 'RecipeManager',
|
||||
component: () => import('../views/RecipeManager.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/inventory',
|
||||
name: 'Inventory',
|
||||
component: () => import('../views/Inventory.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/oils',
|
||||
@@ -25,26 +27,31 @@ const routes = [
|
||||
path: '/projects',
|
||||
name: 'Projects',
|
||||
component: () => import('../views/Projects.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/mydiary',
|
||||
name: 'MyDiary',
|
||||
component: () => import('../views/MyDiary.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/audit',
|
||||
name: 'AuditLog',
|
||||
component: () => import('../views/AuditLog.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/bugs',
|
||||
name: 'BugTracker',
|
||||
component: () => import('../views/BugTracker.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/users',
|
||||
name: 'UserManagement',
|
||||
component: () => import('../views/UserManagement.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
// Getters
|
||||
const isLoggedIn = computed(() => user.value.id !== null)
|
||||
const isAdmin = computed(() => user.value.role === 'admin')
|
||||
const canManage = computed(() =>
|
||||
['senior_editor', 'admin'].includes(user.value.role)
|
||||
)
|
||||
const canEdit = computed(() =>
|
||||
['editor', 'senior_editor', 'admin'].includes(user.value.role)
|
||||
)
|
||||
@@ -82,7 +85,7 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
|
||||
function canEditRecipe(recipe) {
|
||||
if (isAdmin.value || user.value.role === 'senior_editor') return true
|
||||
if (user.value.role === 'editor' && recipe._owner_id === user.value.id) return true
|
||||
if (recipe._owner_id === user.value.id) return true
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -91,6 +94,7 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
user,
|
||||
isLoggedIn,
|
||||
isAdmin,
|
||||
canManage,
|
||||
canEdit,
|
||||
isBusiness,
|
||||
initToken,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { api } from '../composables/useApi'
|
||||
export const DROPS_PER_ML = 18.6
|
||||
|
||||
export const VOLUME_DROPS = {
|
||||
'单次': null,
|
||||
'2.5': 46,
|
||||
'5': 93,
|
||||
'10': 186,
|
||||
@@ -67,19 +68,21 @@ export const useOilsStore = defineStore('oils', () => {
|
||||
bottlePrice: oil.bottle_price,
|
||||
dropCount: oil.drop_count,
|
||||
retailPrice: oil.retail_price ?? null,
|
||||
isActive: oil.is_active ?? true,
|
||||
isActive: oil.is_active !== 0,
|
||||
enName: oil.en_name ?? null,
|
||||
}
|
||||
}
|
||||
oils.value = newOils
|
||||
oilsMeta.value = newMeta
|
||||
}
|
||||
|
||||
async function saveOil(name, bottlePrice, dropCount, retailPrice) {
|
||||
async function saveOil(name, bottlePrice, dropCount, retailPrice, enName = null) {
|
||||
await api.post('/api/oils', {
|
||||
name,
|
||||
bottle_price: bottlePrice,
|
||||
drop_count: dropCount,
|
||||
retail_price: retailPrice,
|
||||
en_name: enName,
|
||||
})
|
||||
await loadOils()
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ export const useRecipesStore = defineStore('recipes', () => {
|
||||
_owner_name: r._owner_name ?? r.owner_name ?? '',
|
||||
_version: r._version ?? r.version ?? 1,
|
||||
name: r.name,
|
||||
en_name: r.en_name ?? '',
|
||||
note: r.note ?? '',
|
||||
tags: r.tags ?? [],
|
||||
ingredients: (r.ingredients ?? []).map((ing) => ({
|
||||
@@ -52,7 +53,12 @@ export const useRecipesStore = defineStore('recipes', () => {
|
||||
return data
|
||||
} else {
|
||||
const data = await api.post('/api/recipes', recipe)
|
||||
await loadRecipes()
|
||||
// Refresh list; if refresh fails, still return success (recipe was saved)
|
||||
try {
|
||||
await loadRecipes()
|
||||
} catch (e) {
|
||||
console.warn('[saveRecipe] loadRecipes failed after save:', e)
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ export const useUiStore = defineStore('ui', () => {
|
||||
const currentSection = ref('search')
|
||||
const showLoginModal = ref(false)
|
||||
const toasts = ref([])
|
||||
const pendingAction = ref(null)
|
||||
|
||||
let toastId = 0
|
||||
|
||||
@@ -20,7 +21,10 @@ export const useUiStore = defineStore('ui', () => {
|
||||
}, duration)
|
||||
}
|
||||
|
||||
function openLogin() {
|
||||
function openLogin(afterLogin) {
|
||||
if (afterLogin) {
|
||||
pendingAction.value = afterLogin
|
||||
}
|
||||
showLoginModal.value = true
|
||||
}
|
||||
|
||||
@@ -28,13 +32,23 @@ export const useUiStore = defineStore('ui', () => {
|
||||
showLoginModal.value = false
|
||||
}
|
||||
|
||||
function runPendingAction() {
|
||||
if (pendingAction.value) {
|
||||
const action = pendingAction.value
|
||||
pendingAction.value = null
|
||||
action()
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
currentSection,
|
||||
showLoginModal,
|
||||
toasts,
|
||||
pendingAction,
|
||||
showSection,
|
||||
showToast,
|
||||
openLogin,
|
||||
closeLogin,
|
||||
runPendingAction,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -154,7 +154,7 @@ function formatDetail(log) {
|
||||
async function fetchLogs() {
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await api(`/api/audit-logs?offset=${page.value * pageSize}&limit=${pageSize}`)
|
||||
const res = await api(`/api/audit-log?offset=${page.value * pageSize}&limit=${pageSize}`)
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
const items = Array.isArray(data) ? data : data.logs || data.items || []
|
||||
@@ -179,7 +179,7 @@ async function undoLog(log) {
|
||||
if (!ok) return
|
||||
try {
|
||||
const id = log._id || log.id
|
||||
const res = await api(`/api/audit-logs/${id}/undo`, { method: 'POST' })
|
||||
const res = await api(`/api/audit-log/${id}/undo`, { method: 'POST' })
|
||||
if (res.ok) {
|
||||
ui.showToast('已撤销')
|
||||
// Refresh
|
||||
|
||||
@@ -16,22 +16,21 @@
|
||||
<span class="bug-status" :class="'s-' + (bug.status || 'open')">{{ statusLabel(bug.status) }}</span>
|
||||
<span class="bug-date">{{ formatDate(bug.created_at) }}</span>
|
||||
</div>
|
||||
<div class="bug-title">{{ bug.title }}</div>
|
||||
<div v-if="bug.description" class="bug-desc">{{ bug.description }}</div>
|
||||
<div v-if="bug.reporter" class="bug-reporter">报告者: {{ bug.reporter }}</div>
|
||||
<div class="bug-title">{{ bug.content }}</div>
|
||||
<div v-if="bug.display_name" class="bug-reporter">{{ bug.display_name || bug.username }}</div>
|
||||
|
||||
<!-- Status workflow -->
|
||||
<!-- Status workflow: is_resolved: 0=open, 1=testing, 2=fixed, 3=tested -->
|
||||
<div class="bug-actions">
|
||||
<template v-if="bug.status === 'open'">
|
||||
<button class="btn-sm btn-status" @click="updateStatus(bug, 'testing')">开始测试</button>
|
||||
<template v-if="bug.is_resolved === 0">
|
||||
<button class="btn-sm btn-status" @click="updateStatus(bug, 1)">待测试</button>
|
||||
</template>
|
||||
<template v-else-if="bug.status === 'testing'">
|
||||
<button class="btn-sm btn-status" @click="updateStatus(bug, 'fixed')">标记修复</button>
|
||||
<button class="btn-sm btn-reopen" @click="updateStatus(bug, 'open')">重新打开</button>
|
||||
<template v-else-if="bug.is_resolved === 1">
|
||||
<button class="btn-sm btn-status" @click="updateStatus(bug, 2)">已修复</button>
|
||||
<button class="btn-sm btn-reopen" @click="updateStatus(bug, 0)">重新打开</button>
|
||||
</template>
|
||||
<template v-else-if="bug.status === 'fixed'">
|
||||
<button class="btn-sm btn-status" @click="updateStatus(bug, 'tested')">验证通过</button>
|
||||
<button class="btn-sm btn-reopen" @click="updateStatus(bug, 'open')">重新打开</button>
|
||||
<template v-else-if="bug.is_resolved === 2">
|
||||
<button class="btn-sm btn-status" @click="updateStatus(bug, 3)">已测试</button>
|
||||
<button class="btn-sm btn-reopen" @click="updateStatus(bug, 0)">重新打开</button>
|
||||
</template>
|
||||
<button class="btn-sm btn-delete" @click="removeBug(bug)">删除</button>
|
||||
</div>
|
||||
@@ -40,10 +39,11 @@
|
||||
<div class="comments-section" v-if="expandedBugId === (bug._id || bug.id)">
|
||||
<div v-for="comment in (bug.comments || [])" :key="comment._id || comment.id" class="comment-item">
|
||||
<div class="comment-meta">
|
||||
<span class="comment-author">{{ comment.author || comment.user_name || '匿名' }}</span>
|
||||
<span class="comment-author">{{ comment.display_name || comment.username || '系统' }}</span>
|
||||
<span class="comment-action" v-if="comment.action">{{ comment.action }}</span>
|
||||
<span class="comment-time">{{ formatDate(comment.created_at) }}</span>
|
||||
</div>
|
||||
<div class="comment-text">{{ comment.text || comment.content }}</div>
|
||||
<div class="comment-text">{{ comment.content }}</div>
|
||||
</div>
|
||||
<div class="comment-add">
|
||||
<input
|
||||
@@ -75,9 +75,9 @@
|
||||
<span class="bug-status s-tested">已解决</span>
|
||||
<span class="bug-date">{{ formatDate(bug.created_at) }}</span>
|
||||
</div>
|
||||
<div class="bug-title">{{ bug.title }}</div>
|
||||
<div class="bug-title">{{ bug.content }}</div>
|
||||
<div class="bug-actions">
|
||||
<button class="btn-sm btn-reopen" @click="updateStatus(bug, 'open')">重新打开</button>
|
||||
<button class="btn-sm btn-reopen" @click="updateStatus(bug, 0)">重新打开</button>
|
||||
<button class="btn-sm btn-delete" @click="removeBug(bug)">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -92,12 +92,8 @@
|
||||
<button class="btn-close" @click="showAddBug = false">✕</button>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>标题</label>
|
||||
<input v-model="bugForm.title" class="form-input" placeholder="Bug标题" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>描述</label>
|
||||
<textarea v-model="bugForm.description" class="form-textarea" rows="4" placeholder="Bug描述,复现步骤等..."></textarea>
|
||||
<label>Bug 内容</label>
|
||||
<textarea v-model="bugForm.content" class="form-textarea" rows="4" placeholder="描述问题、复现步骤等..."></textarea>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>优先级</label>
|
||||
@@ -113,7 +109,7 @@
|
||||
</div>
|
||||
<div class="overlay-footer">
|
||||
<button class="btn-outline" @click="showAddBug = false">取消</button>
|
||||
<button class="btn-primary" @click="createBug" :disabled="!bugForm.title.trim()">提交</button>
|
||||
<button class="btn-primary" @click="createBug" :disabled="!bugForm.content.trim()">提交</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -137,38 +133,35 @@ const expandedBugId = ref(null)
|
||||
const newComment = ref('')
|
||||
|
||||
const bugForm = reactive({
|
||||
title: '',
|
||||
description: '',
|
||||
priority: 'normal',
|
||||
content: '',
|
||||
priority: 2,
|
||||
})
|
||||
|
||||
// priority: 0=urgent, 1=high, 2=normal
|
||||
const priorities = [
|
||||
{ value: 'low', label: '低' },
|
||||
{ value: 'normal', label: '中' },
|
||||
{ value: 'high', label: '高' },
|
||||
{ value: 'critical', label: '紧急' },
|
||||
{ value: 0, label: '紧急' },
|
||||
{ value: 1, label: '高' },
|
||||
{ value: 2, label: '中' },
|
||||
]
|
||||
|
||||
// is_resolved: 0=open, 1=testing, 2=fixed, 3=tested
|
||||
const activeBugs = computed(() =>
|
||||
bugs.value.filter(b => b.status !== 'tested' && b.status !== 'closed')
|
||||
.sort((a, b) => {
|
||||
const order = { critical: 0, high: 1, normal: 2, low: 3 }
|
||||
return (order[a.priority] ?? 2) - (order[b.priority] ?? 2)
|
||||
})
|
||||
bugs.value.filter(b => b.is_resolved !== 2 && b.is_resolved !== 3)
|
||||
.sort((a, b) => (a.priority ?? 2) - (b.priority ?? 2))
|
||||
)
|
||||
|
||||
const resolvedBugs = computed(() =>
|
||||
bugs.value.filter(b => b.status === 'tested' || b.status === 'closed')
|
||||
bugs.value.filter(b => b.is_resolved === 2 || b.is_resolved === 3)
|
||||
)
|
||||
|
||||
function priorityLabel(p) {
|
||||
const map = { low: '低', normal: '中', high: '高', critical: '紧急' }
|
||||
return map[p] || '中'
|
||||
const map = { 0: '紧急', 1: '高', 2: '中' }
|
||||
return map[p] ?? '中'
|
||||
}
|
||||
|
||||
function statusLabel(s) {
|
||||
const map = { open: '待处理', testing: '测试中', fixed: '已修复', tested: '已验证', closed: '已关闭' }
|
||||
return map[s] || s
|
||||
const map = { 0: '待处理', 1: '待测试', 2: '已修复', 3: '已测试' }
|
||||
return map[s] ?? '待处理'
|
||||
}
|
||||
|
||||
function formatDate(d) {
|
||||
@@ -188,7 +181,7 @@ function toggleComments(bug) {
|
||||
|
||||
async function loadBugs() {
|
||||
try {
|
||||
const res = await api('/api/bugs')
|
||||
const res = await api('/api/bug-reports')
|
||||
if (res.ok) {
|
||||
bugs.value = await res.json()
|
||||
}
|
||||
@@ -198,23 +191,19 @@ async function loadBugs() {
|
||||
}
|
||||
|
||||
async function createBug() {
|
||||
if (!bugForm.title.trim()) return
|
||||
if (!bugForm.content.trim()) return
|
||||
try {
|
||||
const res = await api('/api/bugs', {
|
||||
const res = await api('/api/bug-report', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
title: bugForm.title.trim(),
|
||||
description: bugForm.description.trim(),
|
||||
content: bugForm.content.trim(),
|
||||
priority: bugForm.priority,
|
||||
status: 'open',
|
||||
reporter: auth.user.display_name || auth.user.username,
|
||||
}),
|
||||
})
|
||||
if (res.ok) {
|
||||
showAddBug.value = false
|
||||
bugForm.title = ''
|
||||
bugForm.description = ''
|
||||
bugForm.priority = 'normal'
|
||||
bugForm.content = ''
|
||||
bugForm.priority = 2
|
||||
await loadBugs()
|
||||
ui.showToast('Bug已提交')
|
||||
}
|
||||
@@ -224,14 +213,14 @@ async function createBug() {
|
||||
}
|
||||
|
||||
async function updateStatus(bug, newStatus) {
|
||||
const id = bug._id || bug.id
|
||||
const id = bug.id
|
||||
try {
|
||||
const res = await api(`/api/bugs/${id}`, {
|
||||
const res = await api(`/api/bug-reports/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ status: newStatus }),
|
||||
})
|
||||
if (res.ok) {
|
||||
bug.status = newStatus
|
||||
bug.is_resolved = newStatus
|
||||
ui.showToast(`状态已更新: ${statusLabel(newStatus)}`)
|
||||
}
|
||||
} catch {
|
||||
@@ -240,11 +229,11 @@ async function updateStatus(bug, newStatus) {
|
||||
}
|
||||
|
||||
async function removeBug(bug) {
|
||||
const ok = await showConfirm(`确定删除 "${bug.title}"?`)
|
||||
const ok = await showConfirm(`确定删除 "${bug.content}"?`)
|
||||
if (!ok) return
|
||||
const id = bug._id || bug.id
|
||||
try {
|
||||
const res = await api(`/api/bugs/${id}`, { method: 'DELETE' })
|
||||
const res = await api(`/api/bug-reports/${id}`, { method: 'DELETE' })
|
||||
if (res.ok) {
|
||||
bugs.value = bugs.value.filter(b => (b._id || b.id) !== id)
|
||||
ui.showToast('已删除')
|
||||
@@ -258,11 +247,10 @@ async function addComment(bug) {
|
||||
if (!newComment.value.trim()) return
|
||||
const id = bug._id || bug.id
|
||||
try {
|
||||
const res = await api(`/api/bugs/${id}/comments`, {
|
||||
const res = await api(`/api/bug-reports/${id}/comment`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
text: newComment.value.trim(),
|
||||
author: auth.user.display_name || auth.user.username,
|
||||
content: newComment.value.trim(),
|
||||
}),
|
||||
})
|
||||
if (res.ok) {
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
<div class="my-diary">
|
||||
<!-- Sub Tabs -->
|
||||
<div class="sub-tabs">
|
||||
<button class="sub-tab" :class="{ active: activeTab === 'diary' }" @click="activeTab = 'diary'">📖 配方日记</button>
|
||||
<button class="sub-tab" :class="{ active: activeTab === 'brand' }" @click="activeTab = 'brand'">🏷️ Brand</button>
|
||||
<button class="sub-tab" :class="{ active: activeTab === 'account' }" @click="activeTab = 'account'">👤 Account</button>
|
||||
<button class="sub-tab" :class="{ active: activeTab === 'brand' }" @click="activeTab = 'brand'">🏷 我的品牌</button>
|
||||
<button class="sub-tab" :class="{ active: activeTab === 'account' }" @click="activeTab = 'account'">👤 我的账户</button>
|
||||
</div>
|
||||
|
||||
<!-- Diary Tab -->
|
||||
@@ -108,38 +107,100 @@
|
||||
|
||||
<!-- Brand Tab -->
|
||||
<div v-if="activeTab === 'brand'" class="tab-content">
|
||||
<!-- Back to recipe card (when navigated from a recipe) -->
|
||||
<div v-if="returnRecipeId" class="return-banner">
|
||||
<span>📋 上传完成后可返回配方卡片</span>
|
||||
<button class="btn-return" @click="goBackToRecipe">← 返回配方卡片</button>
|
||||
</div>
|
||||
<div class="section-card">
|
||||
<h4>🏷️ 品牌设置</h4>
|
||||
<p style="font-size:13px;color:var(--text-light);margin-bottom:16px">分享配方卡片时,二维码、背景图、Logo 会自动展示在卡片上</p>
|
||||
|
||||
<div class="form-group">
|
||||
<label>品牌名称</label>
|
||||
<input v-model="brandName" class="form-input" placeholder="您的品牌名称" @blur="saveBrandSettings" />
|
||||
</div>
|
||||
<!-- Three upload areas side by side -->
|
||||
<div style="display:flex;gap:20px;flex-wrap:wrap;margin-bottom:16px">
|
||||
<!-- QR Code -->
|
||||
<div>
|
||||
<label class="form-label">📱 二维码</label>
|
||||
<p style="font-size:11px;color:var(--text-light);margin-bottom:6px">卡片右上角展示</p>
|
||||
<div class="upload-box" @click="triggerUpload('qr')">
|
||||
<img v-if="brandQrImage" :src="brandQrImage" class="upload-box-img" />
|
||||
<span v-else class="upload-box-hint">点击上传</span>
|
||||
</div>
|
||||
<input ref="qrInput" type="file" accept="image/*" style="display:none" @change="handleUpload('qr', $event)" />
|
||||
<button v-if="brandQrImage" class="btn-clear" @click="clearBrandImage('qr')">清除</button>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>二维码链接</label>
|
||||
<input v-model="brandQrUrl" class="form-input" placeholder="https://..." @blur="saveBrandSettings" />
|
||||
<div v-if="brandQrUrl" class="qr-preview">
|
||||
<img :src="'https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=' + encodeURIComponent(brandQrUrl)" alt="QR" class="qr-img" />
|
||||
<!-- Background -->
|
||||
<div>
|
||||
<label class="form-label">🖼 背景图</label>
|
||||
<p style="font-size:11px;color:var(--text-light);margin-bottom:6px">铺满整张卡片,半透明</p>
|
||||
<div class="upload-box" @click="triggerUpload('bg')">
|
||||
<img v-if="brandBg" :src="brandBg" class="upload-box-img" />
|
||||
<span v-else class="upload-box-hint">点击上传</span>
|
||||
</div>
|
||||
<input ref="bgInput" type="file" accept="image/*" style="display:none" @change="handleUpload('bg', $event)" />
|
||||
<button v-if="brandBg" class="btn-clear" @click="clearBrandImage('bg')">清除</button>
|
||||
</div>
|
||||
|
||||
<!-- Logo -->
|
||||
<div>
|
||||
<label class="form-label">🏷 Logo</label>
|
||||
<p style="font-size:11px;color:var(--text-light);margin-bottom:6px">卡片左下角水印</p>
|
||||
<div class="upload-box" @click="triggerUpload('logo')">
|
||||
<img v-if="brandLogo" :src="brandLogo" class="upload-box-img" />
|
||||
<span v-else class="upload-box-hint">点击上传</span>
|
||||
</div>
|
||||
<input ref="logoInput" type="file" accept="image/*" style="display:none" @change="handleUpload('logo', $event)" />
|
||||
<button v-if="brandLogo" class="btn-clear" @click="clearBrandImage('logo')">清除</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Brand name -->
|
||||
<div class="form-group">
|
||||
<label>品牌Logo</label>
|
||||
<div class="upload-area" @click="triggerUpload('logo')">
|
||||
<img v-if="brandLogo" :src="brandLogo" class="upload-preview" />
|
||||
<span v-else class="upload-hint">点击上传Logo</span>
|
||||
<label class="form-label">品牌名称或标语(显示在二维码下方)</label>
|
||||
<textarea v-model="brandName" class="form-control" rows="2" placeholder="扫码申请成为优惠顾客 我的精油小屋" style="max-width:350px;font-size:13px" @blur="saveBrandSettings"></textarea>
|
||||
<div style="display:flex;gap:6px;margin-top:6px">
|
||||
<button class="btn-align" :class="{ active: brandAlign === 'left' }" @click="brandAlign='left'; saveBrandSettings()">靠左</button>
|
||||
<button class="btn-align" :class="{ active: brandAlign === 'center' }" @click="brandAlign='center'; saveBrandSettings()">居中</button>
|
||||
<button class="btn-align" :class="{ active: brandAlign === 'right' }" @click="brandAlign='right'; saveBrandSettings()">靠右</button>
|
||||
</div>
|
||||
<input ref="logoInput" type="file" accept="image/*" style="display:none" @change="handleUpload('logo', $event)" />
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>卡片背景</label>
|
||||
<div class="upload-area" @click="triggerUpload('bg')">
|
||||
<img v-if="brandBg" :src="brandBg" class="upload-preview wide" />
|
||||
<span v-else class="upload-hint">点击上传背景图</span>
|
||||
<!-- Card Preview -->
|
||||
<div style="margin-bottom:16px">
|
||||
<label class="form-label">📋 配方卡片预览</label>
|
||||
<div class="card-preview-mini">
|
||||
<!-- Background overlay -->
|
||||
<div v-if="brandBg" style="position:absolute;inset:0;background-size:cover;background-position:center;opacity:0.12;pointer-events:none" :style="{ backgroundImage: 'url(' + brandBg + ')' }"></div>
|
||||
<!-- Logo: shown in bottom row, not as watermark -->
|
||||
<!-- QR: top-right -->
|
||||
<div v-if="brandQrImage" style="position:absolute;top:16px;right:12px;display:flex;flex-direction:column;align-items:center;gap:2px;z-index:2">
|
||||
<img :src="brandQrImage" style="width:36px;height:36px;object-fit:cover;border-radius:4px;box-shadow:0 1px 4px rgba(0,0,0,0.1)" />
|
||||
<div v-if="brandName" :style="{ textAlign: brandAlign }" style="font-size:5px;color:var(--text-light);line-height:1.2;max-width:42px;white-space:pre-line">{{ brandName }}</div>
|
||||
</div>
|
||||
<!-- Content -->
|
||||
<div style="position:relative;z-index:1">
|
||||
<div style="font-size:7px;letter-spacing:1.5px;color:var(--sage);margin-bottom:3px">doTERRA · 来自大地的礼物</div>
|
||||
<div style="font-size:13px;font-weight:700;color:var(--text-dark);margin-bottom:3px;line-height:1.3">配方名称</div>
|
||||
<div style="width:30px;height:1px;background:linear-gradient(90deg,var(--sage),var(--gold));margin:6px 0"></div>
|
||||
<div style="font-size:9px;color:var(--text-light);margin-bottom:6px">薰衣草 · 乳香 · 茶树</div>
|
||||
<!-- Total cost bar -->
|
||||
<div style="background:linear-gradient(135deg,var(--sage),#5a7d5e);border-radius:6px;padding:6px 10px;display:flex;justify-content:space-between;align-items:center">
|
||||
<span style="color:rgba(255,255,255,0.85);font-size:8px;letter-spacing:0.5px">配方总成本</span>
|
||||
<span style="color:white;font-size:12px;font-weight:700">¥12.50</span>
|
||||
</div>
|
||||
<!-- Logo left + Date right -->
|
||||
<div style="display:flex;justify-content:space-between;align-items:flex-end;margin-top:8px">
|
||||
<img v-if="brandLogo" :src="brandLogo" style="height:18px;object-fit:contain" />
|
||||
<span v-else></span>
|
||||
<span style="font-size:7px;color:var(--text-light);letter-spacing:0.5px">制作日期:{{ new Date().toLocaleDateString('zh-CN') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<input ref="bgInput" type="file" accept="image/*" style="display:none" @change="handleUpload('bg', $event)" />
|
||||
</div>
|
||||
|
||||
<div style="display:flex;gap:8px;align-items:center">
|
||||
<button class="btn btn-primary" @click="saveBrandSettings">💾 保存品牌设置</button>
|
||||
<button v-if="returnRecipeId" class="btn btn-outline" @click="goBackToRecipe">← 返回配方卡片</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -160,10 +221,6 @@
|
||||
<div class="form-static">{{ auth.user.username }}</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>角色</label>
|
||||
<div class="form-static role-badge">{{ roleLabel }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-card">
|
||||
@@ -202,7 +259,8 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { useOilsStore } from '../stores/oils'
|
||||
import { useDiaryStore } from '../stores/diary'
|
||||
@@ -215,20 +273,25 @@ const auth = useAuthStore()
|
||||
const oils = useOilsStore()
|
||||
const diaryStore = useDiaryStore()
|
||||
const ui = useUiStore()
|
||||
const router = useRouter()
|
||||
|
||||
const activeTab = ref('diary')
|
||||
const activeTab = ref('brand')
|
||||
const pasteText = ref('')
|
||||
const selectedDiaryId = ref(null)
|
||||
const returnRecipeId = ref(null)
|
||||
const selectedDiary = ref(null)
|
||||
const newEntryText = ref('')
|
||||
|
||||
// Brand settings
|
||||
const brandName = ref('')
|
||||
const brandQrUrl = ref('')
|
||||
const brandQrImage = ref('')
|
||||
const brandLogo = ref('')
|
||||
const brandBg = ref('')
|
||||
const brandAlign = ref('center')
|
||||
const logoInput = ref(null)
|
||||
const bgInput = ref(null)
|
||||
const qrInput = ref(null)
|
||||
|
||||
// Account settings
|
||||
const displayName = ref('')
|
||||
@@ -237,22 +300,20 @@ const newPassword = ref('')
|
||||
const confirmPassword = ref('')
|
||||
const businessReason = ref('')
|
||||
|
||||
const roleLabel = computed(() => {
|
||||
const roles = {
|
||||
admin: '管理员',
|
||||
senior_editor: '高级编辑',
|
||||
editor: '编辑',
|
||||
viewer: '查看者',
|
||||
}
|
||||
return roles[auth.user.role] || auth.user.role
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await diaryStore.loadDiary()
|
||||
displayName.value = auth.user.display_name || ''
|
||||
await loadBrandSettings()
|
||||
returnRecipeId.value = localStorage.getItem('oil_return_recipe_id') || null
|
||||
})
|
||||
|
||||
function goBackToRecipe() {
|
||||
if (returnRecipeId.value) {
|
||||
localStorage.removeItem('oil_return_recipe_id')
|
||||
router.push('/?openRecipe=' + encodeURIComponent(returnRecipeId.value))
|
||||
}
|
||||
}
|
||||
|
||||
function selectDiary(d) {
|
||||
const id = d._id || d.id
|
||||
selectedDiaryId.value = id
|
||||
@@ -341,13 +402,15 @@ function formatDate(d) {
|
||||
// Brand settings
|
||||
async function loadBrandSettings() {
|
||||
try {
|
||||
const res = await api('/api/brand-settings')
|
||||
const res = await api('/api/brand')
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
brandName.value = data.brand_name || ''
|
||||
brandQrUrl.value = data.qr_url || ''
|
||||
brandLogo.value = data.logo_url || ''
|
||||
brandBg.value = data.bg_url || ''
|
||||
brandQrImage.value = data.qr_code || ''
|
||||
brandLogo.value = data.brand_logo || ''
|
||||
brandBg.value = data.brand_bg || ''
|
||||
brandAlign.value = data.brand_align || 'center'
|
||||
}
|
||||
} catch {
|
||||
// no brand settings yet
|
||||
@@ -356,51 +419,165 @@ async function loadBrandSettings() {
|
||||
|
||||
async function saveBrandSettings() {
|
||||
try {
|
||||
await api('/api/brand-settings', {
|
||||
const res = await api('/api/brand', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
brand_name: brandName.value,
|
||||
qr_url: brandQrUrl.value,
|
||||
brand_align: brandAlign.value,
|
||||
}),
|
||||
})
|
||||
if (res.ok) ui.showToast('已保存')
|
||||
} catch {
|
||||
// silent
|
||||
ui.showToast('保存失败')
|
||||
}
|
||||
}
|
||||
|
||||
function triggerUpload(type) {
|
||||
if (type === 'logo') logoInput.value?.click()
|
||||
else bgInput.value?.click()
|
||||
else if (type === 'bg') bgInput.value?.click()
|
||||
else if (type === 'qr') qrInput.value?.click()
|
||||
}
|
||||
|
||||
function readFileAsBase64(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = e => resolve(e.target.result)
|
||||
reader.onerror = reject
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
|
||||
// Compress image if too large (keeps PNG for small images, JPEG for large)
|
||||
function compressImage(base64, maxSize = 500000) {
|
||||
return new Promise((resolve) => {
|
||||
if (base64.length <= maxSize) { resolve(base64); return }
|
||||
const img = new Image()
|
||||
img.onload = () => {
|
||||
const canvas = document.createElement('canvas')
|
||||
let w = img.width, h = img.height
|
||||
const maxDim = 600
|
||||
if (w > maxDim || h > maxDim) {
|
||||
const ratio = Math.min(maxDim / w, maxDim / h)
|
||||
w = Math.round(w * ratio)
|
||||
h = Math.round(h * ratio)
|
||||
}
|
||||
canvas.width = w
|
||||
canvas.height = h
|
||||
canvas.getContext('2d').drawImage(img, 0, 0, w, h)
|
||||
// Try PNG first, then JPEG with decreasing quality
|
||||
let result = canvas.toDataURL('image/png')
|
||||
if (result.length > maxSize) {
|
||||
let quality = 0.85
|
||||
while (quality > 0.2) {
|
||||
result = canvas.toDataURL('image/jpeg', quality)
|
||||
if (result.length <= maxSize) break
|
||||
quality -= 0.1
|
||||
}
|
||||
}
|
||||
resolve(result)
|
||||
}
|
||||
img.onerror = () => resolve(base64) // fallback: return original
|
||||
img.src = base64
|
||||
})
|
||||
}
|
||||
|
||||
// Crop image to square from center
|
||||
function cropToSquare(base64) {
|
||||
return new Promise((resolve) => {
|
||||
const img = new Image()
|
||||
img.onload = () => {
|
||||
const size = Math.min(img.width, img.height)
|
||||
const x = (img.width - size) / 2
|
||||
const y = (img.height - size) / 2
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = size
|
||||
canvas.height = size
|
||||
canvas.getContext('2d').drawImage(img, x, y, size, size, 0, 0, size, size)
|
||||
resolve(canvas.toDataURL('image/png'))
|
||||
}
|
||||
img.onerror = () => resolve(base64)
|
||||
img.src = base64
|
||||
})
|
||||
}
|
||||
|
||||
// Check if image is roughly square
|
||||
function checkSquare(base64) {
|
||||
return new Promise((resolve) => {
|
||||
const img = new Image()
|
||||
img.onload = () => {
|
||||
const ratio = img.width / img.height
|
||||
resolve(ratio > 0.85 && ratio < 1.15) // within 15% of square
|
||||
}
|
||||
img.onerror = () => resolve(true)
|
||||
img.src = base64
|
||||
})
|
||||
}
|
||||
|
||||
async function handleUpload(type, event) {
|
||||
const file = event.target.files[0]
|
||||
if (!file) return
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('type', type)
|
||||
try {
|
||||
const token = localStorage.getItem('oil_auth_token') || ''
|
||||
const res = await fetch('/api/brand-upload', {
|
||||
method: 'POST',
|
||||
headers: token ? { Authorization: 'Bearer ' + token } : {},
|
||||
body: formData,
|
||||
let base64 = await readFileAsBase64(file)
|
||||
|
||||
// QR: check if square, offer to crop
|
||||
if (type === 'qr') {
|
||||
const isSquare = await checkSquare(base64)
|
||||
if (!isSquare) {
|
||||
const { showConfirm: confirm } = await import('../composables/useDialog')
|
||||
const ok = await confirm('二维码图片不是正方形,是否自动裁剪为正方形?\n(取中心区域)')
|
||||
if (ok) {
|
||||
base64 = await cropToSquare(base64)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const maxSize = type === 'bg' ? 1000000 : 500000
|
||||
base64 = await compressImage(base64, maxSize)
|
||||
const fieldMap = { logo: 'brand_logo', bg: 'brand_bg', qr: 'qr_code' }
|
||||
const field = fieldMap[type]
|
||||
if (!field) return
|
||||
ui.showToast('正在上传...')
|
||||
const res = await api('/api/brand', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ [field]: base64 }),
|
||||
})
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
if (type === 'logo') brandLogo.value = data.url
|
||||
else brandBg.value = data.url
|
||||
ui.showToast('上传成功')
|
||||
if (type === 'logo') brandLogo.value = base64
|
||||
else if (type === 'bg') brandBg.value = base64
|
||||
else if (type === 'qr') brandQrImage.value = base64
|
||||
ui.showToast('上传成功 ✓')
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({}))
|
||||
ui.showToast('上传失败: ' + (err.detail || res.status))
|
||||
}
|
||||
} catch (e) {
|
||||
ui.showToast('上传出错: ' + (e.message || '网络错误'))
|
||||
}
|
||||
// Reset input so same file can be re-selected
|
||||
event.target.value = ''
|
||||
}
|
||||
|
||||
async function clearBrandImage(type) {
|
||||
const fieldMap = { logo: 'brand_logo', bg: 'brand_bg', qr: 'qr_code' }
|
||||
const field = fieldMap[type]
|
||||
try {
|
||||
await api('/api/brand', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ [field]: null }),
|
||||
})
|
||||
if (type === 'logo') brandLogo.value = ''
|
||||
else if (type === 'bg') brandBg.value = ''
|
||||
else if (type === 'qr') brandQrImage.value = ''
|
||||
ui.showToast('已清除')
|
||||
} catch {
|
||||
ui.showToast('上传失败')
|
||||
ui.showToast('清除失败')
|
||||
}
|
||||
}
|
||||
|
||||
// Account
|
||||
async function updateDisplayName() {
|
||||
try {
|
||||
await api('/api/me/display-name', {
|
||||
await api('/api/me', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ display_name: displayName.value }),
|
||||
})
|
||||
@@ -719,6 +896,39 @@ async function applyBusiness() {
|
||||
border-color: #7ec6a4;
|
||||
}
|
||||
|
||||
/* Return banner */
|
||||
.return-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
background: #f0faf5;
|
||||
border: 1.5px solid #7ec6a4;
|
||||
border-radius: 12px;
|
||||
padding: 10px 14px;
|
||||
margin-bottom: 14px;
|
||||
font-size: 13px;
|
||||
color: #3e7d5a;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.btn-return {
|
||||
background: linear-gradient(135deg, #7ec6a4 0%, #4a9d7e 100%);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 6px 14px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.btn-return:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
/* Brand */
|
||||
.form-group {
|
||||
margin-bottom: 14px;
|
||||
@@ -740,22 +950,6 @@ async function applyBusiness() {
|
||||
color: #6b6375;
|
||||
}
|
||||
|
||||
.role-badge {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.qr-preview {
|
||||
margin-top: 10px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.qr-img {
|
||||
width: 120px;
|
||||
height: 120px;
|
||||
border-radius: 8px;
|
||||
border: 1.5px solid #e5e4e7;
|
||||
}
|
||||
|
||||
.upload-area {
|
||||
width: 100%;
|
||||
min-height: 80px;
|
||||
@@ -773,6 +967,18 @@ async function applyBusiness() {
|
||||
border-color: #7ec6a4;
|
||||
}
|
||||
|
||||
.qr-preview {
|
||||
margin-top: 10px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.qr-img {
|
||||
width: 120px;
|
||||
height: 120px;
|
||||
border-radius: 8px;
|
||||
border: 1.5px solid #e5e4e7;
|
||||
}
|
||||
|
||||
.upload-preview {
|
||||
max-width: 80px;
|
||||
max-height: 80px;
|
||||
@@ -784,11 +990,78 @@ async function applyBusiness() {
|
||||
max-height: 100px;
|
||||
}
|
||||
|
||||
.qr-upload-preview {
|
||||
max-width: 120px;
|
||||
max-height: 120px;
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
font-size: 12px;
|
||||
color: #9b94a3;
|
||||
margin-top: 4px;
|
||||
padding-left: 2px;
|
||||
}
|
||||
|
||||
.upload-hint {
|
||||
font-size: 13px;
|
||||
color: #b0aab5;
|
||||
}
|
||||
|
||||
/* Upload box (matching initial commit style) */
|
||||
.upload-box {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
border: 2px dashed var(--border, #e0d4c0);
|
||||
border-radius: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
background: white;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
.upload-box:hover { border-color: var(--sage, #7a9e7e); }
|
||||
.upload-box-img { width: 100%; height: 100%; object-fit: contain; }
|
||||
.upload-box-hint { font-size: 12px; color: var(--text-light, #9a8570); }
|
||||
.btn-clear {
|
||||
margin-top: 6px;
|
||||
font-size: 11px;
|
||||
background: none;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 2px 8px;
|
||||
cursor: pointer;
|
||||
color: var(--text-light);
|
||||
}
|
||||
.btn-clear:hover { border-color: #c0392b; color: #c0392b; }
|
||||
.btn-align {
|
||||
font-size: 11px;
|
||||
padding: 3px 10px;
|
||||
border: 1.5px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: white;
|
||||
cursor: pointer;
|
||||
color: var(--text-mid);
|
||||
}
|
||||
.btn-align.active {
|
||||
background: var(--sage-mist);
|
||||
border-color: var(--sage);
|
||||
color: var(--sage-dark);
|
||||
}
|
||||
|
||||
/* Card preview mini */
|
||||
.card-preview-mini {
|
||||
position: relative;
|
||||
width: 280px;
|
||||
background: linear-gradient(145deg, #faf7f0, #f5ede0);
|
||||
border-radius: 14px;
|
||||
border: 1px solid #e0ccaa;
|
||||
overflow: hidden;
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
.hint-text {
|
||||
font-size: 13px;
|
||||
color: #6b6375;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -58,32 +58,25 @@
|
||||
<button class="btn-sm btn-outline" @click="clearSelection">取消选择</button>
|
||||
</div>
|
||||
|
||||
<!-- My Recipes Section -->
|
||||
<!-- My Recipes Section (from diary) -->
|
||||
<div class="recipe-section">
|
||||
<h3 class="section-title">📖 我的配方 ({{ myRecipes.length }})</h3>
|
||||
<div class="recipe-list">
|
||||
<div
|
||||
v-for="r in myFilteredRecipes"
|
||||
:key="r._id"
|
||||
class="recipe-row"
|
||||
:class="{ selected: selectedIds.has(r._id) }"
|
||||
v-for="d in myFilteredRecipes"
|
||||
:key="'diary-' + d.id"
|
||||
class="recipe-row diary-row"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="selectedIds.has(r._id)"
|
||||
@change="toggleSelect(r._id)"
|
||||
class="row-check"
|
||||
/>
|
||||
<div class="row-info" @click="editRecipe(r)">
|
||||
<span class="row-name">{{ r.name }}</span>
|
||||
<div class="row-info" @click="editDiaryRecipe(d)">
|
||||
<span class="row-name">{{ d.name }}</span>
|
||||
<span class="row-tags">
|
||||
<span v-for="t in r.tags" :key="t" class="mini-tag">{{ t }}</span>
|
||||
<span v-for="t in (d.tags || [])" :key="t" class="mini-tag">{{ t }}</span>
|
||||
</span>
|
||||
<span class="row-cost">{{ oils.fmtPrice(oils.calcCost(r.ingredients)) }}</span>
|
||||
<span class="row-cost">{{ oils.fmtPrice(oils.calcCost(d.ingredients || [])) }}</span>
|
||||
</div>
|
||||
<div class="row-actions">
|
||||
<button class="btn-icon" @click="editRecipe(r)" title="编辑">✏️</button>
|
||||
<button class="btn-icon" @click="removeRecipe(r)" title="删除">🗑️</button>
|
||||
<button class="btn-icon" @click="editDiaryRecipe(d)" title="编辑">✏️</button>
|
||||
<button class="btn-icon" @click="removeDiaryRecipe(d)" title="删除">🗑️</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="myFilteredRecipes.length === 0" class="empty-hint">暂无个人配方</div>
|
||||
@@ -203,10 +196,11 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, reactive } from 'vue'
|
||||
import { ref, computed, reactive, onMounted, watch } from 'vue'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { useOilsStore } from '../stores/oils'
|
||||
import { useRecipesStore } from '../stores/recipes'
|
||||
import { useDiaryStore } from '../stores/diary'
|
||||
import { useUiStore } from '../stores/ui'
|
||||
import { api } from '../composables/useApi'
|
||||
import { showConfirm, showPrompt } from '../composables/useDialog'
|
||||
@@ -217,6 +211,7 @@ import TagPicker from '../components/TagPicker.vue'
|
||||
const auth = useAuthStore()
|
||||
const oils = useOilsStore()
|
||||
const recipeStore = useRecipesStore()
|
||||
const diaryStore = useDiaryStore()
|
||||
const ui = useUiStore()
|
||||
|
||||
const manageSearch = ref('')
|
||||
@@ -243,13 +238,11 @@ const tagPickerName = ref('')
|
||||
const tagPickerTags = ref([])
|
||||
|
||||
// Computed lists
|
||||
const myRecipes = computed(() =>
|
||||
recipeStore.recipes.filter(r => r._owner_id === auth.user.id)
|
||||
)
|
||||
// "我的配方" = diary (user_diary table), personal recipes
|
||||
const myRecipes = computed(() => diaryStore.userDiary)
|
||||
|
||||
const publicRecipes = computed(() =>
|
||||
recipeStore.recipes.filter(r => r._owner_id !== auth.user.id)
|
||||
)
|
||||
// "公共配方库" = all recipes in public library (recipes table)
|
||||
const publicRecipes = computed(() => recipeStore.recipes)
|
||||
|
||||
function filterBySearchAndTags(list) {
|
||||
let result = list
|
||||
@@ -257,7 +250,7 @@ function filterBySearchAndTags(list) {
|
||||
if (q) {
|
||||
result = result.filter(r =>
|
||||
r.name.toLowerCase().includes(q) ||
|
||||
r.ingredients.some(ing => ing.oil.toLowerCase().includes(q)) ||
|
||||
(r.ingredients || []).some(ing => (ing.oil || '').toLowerCase().includes(q)) ||
|
||||
(r.tags && r.tags.some(t => t.toLowerCase().includes(q)))
|
||||
)
|
||||
}
|
||||
@@ -401,6 +394,30 @@ async function saveCurrentRecipe() {
|
||||
}
|
||||
}
|
||||
|
||||
// Load diary on mount
|
||||
onMounted(async () => {
|
||||
if (auth.isLoggedIn) {
|
||||
await diaryStore.loadDiary()
|
||||
}
|
||||
})
|
||||
|
||||
function editDiaryRecipe(diary) {
|
||||
// For now, navigate to MyDiary page to edit
|
||||
// TODO: inline editing
|
||||
ui.showToast('请到「我的」页面编辑个人配方')
|
||||
}
|
||||
|
||||
async function removeDiaryRecipe(diary) {
|
||||
const ok = await showConfirm(`确定删除个人配方 "${diary.name}"?`)
|
||||
if (!ok) return
|
||||
try {
|
||||
await diaryStore.deleteDiary(diary.id)
|
||||
ui.showToast('已删除')
|
||||
} catch {
|
||||
ui.showToast('删除失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function removeRecipe(recipe) {
|
||||
const ok = await showConfirm(`确定删除配方 "${recipe.name}"?`)
|
||||
if (!ok) return
|
||||
@@ -414,10 +431,8 @@ async function removeRecipe(recipe) {
|
||||
|
||||
async function approveRecipe(recipe) {
|
||||
try {
|
||||
await api('/api/recipes/' + recipe._id + '/approve', { method: 'POST' })
|
||||
pendingRecipes.value = pendingRecipes.value.filter(r => r._id !== recipe._id)
|
||||
pendingCount.value--
|
||||
ui.showToast('已通过')
|
||||
await api('/api/recipes/' + recipe._id + '/adopt', { method: 'POST' })
|
||||
ui.showToast('已采纳')
|
||||
await recipeStore.loadRecipes()
|
||||
} catch {
|
||||
ui.showToast('操作失败')
|
||||
@@ -425,11 +440,11 @@ async function approveRecipe(recipe) {
|
||||
}
|
||||
|
||||
async function rejectRecipe(recipe) {
|
||||
const ok = await showConfirm(`确定删除「${recipe.name}」?`)
|
||||
if (!ok) return
|
||||
try {
|
||||
await api('/api/recipes/' + recipe._id + '/reject', { method: 'POST' })
|
||||
pendingRecipes.value = pendingRecipes.value.filter(r => r._id !== recipe._id)
|
||||
pendingCount.value--
|
||||
ui.showToast('已拒绝')
|
||||
await recipeStore.deleteRecipe(recipe._id)
|
||||
ui.showToast('已删除')
|
||||
} catch {
|
||||
ui.showToast('操作失败')
|
||||
}
|
||||
@@ -457,16 +472,13 @@ function onTagPickerSave(tags) {
|
||||
showTagPicker.value = false
|
||||
}
|
||||
|
||||
// Load pending if admin
|
||||
if (auth.isAdmin) {
|
||||
api('/api/recipes/pending').then(async res => {
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
pendingRecipes.value = data
|
||||
pendingCount.value = data.length
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
watch(() => recipeStore.recipes, () => {
|
||||
if (auth.isAdmin) {
|
||||
const pending = recipeStore.recipes.filter(r => r._owner_id && r._owner_id !== auth.user.id)
|
||||
pendingRecipes.value = pending
|
||||
pendingCount.value = pending.length
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -1,21 +1,38 @@
|
||||
<template>
|
||||
<div class="recipe-search">
|
||||
<!-- Category Carousel -->
|
||||
<div class="cat-wrap" v-if="categories.length">
|
||||
<button class="cat-arrow cat-arrow-left" @click="scrollCat(-1)" :disabled="catScrollPos <= 0">‹</button>
|
||||
<div class="cat-track" ref="catTrack">
|
||||
<!-- Category Carousel (full-width image slides) -->
|
||||
<div class="cat-wrap" v-if="categories.length && !selectedCategory">
|
||||
<div class="cat-track" :style="{ transform: `translateX(-${catIdx * 100}%)` }">
|
||||
<div
|
||||
v-for="cat in categories"
|
||||
:key="cat.name"
|
||||
class="cat-card"
|
||||
:class="{ active: selectedCategory === cat.name }"
|
||||
@click="toggleCategory(cat.name)"
|
||||
:style="{ backgroundImage: cat.bg_image ? `url(${cat.bg_image})` : `linear-gradient(135deg, ${cat.color_from || '#7a9e7e'}, ${cat.color_to || '#5a7d5e'})` }"
|
||||
@click="selectCategory(cat)"
|
||||
>
|
||||
<span class="cat-icon">{{ cat.icon || '📁' }}</span>
|
||||
<span class="cat-label">{{ cat.name }}</span>
|
||||
<div class="cat-inner">
|
||||
<div class="cat-icon">{{ cat.icon || '🌿' }}</div>
|
||||
<div class="cat-name">{{ cat.name }}</div>
|
||||
<div v-if="cat.subtitle" class="cat-sub">{{ cat.subtitle }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="cat-arrow cat-arrow-right" @click="scrollCat(1)">›</button>
|
||||
<button class="cat-arrow left" @click="slideCat(-1)">‹</button>
|
||||
<button class="cat-arrow right" @click="slideCat(1)">›</button>
|
||||
</div>
|
||||
<div class="cat-dots" v-if="categories.length > 1 && !selectedCategory">
|
||||
<span
|
||||
v-for="(cat, i) in categories"
|
||||
:key="i"
|
||||
class="cat-dot"
|
||||
:class="{ active: catIdx === i }"
|
||||
@click="catIdx = i"
|
||||
></span>
|
||||
</div>
|
||||
<!-- Category filter active banner -->
|
||||
<div v-if="selectedCategory" class="cat-filter-bar">
|
||||
<span>📂 {{ selectedCategory }}</span>
|
||||
<button @click="selectedCategory = null; catIdx = 0" class="btn-sm btn-outline">✕ 返回全部</button>
|
||||
</div>
|
||||
|
||||
<!-- Search Box -->
|
||||
@@ -33,28 +50,33 @@
|
||||
<!-- Personal Section (logged in) -->
|
||||
<div v-if="auth.isLoggedIn" class="personal-section">
|
||||
<div class="section-header" @click="showMyRecipes = !showMyRecipes">
|
||||
<span>📖 我的配方</span>
|
||||
<span>📖 我的配方 ({{ myDiaryRecipes.length }})</span>
|
||||
<span class="toggle-icon">{{ showMyRecipes ? '▾' : '▸' }}</span>
|
||||
</div>
|
||||
<div v-if="showMyRecipes" class="recipe-grid">
|
||||
<RecipeCard
|
||||
v-for="(r, i) in myRecipesPreview"
|
||||
:key="r._id"
|
||||
:recipe="r"
|
||||
:index="findGlobalIndex(r)"
|
||||
@click="openDetail(findGlobalIndex(r))"
|
||||
@toggle-fav="handleToggleFav(r)"
|
||||
/>
|
||||
<div v-if="myRecipesPreview.length === 0" class="empty-hint">暂无个人配方</div>
|
||||
<div
|
||||
v-for="d in myDiaryRecipes"
|
||||
:key="'diary-' + d.id"
|
||||
class="recipe-card diary-card"
|
||||
@click="openDiaryDetail(d)"
|
||||
>
|
||||
<div class="card-name">{{ d.name }}</div>
|
||||
<div class="card-oils">{{ (d.ingredients || []).map(i => i.oil).join('、') }}</div>
|
||||
<div class="card-bottom">
|
||||
<span class="card-price">{{ oils.fmtPrice(oils.calcCost(d.ingredients || [])) }}</span>
|
||||
<button class="share-btn" @click.stop="shareDiaryToPublic(d)" title="共享到公共配方库">📤</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="myDiaryRecipes.length === 0" class="empty-hint">暂无个人配方</div>
|
||||
</div>
|
||||
|
||||
<div class="section-header" @click="showFavorites = !showFavorites">
|
||||
<span>⭐ 收藏配方</span>
|
||||
<span>⭐ 收藏配方 ({{ favoritesPreview.length }})</span>
|
||||
<span class="toggle-icon">{{ showFavorites ? '▾' : '▸' }}</span>
|
||||
</div>
|
||||
<div v-if="showFavorites" class="recipe-grid">
|
||||
<RecipeCard
|
||||
v-for="(r, i) in favoritesPreview"
|
||||
v-for="r in favoritesPreview"
|
||||
:key="r._id"
|
||||
:recipe="r"
|
||||
:index="findGlobalIndex(r)"
|
||||
@@ -65,9 +87,9 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Fuzzy Search Results -->
|
||||
<div v-if="searchQuery && fuzzyResults.length" class="search-results-section">
|
||||
<div class="section-label">🔍 搜索结果 ({{ fuzzyResults.length }})</div>
|
||||
<!-- Search Results (public recipes) -->
|
||||
<div v-if="searchQuery" class="search-results-section">
|
||||
<div class="section-label">🔍 公共配方搜索结果 ({{ fuzzyResults.length }})</div>
|
||||
<div class="recipe-grid">
|
||||
<RecipeCard
|
||||
v-for="(r, i) in fuzzyResults"
|
||||
@@ -77,11 +99,12 @@
|
||||
@click="openDetail(findGlobalIndex(r))"
|
||||
@toggle-fav="handleToggleFav(r)"
|
||||
/>
|
||||
<div v-if="fuzzyResults.length === 0" class="empty-hint">未找到匹配的公共配方</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Public Recipe Grid -->
|
||||
<div v-if="!searchQuery || fuzzyResults.length === 0">
|
||||
<div v-if="!searchQuery">
|
||||
<div class="section-label">🌿 公共配方库 ({{ filteredRecipes.length }})</div>
|
||||
<div class="recipe-grid">
|
||||
<RecipeCard
|
||||
@@ -106,10 +129,12 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, nextTick } from 'vue'
|
||||
import { ref, computed, onMounted, nextTick, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { useOilsStore } from '../stores/oils'
|
||||
import { useRecipesStore } from '../stores/recipes'
|
||||
import { useDiaryStore } from '../stores/diary'
|
||||
import { useUiStore } from '../stores/ui'
|
||||
import { api } from '../composables/useApi'
|
||||
import RecipeCard from '../components/RecipeCard.vue'
|
||||
@@ -118,7 +143,10 @@ import RecipeDetailOverlay from '../components/RecipeDetailOverlay.vue'
|
||||
const auth = useAuthStore()
|
||||
const oils = useOilsStore()
|
||||
const recipeStore = useRecipesStore()
|
||||
const diaryStore = useDiaryStore()
|
||||
const ui = useUiStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const searchQuery = ref('')
|
||||
const selectedCategory = ref(null)
|
||||
@@ -126,31 +154,53 @@ const categories = ref([])
|
||||
const selectedRecipeIndex = ref(null)
|
||||
const showMyRecipes = ref(true)
|
||||
const showFavorites = ref(true)
|
||||
const catScrollPos = ref(0)
|
||||
const catTrack = ref(null)
|
||||
const catIdx = ref(0)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const res = await api('/api/category-modules')
|
||||
const res = await api('/api/categories')
|
||||
if (res.ok) {
|
||||
categories.value = await res.json()
|
||||
}
|
||||
} catch {
|
||||
// category modules are optional
|
||||
} catch {}
|
||||
|
||||
// Load personal diary recipes
|
||||
if (auth.isLoggedIn) {
|
||||
await diaryStore.loadDiary()
|
||||
}
|
||||
|
||||
// Return to a recipe card after QR upload redirect
|
||||
const openRecipeId = route.query.openRecipe
|
||||
if (openRecipeId) {
|
||||
router.replace({ path: '/', query: {} })
|
||||
const tryOpen = () => {
|
||||
const idx = recipeStore.recipes.findIndex(r => String(r._id) === String(openRecipeId))
|
||||
if (idx >= 0) {
|
||||
openDetail(idx)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
if (!tryOpen()) {
|
||||
// Recipes might not be loaded yet, watch until available
|
||||
const stop = watch(
|
||||
() => recipeStore.recipes.length,
|
||||
() => { if (tryOpen()) stop() },
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function toggleCategory(name) {
|
||||
selectedCategory.value = selectedCategory.value === name ? null : name
|
||||
function selectCategory(cat) {
|
||||
selectedCategory.value = cat.tag_name || cat.name
|
||||
}
|
||||
|
||||
function scrollCat(dir) {
|
||||
if (!catTrack.value) return
|
||||
const scrollAmount = 200
|
||||
catTrack.value.scrollLeft += dir * scrollAmount
|
||||
catScrollPos.value = catTrack.value.scrollLeft + dir * scrollAmount
|
||||
function slideCat(dir) {
|
||||
const len = categories.value.length
|
||||
catIdx.value = (catIdx.value + dir + len) % len
|
||||
}
|
||||
|
||||
// Public recipes (all recipes in the public library)
|
||||
const filteredRecipes = computed(() => {
|
||||
let list = recipeStore.recipes
|
||||
if (selectedCategory.value) {
|
||||
@@ -159,6 +209,7 @@ const filteredRecipes = computed(() => {
|
||||
return list
|
||||
})
|
||||
|
||||
// Search results from public recipes
|
||||
const fuzzyResults = computed(() => {
|
||||
if (!searchQuery.value.trim()) return []
|
||||
const q = searchQuery.value.trim().toLowerCase()
|
||||
@@ -170,11 +221,18 @@ const fuzzyResults = computed(() => {
|
||||
})
|
||||
})
|
||||
|
||||
const myRecipesPreview = computed(() => {
|
||||
// Personal recipes from diary (separate from public recipes)
|
||||
const myDiaryRecipes = computed(() => {
|
||||
if (!auth.isLoggedIn) return []
|
||||
return recipeStore.recipes
|
||||
.filter(r => r._owner_id === auth.user.id)
|
||||
.slice(0, 6)
|
||||
let list = diaryStore.userDiary
|
||||
if (searchQuery.value.trim()) {
|
||||
const q = searchQuery.value.trim().toLowerCase()
|
||||
list = list.filter(d => {
|
||||
return d.name.toLowerCase().includes(q) ||
|
||||
(d.ingredients || []).some(ing => ing.oil?.toLowerCase().includes(q))
|
||||
})
|
||||
}
|
||||
return list
|
||||
})
|
||||
|
||||
const favoritesPreview = computed(() => {
|
||||
@@ -194,6 +252,29 @@ function openDetail(index) {
|
||||
}
|
||||
}
|
||||
|
||||
function openDiaryDetail(diary) {
|
||||
// Create a temporary recipe-like object from diary and open it
|
||||
const tmpRecipe = {
|
||||
_id: null,
|
||||
_diary_id: diary.id,
|
||||
name: diary.name,
|
||||
note: diary.note || '',
|
||||
tags: diary.tags || [],
|
||||
ingredients: diary.ingredients || [],
|
||||
_owner_id: auth.user.id,
|
||||
}
|
||||
recipeStore.recipes.push(tmpRecipe)
|
||||
const tmpIdx = recipeStore.recipes.length - 1
|
||||
selectedRecipeIndex.value = tmpIdx
|
||||
// Clean up temp recipe when detail closes
|
||||
const unwatch = watch(selectedRecipeIndex, (val) => {
|
||||
if (val === null) {
|
||||
recipeStore.recipes.splice(tmpIdx, 1)
|
||||
unwatch()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function handleToggleFav(recipe) {
|
||||
if (!auth.isLoggedIn) {
|
||||
ui.openLogin()
|
||||
@@ -202,6 +283,31 @@ async function handleToggleFav(recipe) {
|
||||
await recipeStore.toggleFavorite(recipe._id)
|
||||
}
|
||||
|
||||
async function shareDiaryToPublic(diary) {
|
||||
const { showConfirm } = await import('../composables/useDialog')
|
||||
const ok = await showConfirm(`将「${diary.name}」共享到公共配方库?\n共享后所有用户都能看到。`)
|
||||
if (!ok) return
|
||||
try {
|
||||
await api('/api/recipes', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
name: diary.name,
|
||||
note: diary.note || '',
|
||||
ingredients: (diary.ingredients || []).map(i => ({ oil_name: i.oil, drops: i.drops })),
|
||||
tags: diary.tags || [],
|
||||
}),
|
||||
})
|
||||
if (auth.isAdmin) {
|
||||
ui.showToast('已共享到公共配方库')
|
||||
} else {
|
||||
ui.showToast('已提交,等待管理员审核')
|
||||
}
|
||||
await recipeStore.loadRecipes()
|
||||
} catch {
|
||||
ui.showToast('共享失败')
|
||||
}
|
||||
}
|
||||
|
||||
function onSearch() {
|
||||
// fuzzyResults computed handles the filtering reactively
|
||||
}
|
||||
@@ -219,81 +325,127 @@ function clearSearch() {
|
||||
|
||||
.cat-wrap {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
gap: 4px;
|
||||
margin: 0 -12px 20px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.cat-track {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
overflow-x: auto;
|
||||
scroll-behavior: smooth;
|
||||
flex: 1;
|
||||
padding: 8px 0;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.cat-track::-webkit-scrollbar {
|
||||
display: none;
|
||||
transition: transform 0.4s ease;
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
.cat-card {
|
||||
flex: 0 0 100%;
|
||||
min-height: 200px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
}
|
||||
|
||||
.cat-card::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(135deg, rgba(0,0,0,0.45), rgba(0,0,0,0.25));
|
||||
}
|
||||
|
||||
.cat-inner {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 10px 16px;
|
||||
border-radius: 12px;
|
||||
background: #f8f7f5;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
font-size: 13px;
|
||||
transition: all 0.2s;
|
||||
min-width: 64px;
|
||||
border: 1.5px solid transparent;
|
||||
}
|
||||
|
||||
.cat-card:hover {
|
||||
background: #f0eeeb;
|
||||
}
|
||||
|
||||
.cat-card.active {
|
||||
background: linear-gradient(135deg, #e8f5e9, #c8e6c9);
|
||||
border-color: #7ec6a4;
|
||||
color: #2e7d5a;
|
||||
font-weight: 600;
|
||||
padding: 36px 24px;
|
||||
color: white;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.cat-icon {
|
||||
font-size: 20px;
|
||||
font-size: 48px;
|
||||
margin-bottom: 10px;
|
||||
filter: drop-shadow(0 2px 6px rgba(0,0,0,0.3));
|
||||
}
|
||||
|
||||
.cat-name {
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 3px;
|
||||
text-shadow: 0 2px 8px rgba(0,0,0,0.5);
|
||||
}
|
||||
|
||||
.cat-sub {
|
||||
font-size: 13px;
|
||||
margin-top: 6px;
|
||||
opacity: 0.9;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.cat-arrow {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
z-index: 2;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
background: rgba(255,255,255,0.25);
|
||||
border: none;
|
||||
color: white;
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
backdrop-filter: blur(4px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
.cat-arrow:hover { background: rgba(255,255,255,0.45); }
|
||||
.cat-arrow.left { left: 12px; }
|
||||
.cat-arrow.right { right: 12px; }
|
||||
|
||||
.cat-dots {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.cat-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--border, #e0d4c0);
|
||||
cursor: pointer;
|
||||
transition: all 0.25s;
|
||||
}
|
||||
.cat-dot.active {
|
||||
background: var(--sage, #7a9e7e);
|
||||
width: 22px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.cat-filter-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
background: var(--sage-mist, #eef4ee);
|
||||
border-radius: 10px;
|
||||
padding: 10px 16px;
|
||||
margin-bottom: 16px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--sage-dark, #5a7d5e);
|
||||
}
|
||||
|
||||
.cat-label {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.cat-arrow {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid #d4cfc7;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
color: #6b6375;
|
||||
}
|
||||
|
||||
.cat-arrow:disabled {
|
||||
opacity: 0.3;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.search-box {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -390,6 +542,55 @@ function clearSearch() {
|
||||
padding: 24px 0;
|
||||
}
|
||||
|
||||
.diary-card {
|
||||
background: white;
|
||||
border-radius: 14px;
|
||||
padding: 16px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.06);
|
||||
border: 2px solid transparent;
|
||||
border-left: 3px solid var(--sage, #7a9e7e);
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.diary-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 16px rgba(0,0,0,0.1);
|
||||
}
|
||||
.diary-card .card-name {
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: #2c2416;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.diary-card .card-oils {
|
||||
font-size: 12px;
|
||||
color: #9a8570;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.diary-card .card-bottom {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.diary-card .card-price {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--sage-dark, #5a7d5e);
|
||||
}
|
||||
|
||||
.share-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
padding: 2px 4px;
|
||||
border-radius: 6px;
|
||||
opacity: 0.5;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
.share-btn:hover { opacity: 1; }
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.recipe-grid {
|
||||
grid-template-columns: 1fr;
|
||||
|
||||
2
node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json
generated
vendored
2
node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json
generated
vendored
@@ -1 +1 @@
|
||||
{"version":"4.1.2","results":[[":frontend/src/__tests__/volumeDilution.test.js",{"duration":5.926774999999992,"failed":false}],[":frontend/src/__tests__/smartPaste.test.js",{"duration":16.112632000000005,"failed":false}],[":frontend/src/__tests__/oilCalculations.test.js",{"duration":11.990026,"failed":false}],[":frontend/src/__tests__/dialog.test.js",{"duration":4.135876999999994,"failed":false}],[":frontend/src/__tests__/oilTranslation.test.js",{"duration":4.413353999999998,"failed":false}]]}
|
||||
{"version":"4.1.2","results":[[":frontend/src/__tests__/volumeDilution.test.js",{"duration":6.227510999999993,"failed":false}],[":frontend/src/__tests__/smartPaste.test.js",{"duration":14.144011000000006,"failed":false}],[":frontend/src/__tests__/oilCalculations.test.js",{"duration":18.03941499999999,"failed":false}],[":frontend/src/__tests__/dialog.test.js",{"duration":3.7299579999999963,"failed":false}],[":frontend/src/__tests__/oilTranslation.test.js",{"duration":5.783867999999998,"failed":false}]]}
|
||||
259
scripts/deploy-preview.py
Normal file
259
scripts/deploy-preview.py
Normal file
@@ -0,0 +1,259 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deploy or teardown a PR preview environment on local k3s.
|
||||
|
||||
Runs directly on the oci server (where k3s and docker are local).
|
||||
|
||||
Usage:
|
||||
python3 scripts/deploy-preview.py deploy <PR_ID>
|
||||
python3 scripts/deploy-preview.py teardown <PR_ID>
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import json
|
||||
import tempfile
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
|
||||
REGISTRY = "registry.oci.euphon.net"
|
||||
BASE_DOMAIN = "oil.oci.euphon.net"
|
||||
PROD_NS = "oil-calculator"
|
||||
|
||||
|
||||
def run(cmd: list[str] | str, *, check=True, capture=False) -> subprocess.CompletedProcess:
|
||||
"""Run a command, print it, and optionally check for errors."""
|
||||
if isinstance(cmd, str):
|
||||
cmd = ["sh", "-c", cmd]
|
||||
display = " ".join(cmd) if isinstance(cmd, list) else cmd
|
||||
print(f" $ {display}")
|
||||
r = subprocess.run(cmd, text=True, capture_output=capture)
|
||||
if capture and r.stdout.strip():
|
||||
for line in r.stdout.strip().splitlines()[:5]:
|
||||
print(f" {line}")
|
||||
if check and r.returncode != 0:
|
||||
print(f" FAILED (exit {r.returncode})")
|
||||
if capture and r.stderr.strip():
|
||||
print(f" {r.stderr.strip()[:200]}")
|
||||
sys.exit(1)
|
||||
return r
|
||||
|
||||
|
||||
def kubectl(*args, capture=False, check=True) -> subprocess.CompletedProcess:
|
||||
return run(["sudo", "k3s", "kubectl", *args], capture=capture, check=check)
|
||||
|
||||
|
||||
def docker(*args, check=True) -> subprocess.CompletedProcess:
|
||||
return run(["docker", *args], check=check)
|
||||
|
||||
|
||||
def write_temp(content: str, suffix=".yaml") -> Path:
|
||||
"""Write content to a temp file and return its path."""
|
||||
f = tempfile.NamedTemporaryFile(mode="w", suffix=suffix, delete=False)
|
||||
f.write(content)
|
||||
f.close()
|
||||
return Path(f.name)
|
||||
|
||||
|
||||
# ─── Deploy ──────────────────────────────────────────────
|
||||
|
||||
def deploy(pr_id: str):
|
||||
ns = f"oil-pr-{pr_id}"
|
||||
host = f"pr-{pr_id}.{BASE_DOMAIN}"
|
||||
image = f"{REGISTRY}/oil-calculator:pr-{pr_id}"
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f" Deploying: https://{host}")
|
||||
print(f" Namespace: {ns}")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
# 1. Copy production DB into build context
|
||||
print("[1/5] Copying production database...")
|
||||
Path("data").mkdir(exist_ok=True)
|
||||
prod_pod = kubectl(
|
||||
"get", "pods", "-n", PROD_NS,
|
||||
"-l", "app=oil-calculator",
|
||||
"--field-selector=status.phase=Running",
|
||||
"-o", "jsonpath={.items[0].metadata.name}",
|
||||
capture=True, check=False
|
||||
).stdout.strip()
|
||||
|
||||
if prod_pod:
|
||||
kubectl("cp", f"{PROD_NS}/{prod_pod}:/data/oil_calculator.db", "data/oil_calculator.db")
|
||||
else:
|
||||
print(" WARNING: No running prod pod, using empty DB")
|
||||
Path("data/oil_calculator.db").touch()
|
||||
|
||||
# 2. Build and push image
|
||||
print("[2/5] Building Docker image...")
|
||||
dockerfile = textwrap.dedent("""\
|
||||
FROM node:20-slim AS frontend-build
|
||||
WORKDIR /build
|
||||
COPY frontend/package.json frontend/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM python:3.12-slim
|
||||
WORKDIR /app
|
||||
COPY backend/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY backend/ ./backend/
|
||||
COPY --from=frontend-build /build/dist ./frontend/
|
||||
COPY data/oil_calculator.db /data/oil_calculator.db
|
||||
ENV DB_PATH=/data/oil_calculator.db
|
||||
ENV FRONTEND_DIR=/app/frontend
|
||||
EXPOSE 8000
|
||||
CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
""")
|
||||
df = write_temp(dockerfile, suffix=".Dockerfile")
|
||||
docker("build", "-f", str(df), "-t", image, ".")
|
||||
df.unlink()
|
||||
docker("push", image)
|
||||
|
||||
# 3. Create namespace + regcred
|
||||
print("[3/5] Creating namespace...")
|
||||
kubectl("create", "namespace", ns, "--dry-run=client", "-o", "yaml",
|
||||
check=False) # just for display
|
||||
run(f"sudo k3s kubectl create namespace {ns} --dry-run=client -o yaml | sudo k3s kubectl apply -f -")
|
||||
|
||||
# Copy regcred from prod namespace
|
||||
r = kubectl("get", "secret", "regcred", "-n", PROD_NS, "-o", "json", capture=True)
|
||||
secret = json.loads(r.stdout)
|
||||
secret["metadata"] = {"name": "regcred", "namespace": ns}
|
||||
p = write_temp(json.dumps(secret), suffix=".json")
|
||||
kubectl("apply", "-f", str(p))
|
||||
p.unlink()
|
||||
|
||||
# 4. Apply manifests
|
||||
print("[4/5] Applying K8s resources...")
|
||||
manifests = textwrap.dedent(f"""\
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: oil-calculator
|
||||
namespace: {ns}
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: oil-calculator
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: oil-calculator
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- name: regcred
|
||||
containers:
|
||||
- name: app
|
||||
image: {image}
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- containerPort: 8000
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 256Mi
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: oil-calculator
|
||||
namespace: {ns}
|
||||
spec:
|
||||
selector:
|
||||
app: oil-calculator
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 8000
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: oil-calculator
|
||||
namespace: {ns}
|
||||
annotations:
|
||||
traefik.ingress.kubernetes.io/router.tls.certresolver: le
|
||||
spec:
|
||||
ingressClassName: traefik
|
||||
tls:
|
||||
- hosts:
|
||||
- {host}
|
||||
rules:
|
||||
- host: {host}
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: oil-calculator
|
||||
port:
|
||||
number: 80
|
||||
""")
|
||||
p = write_temp(manifests)
|
||||
kubectl("apply", "-f", str(p))
|
||||
p.unlink()
|
||||
|
||||
# 5. Restart to pick up new image and wait
|
||||
print("[5/5] Restarting deployment...")
|
||||
kubectl("rollout", "restart", "deploy/oil-calculator", "-n", ns)
|
||||
kubectl("rollout", "status", "deploy/oil-calculator", "-n", ns, "--timeout=120s")
|
||||
|
||||
# Cleanup
|
||||
run("rm -rf data/oil_calculator.db", check=False)
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f" Preview live: https://{host}")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
|
||||
# ─── Teardown ────────────────────────────────────────────
|
||||
|
||||
def teardown(pr_id: str):
|
||||
ns = f"oil-pr-{pr_id}"
|
||||
image = f"{REGISTRY}/oil-calculator:pr-{pr_id}"
|
||||
|
||||
print(f"\n Tearing down: {ns}")
|
||||
kubectl("delete", "namespace", ns, "--ignore-not-found")
|
||||
docker("rmi", image, check=False)
|
||||
print(" Done.\n")
|
||||
|
||||
|
||||
# ─── Deploy Production ───────────────────────────────────
|
||||
|
||||
def deploy_prod():
|
||||
image = f"{REGISTRY}/oil-calculator:latest"
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f" Deploying production: https://{BASE_DOMAIN}")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
docker("build", "-t", image, ".")
|
||||
docker("push", image)
|
||||
kubectl("rollout", "restart", "deploy/oil-calculator", "-n", PROD_NS)
|
||||
kubectl("rollout", "status", "deploy/oil-calculator", "-n", PROD_NS, "--timeout=120s")
|
||||
|
||||
print(f"\n Production deployed: https://{BASE_DOMAIN}\n")
|
||||
|
||||
|
||||
# ─── Main ────────────────────────────────────────────────
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
|
||||
action = sys.argv[1]
|
||||
if action == "deploy" and len(sys.argv) >= 3:
|
||||
deploy(sys.argv[2])
|
||||
elif action == "teardown" and len(sys.argv) >= 3:
|
||||
teardown(sys.argv[2])
|
||||
elif action == "deploy-prod":
|
||||
deploy_prod()
|
||||
else:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user