Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eb2e445398 | |||
| 61b8812808 | |||
| f7838bd919 | |||
| b0fd3f4187 | |||
| b91717fc19 | |||
| a065adcd82 | |||
| 6edf2fa341 | |||
| 9e3d548536 | |||
| e55e415a50 | |||
| 5253d14af7 | |||
| 4f75d78a2b | |||
| 8f9b65147b |
@@ -129,13 +129,26 @@ Apply these rules strictly:
|
||||
|
||||
## Task 3: Execute Release
|
||||
|
||||
Use the release script whenever possible:
|
||||
Use the release script — it is **fully non-interactive** (no y/N prompts) and handles the entire flow automatically:
|
||||
|
||||
```bash
|
||||
./scripts/release.sh <patch|minor|major>
|
||||
./scripts/release.sh <patch|minor|major|x.y.z>
|
||||
```
|
||||
|
||||
This script handles: branch creation → version bump → PR → CI wait → merge → signed tag → push.
|
||||
The script performs these steps in order:
|
||||
1. Checks out and updates `main`
|
||||
2. Creates release branch `chore/release-X.Y.Z`
|
||||
3. Bumps version in `backend/package.json` and `frontend/package.json`
|
||||
4. Commits, pushes, and creates a PR
|
||||
5. Waits for CI checks (with retry logic — polls every 15s, waits up to 10 minutes)
|
||||
6. Merges the PR (squash + delete branch)
|
||||
7. Creates a signed tag `vX.Y.Z` and pushes it
|
||||
|
||||
**The script auto-detects the git remote** (`origin` or `github`) and uses it consistently.
|
||||
|
||||
**CI wait behavior:** GitHub Actions can take 10-30 seconds before checks appear on a new PR. The script waits 20 seconds initially, then polls every 15 seconds until checks are registered, then watches them to completion. Maximum wait is 10 minutes.
|
||||
|
||||
**On failure:** If CI fails, the script exits with an error. The release branch and PR remain open for inspection. Fix the issue, push to the branch, and the PR will re-run CI. Then merge manually or re-run the script.
|
||||
|
||||
### Version Files (MANDATORY)
|
||||
|
||||
@@ -166,8 +179,8 @@ The version number is displayed in the **About modal** (Settings → About) as a
|
||||
|
||||
### After Tagging
|
||||
|
||||
- The `docker-build.yml` workflow automatically builds and pushes Docker images to GHCR.
|
||||
- The `version-bump.yml` workflow automatically updates `package.json` versions if needed.
|
||||
- The `docker-build.yml` workflow automatically builds and pushes Docker images to GHCR with both versioned tags (`1.8.7`, `1.8`) and `latest`.
|
||||
- The `update-test-badges.yml` workflow runs automatically after a successful Docker build to update test count badges in the README.
|
||||
- Track progress: `https://github.com/DanielVolz/medassist-ng/actions`
|
||||
|
||||
---
|
||||
|
||||
@@ -4,12 +4,13 @@
|
||||
|
||||
- **English is the primary language**: All code, comments, documentation, commit messages, PR descriptions, and GitHub releases MUST be written in English. The user may communicate in German, but all project artifacts must be in English.
|
||||
- **NEVER release without explicit permission**: Do NOT create tags, releases, or version bumps unless the user explicitly asks for it. Always wait for explicit confirmation before any release action.
|
||||
- **NEVER create PRs without explicit permission**: Do NOT create Pull Requests, push branches, or merge code unless the user explicitly asks for it. Always present changes and wait for the user to confirm before any git operations that affect the remote repository.
|
||||
- **NEVER create PRs, push, or merge**: Only the **release-manager agent** (`@release-manager`) is allowed to create Pull Requests, push branches to the remote, or merge code. Regular agents and Copilot MUST NOT perform any git operations that affect the remote repository (no `git push`, no `gh pr create`, no `gh pr merge`). Present your local changes and tell the user to invoke `@release-manager` when ready to ship.
|
||||
- **No temporary files**: Delete temporary scripts/files immediately after use. Do not commit temporary debug scripts, test files, or one-off utilities to the repository.
|
||||
- **Clean workspace**: Always clean up after yourself. If you create a file for a specific task, delete it once done.
|
||||
- **Remove old code when re-implementing**: When fixing a bug or re-implementing a feature that didn't work, ALWAYS remove the old/broken code completely. Never leave dead code, unused functions, or obsolete implementations in the codebase.
|
||||
- **Tests are mandatory**: Every new feature and every bug fix MUST have corresponding tests. When modifying existing features, update or add tests accordingly. If old tests become obsolete due to code changes, remove or update them.
|
||||
- **Fix bugs, don't test around them**: If you discover incorrect behavior in the code while writing tests, ALWAYS fix the buggy code first, then write tests that verify the correct behavior. NEVER write tests that mimic or assert broken behavior. The user's time is finite and irreplaceable — every bug left unfixed wastes it.
|
||||
- **Keep README.md up to date**: After implementing code changes, check whether the `README.md` needs to be updated (e.g., new features, changed ENV variables, new commands, changed architecture, new endpoints, updated screenshots). If changes are relevant to the README, **ask the user for confirmation** before updating it. Do NOT silently update the README — always present the proposed README changes and wait for approval. Examples of README-relevant changes: new ENV variables, new API endpoints, new UI features, changed setup/install steps, new dependencies, changed Docker configuration.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
@@ -137,11 +138,16 @@ Push to main / Tag created
|
||||
↓
|
||||
┌─────────────────────────────────────┐
|
||||
│ docker-build.yml │
|
||||
│ ├─ backend-test (parallel) │
|
||||
│ ├─ frontend-build (parallel) │
|
||||
│ └─ build-and-push (after tests) │
|
||||
│ └─ build-and-push │
|
||||
│ ├─ Build Docker images │
|
||||
│ └─ Push to GHCR │
|
||||
│ (Tag builds also set "latest") │
|
||||
└─────────────────────────────────────┘
|
||||
↓ After successful build
|
||||
┌─────────────────────────────────────┐
|
||||
│ update-test-badges.yml │
|
||||
│ (workflow_run after docker-build) │
|
||||
│ └─ Run tests, update badge counts │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
@@ -178,7 +184,9 @@ gh pr merge --squash --delete-branch
|
||||
| File | Trigger | Purpose |
|
||||
|------|---------|--------|
|
||||
| `.github/workflows/test.yml` | Pull Requests | Run tests, block PR on failures |
|
||||
| `.github/workflows/docker-build.yml` | Push to main, Tags | Tests + Build and push Docker images |
|
||||
| `.github/workflows/docker-build.yml` | Push to main, Tags | Build and push Docker images (+ create GitHub release on tags) |
|
||||
| `.github/workflows/update-test-badges.yml` | After successful docker-build | Update test count badges in README |
|
||||
| `.github/workflows/codeql.yml` | Push to main, PRs, Weekly | Security analysis |
|
||||
|
||||
## Key Patterns
|
||||
|
||||
|
||||
@@ -25,50 +25,15 @@ env:
|
||||
|
||||
jobs:
|
||||
# =============================================================================
|
||||
# Run Tests First
|
||||
# =============================================================================
|
||||
backend-test:
|
||||
name: Backend Tests
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
defaults:
|
||||
run:
|
||||
working-directory: backend
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: backend/package-lock.json
|
||||
- run: npm ci
|
||||
- run: npx tsc --noEmit
|
||||
- run: npm run test:run
|
||||
|
||||
frontend-build:
|
||||
name: Frontend Build
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
defaults:
|
||||
run:
|
||||
working-directory: frontend
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
|
||||
# =============================================================================
|
||||
# Build and Push Docker Images (only after tests pass)
|
||||
# Build and Push Docker Images
|
||||
# Tests are NOT run here — branch protection on main requires all PR checks
|
||||
# (backend-test + frontend-build from test.yml) to pass before merge.
|
||||
# Tags are created from main, so code is already tested.
|
||||
#
|
||||
# Tag builds (v*) always set "latest" in addition to the semver tags.
|
||||
# This ensures "latest" always points to the most recent release.
|
||||
# =============================================================================
|
||||
build-and-push:
|
||||
needs: [backend-test, frontend-build]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -106,7 +71,7 @@ jobs:
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=raw,value=${{ github.event.inputs.tag || 'latest' }},enable=${{ github.event_name == 'workflow_dispatch' }}
|
||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
name: Create Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get version info
|
||||
id: version
|
||||
run: |
|
||||
CURRENT_TAG=${GITHUB_REF#refs/tags/}
|
||||
VERSION=${CURRENT_TAG#v}
|
||||
echo "tag=$CURRENT_TAG" >> $GITHUB_OUTPUT
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
# Get previous tag
|
||||
PREV_TAG=$(git tag --sort=-v:refname | grep -A1 "^${CURRENT_TAG}$" | tail -1)
|
||||
if [ "$PREV_TAG" = "$CURRENT_TAG" ]; then
|
||||
PREV_TAG=""
|
||||
fi
|
||||
echo "previous_tag=$PREV_TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Generate release template
|
||||
run: |
|
||||
cat > release_notes.md << 'EOF'
|
||||
## What's New
|
||||
|
||||
<!--
|
||||
Write 1-2 sentences describing the main changes in this release.
|
||||
Example: This release introduces a medication refill tracking feature and improves the mobile user experience.
|
||||
-->
|
||||
|
||||
### New Features
|
||||
|
||||
<!-- List new features with **bold** names and descriptions -->
|
||||
- **Feature Name**: Description of the feature
|
||||
|
||||
### Improvements
|
||||
|
||||
<!-- List improvements and fixes -->
|
||||
- **Improvement**: Description
|
||||
|
||||
### Where to Find It
|
||||
|
||||
<!-- Tell users where they can access new features -->
|
||||
|
||||
---
|
||||
|
||||
## Docker Images
|
||||
|
||||
```bash
|
||||
docker pull ghcr.io/danielvolz/medassist-ng-backend:${{ steps.version.outputs.version }}
|
||||
docker pull ghcr.io/danielvolz/medassist-ng-frontend:${{ steps.version.outputs.version }}
|
||||
```
|
||||
|
||||
**Full Changelog**: https://github.com/DanielVolz/medassist-ng/compare/${{ steps.version.outputs.previous_tag }}...${{ steps.version.outputs.tag }}
|
||||
EOF
|
||||
|
||||
- name: Create Draft Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
body_path: release_notes.md
|
||||
draft: true
|
||||
generate_release_notes: false
|
||||
name: "Release ${{ steps.version.outputs.tag }}"
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -2,13 +2,10 @@ name: Update Test Badges
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
workflow_run:
|
||||
workflows: ["Build and Push Docker Images"]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'backend/src/**'
|
||||
- 'frontend/src/**'
|
||||
- 'backend/package.json'
|
||||
- 'frontend/package.json'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -17,12 +14,14 @@ jobs:
|
||||
update-badges:
|
||||
name: Update Test Count Badges
|
||||
runs-on: ubuntu-latest
|
||||
# Only run after successful docker builds, not failed ones
|
||||
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
token: ${{ secrets.BADGE_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
name: Version Bump on Release
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
version-bump:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Get version from tag
|
||||
id: version
|
||||
run: |
|
||||
# Extract version from tag (e.g., v1.6.0 -> 1.6.0)
|
||||
VERSION="${GITHUB_REF_NAME#v}"
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "Extracted version: $VERSION"
|
||||
|
||||
- name: Update package.json versions
|
||||
run: |
|
||||
VERSION="${{ steps.version.outputs.version }}"
|
||||
|
||||
# Update backend/package.json
|
||||
jq --arg v "$VERSION" '.version = $v' backend/package.json > backend/package.json.tmp
|
||||
mv backend/package.json.tmp backend/package.json
|
||||
|
||||
# Update frontend/package.json
|
||||
jq --arg v "$VERSION" '.version = $v' frontend/package.json > frontend/package.json.tmp
|
||||
mv frontend/package.json.tmp frontend/package.json
|
||||
|
||||
echo "Updated versions to $VERSION"
|
||||
cat backend/package.json | head -5
|
||||
cat frontend/package.json | head -5
|
||||
|
||||
- name: Commit and push
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
git add backend/package.json frontend/package.json
|
||||
|
||||
# Only commit if there are changes
|
||||
if git diff --staged --quiet; then
|
||||
echo "No version changes needed"
|
||||
else
|
||||
git commit -m "chore: bump version to ${{ steps.version.outputs.version }} [skip ci]"
|
||||
git push origin main
|
||||
fi
|
||||
@@ -18,8 +18,8 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/Backend_Tests-454%2F454-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
|
||||
<img src="https://img.shields.io/badge/Frontend_Tests-611%2F611-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
|
||||
<img src="https://img.shields.io/badge/Backend_Tests-494%2F494-brightgreen?logo=vitest" alt="Backend Tests 454/454" />
|
||||
<img src="https://img.shields.io/badge/Frontend_Tests-645%2F645-brightgreen?logo=vitest" alt="Frontend Tests 611/611" />
|
||||
</p>
|
||||
|
||||
### 🤖 AI-Generated Code
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "medassist-ng-backend",
|
||||
"version": "1.8.5",
|
||||
"version": "1.8.7",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -52,7 +52,6 @@ services:
|
||||
- /tmp:noexec,nosuid,size=64m
|
||||
- /var/cache/nginx:noexec,nosuid,size=64m
|
||||
- /var/run:noexec,nosuid,size=64m
|
||||
- /etc/nginx/conf.d:noexec,nosuid,size=1m,uid=101,gid=101
|
||||
cap_drop:
|
||||
- ALL
|
||||
|
||||
|
||||
@@ -32,6 +32,11 @@ RUN npm run build
|
||||
# -----------------------------------------------------------------------------
|
||||
FROM nginxinc/nginx-unprivileged:1.27-alpine AS runner
|
||||
|
||||
# Redirect envsubst output to /tmp (writable under read_only: true)
|
||||
# and update nginx main config to include from there instead of /etc/nginx/conf.d/
|
||||
ENV NGINX_ENVSUBST_OUTPUT_DIR=/tmp
|
||||
RUN sed -i 's|include /etc/nginx/conf.d/\*.conf;|include /tmp/default.conf;|' /etc/nginx/nginx.conf
|
||||
|
||||
# Copy custom nginx config as template for envsubst processing
|
||||
# nginx-unprivileged automatically substitutes env vars in .template files
|
||||
COPY nginx.conf /etc/nginx/templates/default.conf.template
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "medassist-ng-frontend",
|
||||
"private": true,
|
||||
"version": "1.8.5",
|
||||
"version": "1.8.7",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -278,7 +278,8 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
systemLocale,
|
||||
settingsHook.settings.reminderDaysBefore,
|
||||
settingsHook.settings.stockCalculationMode,
|
||||
doses.takenDoses
|
||||
doses.takenDoses,
|
||||
doses.takenDoseTimestamps
|
||||
),
|
||||
[
|
||||
medications.meds,
|
||||
@@ -287,6 +288,7 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
settingsHook.settings.reminderDaysBefore,
|
||||
settingsHook.settings.stockCalculationMode,
|
||||
doses.takenDoses,
|
||||
doses.takenDoseTimestamps,
|
||||
]
|
||||
);
|
||||
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
// useDoses Hook - Dose tracking state and operations
|
||||
// =============================================================================
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
export interface UseDosesReturn {
|
||||
takenDoses: Set<string>;
|
||||
setTakenDoses: React.Dispatch<React.SetStateAction<Set<string>>>;
|
||||
takenDoseTimestamps: Map<string, number>;
|
||||
dismissedDoses: Set<string>;
|
||||
showClearMissedConfirm: boolean;
|
||||
setShowClearMissedConfirm: (show: boolean) => void;
|
||||
@@ -19,25 +20,39 @@ export interface UseDosesReturn {
|
||||
|
||||
export function useDoses(): UseDosesReturn {
|
||||
const [takenDoses, setTakenDoses] = useState<Set<string>>(new Set());
|
||||
const [takenDoseTimestamps, setTakenDoseTimestamps] = useState<Map<string, number>>(new Map());
|
||||
const [dismissedDoses, setDismissedDoses] = useState<Set<string>>(new Set());
|
||||
const [showClearMissedConfirm, setShowClearMissedConfirm] = useState(false);
|
||||
|
||||
// Track in-flight mutations to prevent polling from overwriting optimistic updates
|
||||
const mutationInFlightRef = useRef(0);
|
||||
|
||||
// Load taken doses from server
|
||||
const loadTakenDoses = useCallback(async () => {
|
||||
// Skip polling while mutations are in-flight to prevent race conditions
|
||||
// where a poll response with stale data overwrites optimistic updates
|
||||
if (mutationInFlightRef.current > 0) return;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/doses/taken", { credentials: "include" });
|
||||
if (res.ok) {
|
||||
// Double-check no mutation started while we were fetching
|
||||
if (mutationInFlightRef.current > 0) return;
|
||||
|
||||
const data = await res.json();
|
||||
const taken = new Set<string>();
|
||||
const timestamps = new Map<string, number>();
|
||||
const dismissed = new Set<string>();
|
||||
for (const d of data.doses) {
|
||||
if (d.dismissed) {
|
||||
dismissed.add(d.doseId);
|
||||
} else {
|
||||
taken.add(d.doseId);
|
||||
timestamps.set(d.doseId, d.takenAt);
|
||||
}
|
||||
}
|
||||
setTakenDoses(taken);
|
||||
setTakenDoseTimestamps(timestamps);
|
||||
setDismissedDoses(dismissed);
|
||||
}
|
||||
// Don't reset on error - keep current state
|
||||
@@ -77,59 +92,91 @@ export function useDoses(): UseDosesReturn {
|
||||
[takenDoses, getDoseId]
|
||||
);
|
||||
|
||||
const markDoseTaken = useCallback(async (doseId: string) => {
|
||||
// Optimistic update
|
||||
setTakenDoses((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.add(doseId);
|
||||
return next;
|
||||
});
|
||||
|
||||
// Send to server
|
||||
try {
|
||||
await fetch("/api/doses/taken", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ doseId }),
|
||||
});
|
||||
} catch {
|
||||
// Revert on error
|
||||
setTakenDoses((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(doseId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
const undoDoseTaken = useCallback(async (doseId: string) => {
|
||||
// Optimistic update
|
||||
setTakenDoses((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(doseId);
|
||||
return next;
|
||||
});
|
||||
|
||||
// Send to server
|
||||
try {
|
||||
await fetch(`/api/doses/taken/${encodeURIComponent(doseId)}`, {
|
||||
method: "DELETE",
|
||||
credentials: "include",
|
||||
});
|
||||
} catch {
|
||||
// Revert on error
|
||||
const markDoseTaken = useCallback(
|
||||
async (doseId: string) => {
|
||||
// Optimistic update
|
||||
mutationInFlightRef.current++;
|
||||
setTakenDoses((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.add(doseId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
setTakenDoseTimestamps((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(doseId, Date.now());
|
||||
return next;
|
||||
});
|
||||
|
||||
// Send to server
|
||||
try {
|
||||
await fetch("/api/doses/taken", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ doseId }),
|
||||
});
|
||||
} catch {
|
||||
// Revert on error
|
||||
setTakenDoses((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(doseId);
|
||||
return next;
|
||||
});
|
||||
setTakenDoseTimestamps((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.delete(doseId);
|
||||
return next;
|
||||
});
|
||||
} finally {
|
||||
mutationInFlightRef.current--;
|
||||
// Re-sync with server after mutation completes
|
||||
loadTakenDoses();
|
||||
}
|
||||
},
|
||||
[loadTakenDoses]
|
||||
);
|
||||
|
||||
const undoDoseTaken = useCallback(
|
||||
async (doseId: string) => {
|
||||
// Optimistic update
|
||||
mutationInFlightRef.current++;
|
||||
setTakenDoses((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(doseId);
|
||||
return next;
|
||||
});
|
||||
setTakenDoseTimestamps((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.delete(doseId);
|
||||
return next;
|
||||
});
|
||||
|
||||
// Send to server
|
||||
try {
|
||||
await fetch(`/api/doses/taken/${encodeURIComponent(doseId)}`, {
|
||||
method: "DELETE",
|
||||
credentials: "include",
|
||||
});
|
||||
} catch {
|
||||
// Revert on error
|
||||
setTakenDoses((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.add(doseId);
|
||||
return next;
|
||||
});
|
||||
} finally {
|
||||
mutationInFlightRef.current--;
|
||||
// Re-sync with server after mutation completes
|
||||
loadTakenDoses();
|
||||
}
|
||||
},
|
||||
[loadTakenDoses]
|
||||
);
|
||||
|
||||
return {
|
||||
takenDoses,
|
||||
setTakenDoses,
|
||||
takenDoseTimestamps,
|
||||
dismissedDoses,
|
||||
showClearMissedConfirm,
|
||||
setShowClearMissedConfirm,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import type { Coverage, FormState, Medication, RefillEntry } from "../types";
|
||||
import { getMedTotal } from "../types";
|
||||
import { getMedTotal, getPackageSize } from "../types";
|
||||
|
||||
export interface UseRefillReturn {
|
||||
// Refill state
|
||||
@@ -146,8 +146,8 @@ export function useRefill(): UseRefillReturn {
|
||||
const desiredTotal = finalFullBlisters * selectedMed.pillsPerBlister + finalPartialPills;
|
||||
|
||||
// The "base" from DB structure (without any stockAdjustment)
|
||||
const baseTotal =
|
||||
selectedMed.packCount * selectedMed.blistersPerPack * selectedMed.pillsPerBlister + selectedMed.looseTablets;
|
||||
// Use getPackageSize() which handles both blister and bottle types correctly
|
||||
const baseTotal = getPackageSize(selectedMed);
|
||||
|
||||
// stockAdjustment = what we need to make getMedTotal() return desiredTotal
|
||||
const newStockAdjustment = desiredTotal - baseTotal;
|
||||
|
||||
@@ -103,10 +103,14 @@ describe("useDoses", () => {
|
||||
});
|
||||
|
||||
it("marks dose as taken optimistically", async () => {
|
||||
// First call for initial load, subsequent calls for marking dose
|
||||
// First call for initial load, second for marking dose, third for re-sync
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ doses: [{ doseId: "new-dose", takenAt: Date.now(), dismissed: false }] }),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
@@ -119,7 +123,9 @@ describe("useDoses", () => {
|
||||
await result.current.markDoseTaken("new-dose");
|
||||
});
|
||||
|
||||
expect(result.current.takenDoses.has("new-dose")).toBe(true);
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.has("new-dose")).toBe(true);
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/doses/taken",
|
||||
expect.objectContaining({
|
||||
@@ -130,10 +136,11 @@ describe("useDoses", () => {
|
||||
});
|
||||
|
||||
it("reverts optimistic update on error", async () => {
|
||||
// First call for initial load, second for marking dose fails
|
||||
// First call for initial load, second for marking dose fails, third for re-sync
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||
.mockRejectedValueOnce(new Error("Network error"));
|
||||
.mockRejectedValueOnce(new Error("Network error"))
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) });
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
@@ -153,12 +160,13 @@ describe("useDoses", () => {
|
||||
|
||||
it("undoes dose taken optimistically", async () => {
|
||||
const mockDoses = {
|
||||
doses: [{ doseId: "taken-dose", dismissed: false }],
|
||||
doses: [{ doseId: "taken-dose", takenAt: Date.now(), dismissed: false }],
|
||||
};
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) });
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
@@ -170,7 +178,9 @@ describe("useDoses", () => {
|
||||
await result.current.undoDoseTaken("taken-dose");
|
||||
});
|
||||
|
||||
expect(result.current.takenDoses.has("taken-dose")).toBe(false);
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.has("taken-dose")).toBe(false);
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledWith("/api/doses/taken/taken-dose", expect.objectContaining({ method: "DELETE" }));
|
||||
});
|
||||
|
||||
|
||||
@@ -287,6 +287,114 @@ describe("useRefill", () => {
|
||||
expect(mockLoadMeds).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stock correction uses correct base for bottle type medications", async () => {
|
||||
// BUG FIX: submitStockCorrection used blister formula (packCount * blistersPerPack * pillsPerBlister + looseTablets)
|
||||
// for ALL medications, but getMedTotal() uses only looseTablets + stockAdjustment for bottles.
|
||||
// This mismatch caused the correction to compute the wrong stockAdjustment.
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });
|
||||
|
||||
const bottleMed: Medication = {
|
||||
id: 4,
|
||||
name: "Pills in a Box",
|
||||
packageType: "bottle",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 1,
|
||||
looseTablets: 150,
|
||||
stockAdjustment: -2,
|
||||
takenBy: [],
|
||||
blisters: [{ usage: 1, every: 1, start: "2026-01-31T20:27:00" }],
|
||||
updatedAt: null,
|
||||
};
|
||||
|
||||
// getMedTotal for bottle = looseTablets + stockAdjustment = 150 + (-2) = 148
|
||||
// getPackageSize for bottle = looseTablets = 150
|
||||
|
||||
const mockLoadMeds = vi.fn();
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
// Pre-fill: user sees 148 pills (148 / 1 = 148 full, 0 partial)
|
||||
act(() => {
|
||||
result.current.openEditStockModal(bottleMed, {
|
||||
all: [{ name: "Pills in a Box", medsLeft: 148, daysLeft: 148 }] as Coverage[],
|
||||
});
|
||||
});
|
||||
|
||||
// User adds +1 → 149 full blisters (pillsPerBlister=1)
|
||||
act(() => {
|
||||
result.current.setEditStockFullBlisters(149);
|
||||
result.current.setEditStockPartialBlisterPills(0);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitStockCorrection(4, bottleMed, mockLoadMeds);
|
||||
});
|
||||
|
||||
// desiredTotal = 149 * 1 + 0 = 149
|
||||
// baseTotal (fixed) = getPackageSize(bottle) = looseTablets = 150
|
||||
// newStockAdjustment = 149 - 150 = -1
|
||||
// → getMedTotal = 150 + (-1) = 149 ✓
|
||||
const fetchCall = (global.fetch as ReturnType<typeof vi.fn>).mock.calls.find(
|
||||
(call: [string, RequestInit]) => call[0] === "/api/medications/4/stock-adjustment"
|
||||
);
|
||||
expect(fetchCall).toBeDefined();
|
||||
const body = JSON.parse(fetchCall![1].body as string);
|
||||
expect(body.stockAdjustment).toBe(-1); // NOT -2 (the old bug)
|
||||
});
|
||||
|
||||
it("stock correction uses correct base for blister type medications", async () => {
|
||||
// Ensure blister type still works correctly after the bottle fix
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });
|
||||
|
||||
const blisterMed: Medication = {
|
||||
id: 2,
|
||||
name: "Blister Med",
|
||||
packageType: "blister",
|
||||
packCount: 1,
|
||||
blistersPerPack: 5,
|
||||
pillsPerBlister: 5,
|
||||
looseTablets: 0,
|
||||
stockAdjustment: 1,
|
||||
takenBy: [],
|
||||
blisters: [{ usage: 1, every: 1, start: "2026-01-30T21:07:00" }],
|
||||
updatedAt: null,
|
||||
};
|
||||
|
||||
// getMedTotal for blister = 1*5*5 + 0 + 1 = 26
|
||||
// getPackageSize for blister = 1*5*5 + 0 = 25
|
||||
|
||||
const mockLoadMeds = vi.fn();
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
// User sees 26 pills → 5 full blisters (5pills each) + 1 partial
|
||||
act(() => {
|
||||
result.current.openEditStockModal(blisterMed, {
|
||||
all: [{ name: "Blister Med", medsLeft: 26, daysLeft: 26 }] as Coverage[],
|
||||
});
|
||||
});
|
||||
|
||||
// User changes to 27 (+1): 5 full + 2 partial
|
||||
act(() => {
|
||||
result.current.setEditStockFullBlisters(5);
|
||||
result.current.setEditStockPartialBlisterPills(2);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitStockCorrection(2, blisterMed, mockLoadMeds);
|
||||
});
|
||||
|
||||
// desiredTotal = 5 * 5 + 2 = 27
|
||||
// baseTotal = getPackageSize(blister) = 1*5*5 + 0 = 25
|
||||
// newStockAdjustment = 27 - 25 = 2
|
||||
// → getMedTotal = 25 + 2 = 27 ✓
|
||||
const fetchCall = (global.fetch as ReturnType<typeof vi.fn>).mock.calls.find(
|
||||
(call: [string, RequestInit]) => call[0] === "/api/medications/2/stock-adjustment"
|
||||
);
|
||||
expect(fetchCall).toBeDefined();
|
||||
const body = JSON.parse(fetchCall![1].body as string);
|
||||
expect(body.stockAdjustment).toBe(2);
|
||||
});
|
||||
|
||||
it("allows setting state directly", () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
|
||||
@@ -409,8 +409,9 @@ describe("calculateCoverage", () => {
|
||||
});
|
||||
|
||||
it("stock correction with dose tracking data also reflects correctly", () => {
|
||||
// When the user has dose tracking data, the actualConsumed path is used.
|
||||
// Verify that no phantom dose is generated right after a stock correction.
|
||||
// In automatic mode, dose tracking data is ignored — stock is always
|
||||
// reduced based on the schedule. Verify that tracked doses don't affect
|
||||
// the calculation and that stock correction still resets the baseline.
|
||||
const correctionTime = new Date("2024-03-15T12:00:00Z");
|
||||
const march14 = new Date("2024-03-14T00:00:00").getTime();
|
||||
|
||||
@@ -437,20 +438,23 @@ describe("calculateCoverage", () => {
|
||||
];
|
||||
|
||||
// User has tracked a dose yesterday (before the correction)
|
||||
// In automatic mode, this should be ignored — only the schedule matters.
|
||||
const takenDoses = new Set([`1-0-${march14}`]);
|
||||
|
||||
const result = calculateCoverage(meds, [], "en", 7, "automatic", takenDoses);
|
||||
|
||||
expect(result.all).toHaveLength(1);
|
||||
// getMedTotal = 30 - 7 = 23.
|
||||
// The taken dose from yesterday should NOT be counted (it's before the correction).
|
||||
// No new doses should exist since the correction just happened.
|
||||
// Automatic mode ignores tracking data. After correction, consumption
|
||||
// restarts from correctionTime + period, which is in the future.
|
||||
expect(result.all[0].medsLeft).toBe(23);
|
||||
});
|
||||
|
||||
it("stock correction consumption resumes after one full period", () => {
|
||||
// After 1 day (for daily medication), the next dose should be consumed.
|
||||
// Set system time to 1 day + 1 hour after correction.
|
||||
// After correction, the next scheduled dose on the blister's grid should
|
||||
// be counted once its time arrives.
|
||||
// Correction at March 14 12:00, blister start 08:00 daily →
|
||||
// next dose after correction = March 15 08:00. Now is 13:00 on March 15 → 1 dose.
|
||||
const correctionTime = new Date("2024-03-14T12:00:00Z");
|
||||
vi.setSystemTime(new Date("2024-03-15T13:00:00Z")); // 25 hours after correction
|
||||
|
||||
@@ -483,6 +487,521 @@ describe("calculateCoverage", () => {
|
||||
// medsLeft = 23 - 1 = 22
|
||||
expect(result.all[0].medsLeft).toBe(22);
|
||||
});
|
||||
|
||||
it("stock correction aligns to schedule grid, not correction timestamp", () => {
|
||||
// BUG: When correction happened just before a scheduled dose (e.g. 15:40
|
||||
// correction, 15:42 dose), the old code added 1 full period to the correction
|
||||
// time (15:40 + 24h = tomorrow 15:40), missing today's 15:42 dose entirely.
|
||||
// FIX: Align effectiveStart to the blister's schedule grid so that the first
|
||||
// dose counted is the next one on the schedule after the correction.
|
||||
const correctionTime = new Date("2024-03-14T15:40:00Z"); // 2 min before dose
|
||||
vi.setSystemTime(new Date("2024-03-14T15:45:00Z")); // 5 min after correction, 3 min after dose
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "TestMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 30,
|
||||
looseTablets: 0,
|
||||
stockAdjustment: -5, // 30 - 5 = 25 pills
|
||||
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||
takenBy: [],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-03-01T15:42:00Z", // Daily at 15:42
|
||||
},
|
||||
],
|
||||
updatedAt: correctionTime.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
const result = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||
|
||||
expect(result.all).toHaveLength(1);
|
||||
// Correction at 15:40, dose at 15:42, now at 15:45.
|
||||
// The 15:42 dose is AFTER the correction → should be counted.
|
||||
// medsLeft = 25 - 1 = 24
|
||||
expect(result.all[0].medsLeft).toBe(24);
|
||||
});
|
||||
|
||||
it("stock correction shortly after a dose does not count that dose again", () => {
|
||||
// If correction happens shortly AFTER a dose, that dose is already reflected
|
||||
// in the stock count and should NOT be counted again.
|
||||
const correctionTime = new Date("2024-03-14T15:45:00Z"); // 3 min AFTER the 15:42 dose
|
||||
vi.setSystemTime(new Date("2024-03-14T16:00:00Z")); // 15 min after correction
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "TestMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 30,
|
||||
looseTablets: 0,
|
||||
stockAdjustment: -5,
|
||||
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||
takenBy: [],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-03-01T15:42:00Z", // Daily at 15:42
|
||||
},
|
||||
],
|
||||
updatedAt: correctionTime.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
const result = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||
|
||||
expect(result.all).toHaveLength(1);
|
||||
// Correction at 15:45, after today's 15:42 dose → next dose is TOMORROW 15:42.
|
||||
// Now is 16:00 today → next dose hasn't arrived yet → 0 consumed.
|
||||
// medsLeft = 25
|
||||
expect(result.all[0].medsLeft).toBe(25);
|
||||
});
|
||||
|
||||
it("automatic mode ignores past dose tracking data", () => {
|
||||
// Automatic mode uses time-based expected consumption for past doses.
|
||||
// Even if a user marks only some past doses as taken, the stock should still
|
||||
// decrease for ALL scheduled doses whose time has passed.
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "TestMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 30,
|
||||
looseTablets: 0,
|
||||
takenBy: [],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-03-10T09:00:00",
|
||||
},
|
||||
],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
// System time is March 15 12:00, start is 09:00 → 6 occurrences (March 10-15)
|
||||
const march10 = new Date("2024-03-10T00:00:00").getTime();
|
||||
const march11 = new Date("2024-03-11T00:00:00").getTime();
|
||||
|
||||
// User only marked 2 out of 6 past doses as taken
|
||||
const takenDoses = new Set([`1-0-${march10}`, `1-0-${march11}`]);
|
||||
|
||||
const resultWithTracking = calculateCoverage(meds, [], "en", 7, "automatic", takenDoses);
|
||||
const resultWithoutTracking = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||
|
||||
// Both should have the same medsLeft — past tracking data doesn't reduce extra
|
||||
expect(resultWithTracking.all[0].medsLeft).toBe(resultWithoutTracking.all[0].medsLeft);
|
||||
// 30 pills - 6 consumed = 24
|
||||
expect(resultWithTracking.all[0].medsLeft).toBe(24);
|
||||
});
|
||||
|
||||
it("automatic mode counts early-taken future doses", () => {
|
||||
// If a user marks a dose as taken BEFORE the scheduled time,
|
||||
// it should count as consumed immediately (early intake).
|
||||
// System time is March 15 12:00, intake at 21:00 → today's dose not yet auto-consumed
|
||||
vi.setSystemTime(new Date("2024-03-15T12:00:00Z"));
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "TestMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 30,
|
||||
looseTablets: 0,
|
||||
takenBy: [],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-03-10T21:00:00", // 21:00 = after current time 12:00
|
||||
},
|
||||
],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
// 5 occurrences auto-consumed: March 10-14 (all at 21:00, which is past)
|
||||
// March 15 at 21:00 hasn't passed yet (it's only 12:00)
|
||||
const resultNoTracking = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||
expect(resultNoTracking.all[0].medsLeft).toBe(25); // 30 - 5 = 25
|
||||
|
||||
// User marks today's (March 15) dose as taken early at 12:00
|
||||
const march15 = new Date("2024-03-15T00:00:00").getTime();
|
||||
const takenDoses = new Set([`1-0-${march15}`]);
|
||||
|
||||
const resultEarlyTaken = calculateCoverage(meds, [], "en", 7, "automatic", takenDoses);
|
||||
// 5 auto + 1 early = 6 consumed → 30 - 6 = 24
|
||||
expect(resultEarlyTaken.all[0].medsLeft).toBe(24);
|
||||
});
|
||||
|
||||
it("automatic mode does not double-count after intake time passes", () => {
|
||||
// After the scheduled time, the dose is auto-consumed.
|
||||
// If it was also marked as taken (earlier), it should NOT be counted twice.
|
||||
vi.setSystemTime(new Date("2024-03-15T22:00:00Z")); // After 21:00
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "TestMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 30,
|
||||
looseTablets: 0,
|
||||
takenBy: [],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-03-10T21:00:00",
|
||||
},
|
||||
],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
// 6 occurrences auto-consumed: March 10-15 (all at 21:00, now it's 22:00)
|
||||
const march15 = new Date("2024-03-15T00:00:00").getTime();
|
||||
const march14 = new Date("2024-03-14T00:00:00").getTime();
|
||||
// User marked March 14 and 15 as taken (both already auto-consumed by now)
|
||||
const takenDoses = new Set([`1-0-${march14}`, `1-0-${march15}`]);
|
||||
|
||||
const resultTracked = calculateCoverage(meds, [], "en", 7, "automatic", takenDoses);
|
||||
const resultNoTracking = calculateCoverage(meds, [], "en", 7, "automatic", new Set());
|
||||
|
||||
// Both should be 24 (30 - 6). No double counting!
|
||||
expect(resultTracked.all[0].medsLeft).toBe(24);
|
||||
expect(resultNoTracking.all[0].medsLeft).toBe(24);
|
||||
});
|
||||
|
||||
it("manual mode: dose taken BEFORE stock correction is excluded", () => {
|
||||
// When a user corrects stock, any dose marked BEFORE the correction
|
||||
// is already reflected in the corrected count and should NOT be counted.
|
||||
const correctionTime = new Date("2024-03-15T12:00:00Z");
|
||||
const todayMidnight = new Date("2024-03-15T00:00:00").getTime();
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "DailyMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 14,
|
||||
pillsPerBlister: 14,
|
||||
looseTablets: 0,
|
||||
stockAdjustment: -85, // 196 - 85 = 111 pills
|
||||
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||
takenBy: [],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-01-01T08:00:00",
|
||||
},
|
||||
],
|
||||
updatedAt: correctionTime.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
// User took a dose today at 10am (BEFORE the correction at 12pm)
|
||||
const doseId = `1-0-${todayMidnight}`;
|
||||
const takenDoses = new Set([doseId]);
|
||||
const takenDoseTimestamps = new Map([[doseId, new Date("2024-03-15T10:00:00Z").getTime()]]);
|
||||
|
||||
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||
|
||||
expect(result.all).toHaveLength(1);
|
||||
// getMedTotal = 196 - 85 = 111
|
||||
// Dose was taken BEFORE correction → NOT counted
|
||||
expect(result.all[0].medsLeft).toBe(111);
|
||||
});
|
||||
|
||||
it("manual mode: dose taken AFTER stock correction is counted", () => {
|
||||
// When a user corrects stock and then takes a dose, that dose SHOULD be counted.
|
||||
const correctionTime = new Date("2024-03-15T12:00:00Z");
|
||||
const todayMidnight = new Date("2024-03-15T00:00:00").getTime();
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "DailyMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 14,
|
||||
pillsPerBlister: 14,
|
||||
looseTablets: 0,
|
||||
stockAdjustment: -85, // 196 - 85 = 111 pills
|
||||
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||
takenBy: [],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-01-01T08:00:00",
|
||||
},
|
||||
],
|
||||
updatedAt: correctionTime.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
// User took a dose today at 2pm (AFTER the correction at 12pm)
|
||||
const doseId = `1-0-${todayMidnight}`;
|
||||
const takenDoses = new Set([doseId]);
|
||||
const takenDoseTimestamps = new Map([[doseId, new Date("2024-03-15T14:00:00Z").getTime()]]);
|
||||
|
||||
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||
|
||||
expect(result.all).toHaveLength(1);
|
||||
// getMedTotal = 196 - 85 = 111
|
||||
// Dose was taken AFTER correction → counted → 111 - 1 = 110
|
||||
expect(result.all[0].medsLeft).toBe(110);
|
||||
});
|
||||
|
||||
it("manual mode: stock correction counts next-day taken doses", () => {
|
||||
// After a stock correction, doses taken the next day SHOULD be counted.
|
||||
const correctionTime = new Date("2024-03-14T12:00:00Z");
|
||||
const march15Midnight = new Date("2024-03-15T00:00:00").getTime();
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "DailyMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 30,
|
||||
looseTablets: 0,
|
||||
stockAdjustment: -7, // 30 - 7 = 23 pills
|
||||
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||
takenBy: [],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-03-01T08:00:00",
|
||||
},
|
||||
],
|
||||
updatedAt: correctionTime.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
// User takes dose on March 15 at 8am (day after correction on March 14)
|
||||
const doseId = `1-0-${march15Midnight}`;
|
||||
const takenDoses = new Set([doseId]);
|
||||
const takenDoseTimestamps = new Map([[doseId, new Date("2024-03-15T08:00:00Z").getTime()]]);
|
||||
|
||||
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||
|
||||
expect(result.all).toHaveLength(1);
|
||||
// getMedTotal = 30 - 7 = 23
|
||||
// March 15 dose should be counted (taken after correction)
|
||||
expect(result.all[0].medsLeft).toBe(22);
|
||||
});
|
||||
|
||||
it("manual mode: no stock correction counts all taken doses", () => {
|
||||
// Without any stock correction, all taken doses should be counted
|
||||
const march14Midnight = new Date("2024-03-14T00:00:00").getTime();
|
||||
const march15Midnight = new Date("2024-03-15T00:00:00").getTime();
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "DailyMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 30,
|
||||
looseTablets: 0,
|
||||
takenBy: [],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-03-01T08:00:00",
|
||||
},
|
||||
],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
// User took doses on March 14 and 15
|
||||
const doseId1 = `1-0-${march14Midnight}`;
|
||||
const doseId2 = `1-0-${march15Midnight}`;
|
||||
const takenDoses = new Set([doseId1, doseId2]);
|
||||
// No stock correction → takenAt doesn't matter, but provide for completeness
|
||||
const takenDoseTimestamps = new Map([
|
||||
[doseId1, new Date("2024-03-14T08:00:00Z").getTime()],
|
||||
[doseId2, new Date("2024-03-15T08:00:00Z").getTime()],
|
||||
]);
|
||||
|
||||
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||
|
||||
expect(result.all).toHaveLength(1);
|
||||
// Both doses should be counted: medsLeft = 30 - 2 = 28
|
||||
expect(result.all[0].medsLeft).toBe(28);
|
||||
});
|
||||
|
||||
it("manual mode: stock correction with multiple medications", () => {
|
||||
// Regression test: 3 medications (daily, daily, weekly).
|
||||
// Stock correction on all 3. Daily meds have doses taken BEFORE correction.
|
||||
const correctionTime = new Date("2024-03-15T12:00:00Z");
|
||||
const todayMidnight = new Date("2024-03-15T00:00:00").getTime();
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "DailyMed1",
|
||||
packCount: 1,
|
||||
blistersPerPack: 14,
|
||||
pillsPerBlister: 14,
|
||||
looseTablets: 0,
|
||||
stockAdjustment: -85, // 196 - 85 = 111
|
||||
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||
takenBy: [],
|
||||
blisters: [{ usage: 1, every: 1, start: "2024-01-01T08:00:00" }],
|
||||
updatedAt: correctionTime.toISOString(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "DailyMed2",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 30,
|
||||
looseTablets: 0,
|
||||
stockAdjustment: -10, // 30 - 10 = 20
|
||||
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||
takenBy: [],
|
||||
blisters: [{ usage: 1, every: 1, start: "2024-01-01T09:00:00" }],
|
||||
updatedAt: correctionTime.toISOString(),
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: "WeeklyMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
stockAdjustment: -2, // 10 - 2 = 8
|
||||
lastStockCorrectionAt: correctionTime.toISOString(),
|
||||
takenBy: [],
|
||||
blisters: [{ usage: 1, every: 7, start: "2024-01-05T10:00:00" }],
|
||||
updatedAt: correctionTime.toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
// Daily meds have same-day doses taken BEFORE correction (at 8am, correction at 12pm)
|
||||
const doseId1 = `1-0-${todayMidnight}`;
|
||||
const doseId2 = `2-0-${todayMidnight}`;
|
||||
const takenDoses = new Set([doseId1, doseId2]);
|
||||
const takenDoseTimestamps = new Map([
|
||||
[doseId1, new Date("2024-03-15T08:00:00Z").getTime()], // Before correction
|
||||
[doseId2, new Date("2024-03-15T09:00:00Z").getTime()], // Before correction
|
||||
]);
|
||||
|
||||
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||
|
||||
expect(result.all).toHaveLength(3);
|
||||
const daily1 = result.all.find((c) => c.name === "DailyMed1")!;
|
||||
const daily2 = result.all.find((c) => c.name === "DailyMed2")!;
|
||||
const weekly = result.all.find((c) => c.name === "WeeklyMed")!;
|
||||
|
||||
// All three should reflect full stock (doses taken before correction → excluded)
|
||||
expect(daily1.medsLeft).toBe(111);
|
||||
expect(daily2.medsLeft).toBe(20);
|
||||
expect(weekly.medsLeft).toBe(8);
|
||||
});
|
||||
|
||||
it("manual mode: person-suffix dose IDs are counted correctly", () => {
|
||||
// BUG HUNT: In prod (manual mode), dose IDs have a person suffix like
|
||||
// "31-0-1770505200000-Daniel". Does the manual mode code correctly parse
|
||||
// and count these?
|
||||
const march14 = new Date("2024-03-14T00:00:00").getTime();
|
||||
const march15 = new Date("2024-03-15T00:00:00").getTime();
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 31,
|
||||
name: "ProdMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 30,
|
||||
looseTablets: 0,
|
||||
takenBy: ["Daniel"],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-03-01T08:00:00",
|
||||
},
|
||||
],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
// Dose IDs with person suffix (as prod generates them)
|
||||
const doseId1 = `31-0-${march14}-Daniel`;
|
||||
const doseId2 = `31-0-${march15}-Daniel`;
|
||||
const takenDoses = new Set([doseId1, doseId2]);
|
||||
// No stock correction → all counted
|
||||
const takenDoseTimestamps = new Map([
|
||||
[doseId1, new Date("2024-03-14T08:00:00Z").getTime()],
|
||||
[doseId2, new Date("2024-03-15T08:00:00Z").getTime()],
|
||||
]);
|
||||
|
||||
const result = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||
|
||||
expect(result.all).toHaveLength(1);
|
||||
// Both doses should be counted: medsLeft = 30 - 2 = 28
|
||||
expect(result.all[0].medsLeft).toBe(28);
|
||||
});
|
||||
|
||||
it("manual mode: future dose taken today counts immediately", () => {
|
||||
// User marks a future dose (later today) as taken.
|
||||
// It should be counted in manual mode immediately.
|
||||
vi.setSystemTime(new Date("2024-03-15T12:00:00Z"));
|
||||
const march15 = new Date("2024-03-15T00:00:00").getTime();
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 31,
|
||||
name: "ProdMed",
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 30,
|
||||
looseTablets: 0,
|
||||
takenBy: ["Daniel"],
|
||||
blisters: [
|
||||
{
|
||||
usage: 1,
|
||||
every: 1,
|
||||
start: "2024-03-01T21:00:00", // 21:00, still in future at 12:00
|
||||
},
|
||||
],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
// No doses taken → 30 pills
|
||||
const resultBefore = calculateCoverage(meds, [], "en", 7, "manual", new Set());
|
||||
expect(resultBefore.all[0].medsLeft).toBe(30);
|
||||
|
||||
// Take today's dose (future time) → 29 pills
|
||||
const doseId = `31-0-${march15}-Daniel`;
|
||||
const takenDoses = new Set([doseId]);
|
||||
const takenDoseTimestamps = new Map([[doseId, Date.now()]]);
|
||||
const resultAfter = calculateCoverage(meds, [], "en", 7, "manual", takenDoses, takenDoseTimestamps);
|
||||
expect(resultAfter.all[0].medsLeft).toBe(29);
|
||||
|
||||
// Undo → back to 30 pills
|
||||
const resultUndo = calculateCoverage(meds, [], "en", 7, "manual", new Set());
|
||||
expect(resultUndo.all[0].medsLeft).toBe(30);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStockStatus", () => {
|
||||
|
||||
@@ -100,7 +100,8 @@ export function calculateCoverage(
|
||||
locale: string,
|
||||
reminderDaysBefore: number,
|
||||
stockCalculationMode: "automatic" | "manual",
|
||||
takenDoses: Set<string>
|
||||
takenDoses: Set<string>,
|
||||
takenDoseTimestamps?: Map<string, number>
|
||||
): { low: Coverage[]; all: Coverage[] } {
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
const now = Date.now();
|
||||
@@ -122,60 +123,90 @@ export function calculateCoverage(
|
||||
const stockCorrectionCutoff = m.lastStockCorrectionAt ? new Date(m.lastStockCorrectionAt).getTime() : 0;
|
||||
|
||||
if (stockCalculationMode === "automatic") {
|
||||
// In automatic mode, calculate expected consumption based on time
|
||||
// but also account for manual corrections (doses marked as not taken)
|
||||
// In automatic mode, stock is reduced automatically based on the schedule.
|
||||
// Every scheduled dose counts as consumed once its time has passed.
|
||||
// Additionally, if a user marks a future dose as taken BEFORE the scheduled
|
||||
// time (early intake), that dose is also counted as consumed immediately.
|
||||
// This prevents double-counting: once the scheduled time arrives, the dose
|
||||
// was already counted via the early-taken path, not again via time.
|
||||
blisters.forEach((s, blisterIdx) => {
|
||||
const blisterStart = new Date(s.start).getTime();
|
||||
const period = Math.max(1, s.every) * MS_PER_DAY;
|
||||
|
||||
// After a stock correction, start counting consumption from the NEXT
|
||||
// scheduled dose, because the user's pill count already reflects all
|
||||
// consumption up to the correction time.
|
||||
// scheduled dose on this blister's grid, because the user's pill count
|
||||
// already reflects all consumption up to the correction time.
|
||||
// We align to the schedule grid so that e.g. correction at 15:40 with
|
||||
// a daily 15:42 dose counts today's 15:42 dose (2 min later), not
|
||||
// tomorrow's dose (24h later as the old code did).
|
||||
let effectiveStart: number;
|
||||
if (stockCorrectionCutoff > 0 && stockCorrectionCutoff >= blisterStart) {
|
||||
effectiveStart = stockCorrectionCutoff + period;
|
||||
const elapsedSinceStart = stockCorrectionCutoff - blisterStart;
|
||||
const periodsElapsed = Math.floor(elapsedSinceStart / period);
|
||||
effectiveStart = blisterStart + (periodsElapsed + 1) * period;
|
||||
} else {
|
||||
effectiveStart = blisterStart;
|
||||
}
|
||||
if (Number.isNaN(effectiveStart) || effectiveStart > now) return;
|
||||
const occurrences = Math.floor((now - effectiveStart) / period) + 1;
|
||||
if (Number.isNaN(effectiveStart)) return;
|
||||
|
||||
const intake = intakes[blisterIdx];
|
||||
const intakePerson = intake?.takenBy;
|
||||
|
||||
// For per-intake takenBy, only count for that person
|
||||
// For legacy (no takenBy), count for all people in medication takenBy
|
||||
const peopleForThisIntake = intakePerson ? [intakePerson] : m.takenBy?.length > 0 ? m.takenBy : [null];
|
||||
const expectedConsumed = occurrences * s.usage * peopleForThisIntake.length;
|
||||
|
||||
// Count how many doses were actually marked as taken for this blister
|
||||
let actualConsumed = 0;
|
||||
// Time-based: count doses where the scheduled time has already passed
|
||||
let timeBasedConsumed = 0;
|
||||
let lastAutoConsumedDateMs = 0;
|
||||
|
||||
// Generate all expected dose IDs for this blister up to now
|
||||
for (let i = 0; i < occurrences; i++) {
|
||||
const doseDate = new Date(effectiveStart + i * period);
|
||||
const dateOnlyMs = new Date(doseDate.getFullYear(), doseDate.getMonth(), doseDate.getDate()).getTime();
|
||||
const baseDoseId = `${m.id}-${blisterIdx}-${dateOnlyMs}`;
|
||||
if (effectiveStart <= now) {
|
||||
const occurrences = Math.floor((now - effectiveStart) / period) + 1;
|
||||
timeBasedConsumed = occurrences * s.usage * peopleForThisIntake.length;
|
||||
|
||||
// Check if each person has taken this dose
|
||||
for (const person of peopleForThisIntake) {
|
||||
const doseId = person ? `${baseDoseId}-${person}` : baseDoseId;
|
||||
if (takenDoses.has(doseId)) {
|
||||
actualConsumed += s.usage;
|
||||
// Date-only timestamp of the last auto-consumed dose
|
||||
const lastDoseTime = new Date(effectiveStart + (occurrences - 1) * period);
|
||||
lastAutoConsumedDateMs = new Date(
|
||||
lastDoseTime.getFullYear(),
|
||||
lastDoseTime.getMonth(),
|
||||
lastDoseTime.getDate()
|
||||
).getTime();
|
||||
}
|
||||
|
||||
// Early intakes: count future doses already marked as taken.
|
||||
// The cutoff is the later of: last auto-consumed date or stock correction date.
|
||||
// This prevents double-counting (time-based + early-taken) and respects corrections.
|
||||
const stockCorrectionDateOnly =
|
||||
stockCorrectionCutoff > 0
|
||||
? new Date(
|
||||
new Date(stockCorrectionCutoff).getFullYear(),
|
||||
new Date(stockCorrectionCutoff).getMonth(),
|
||||
new Date(stockCorrectionCutoff).getDate()
|
||||
).getTime()
|
||||
: 0;
|
||||
const earlyCutoff = Math.max(lastAutoConsumedDateMs, stockCorrectionDateOnly);
|
||||
|
||||
let earlyTakenConsumed = 0;
|
||||
for (const doseId of takenDoses) {
|
||||
const parts = doseId.split("-");
|
||||
if (parts.length >= 3) {
|
||||
const medId = parseInt(parts[0], 10);
|
||||
const bIdx = parseInt(parts[1], 10);
|
||||
const timestamp = parseInt(parts[2], 10);
|
||||
if (medId === m.id && bIdx === blisterIdx && timestamp > earlyCutoff) {
|
||||
earlyTakenConsumed += s.usage;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we have tracking data (any doses marked), use actual consumed
|
||||
// Otherwise fall back to expected (for backwards compatibility)
|
||||
const hasTrackingData = Array.from(takenDoses).some((id) => {
|
||||
const parts = id.split("-");
|
||||
return parts.length >= 3 && parseInt(parts[0], 10) === m.id && parseInt(parts[1], 10) === blisterIdx;
|
||||
});
|
||||
|
||||
consumed += hasTrackingData ? actualConsumed : expectedConsumed;
|
||||
consumed += timeBasedConsumed + earlyTakenConsumed;
|
||||
});
|
||||
} else {
|
||||
// In manual mode, only count doses that are explicitly marked as taken
|
||||
// In manual mode, only count doses that are explicitly marked as taken.
|
||||
// For stock correction filtering, we use the actual time the dose was marked
|
||||
// as taken (takenAt), not the scheduled date. This correctly handles same-day
|
||||
// scenarios: if a user corrects stock at 3pm, then takes a dose at 4pm,
|
||||
// the dose counts because takenAt (4pm) > correctionTime (3pm).
|
||||
takenDoses.forEach((doseId) => {
|
||||
const parts = doseId.split("-");
|
||||
if (parts.length >= 3) {
|
||||
@@ -190,19 +221,17 @@ export function calculateCoverage(
|
||||
blisterStartDate.getMonth(),
|
||||
blisterStartDate.getDate()
|
||||
).getTime();
|
||||
// Convert stock correction cutoff to date-only as well
|
||||
const stockCorrectionDateOnly =
|
||||
stockCorrectionCutoff > 0
|
||||
? new Date(
|
||||
new Date(stockCorrectionCutoff).getFullYear(),
|
||||
new Date(stockCorrectionCutoff).getMonth(),
|
||||
new Date(stockCorrectionCutoff).getDate()
|
||||
).getTime()
|
||||
: 0;
|
||||
|
||||
// Use actual takenAt timestamp for stock correction comparison.
|
||||
// A dose counts only if it was MARKED after the stock correction,
|
||||
// regardless of what day it was scheduled for.
|
||||
const takenAt = takenDoseTimestamps?.get(doseId) ?? 0;
|
||||
const afterCorrectionOrNoCorrectionMs = stockCorrectionCutoff === 0 || takenAt > stockCorrectionCutoff;
|
||||
|
||||
if (
|
||||
!Number.isNaN(blisterStartDateOnly) &&
|
||||
doseTimestamp >= blisterStartDateOnly &&
|
||||
doseTimestamp >= stockCorrectionDateOnly
|
||||
afterCorrectionOrNoCorrectionMs
|
||||
) {
|
||||
consumed += blisters[blisterIdx].usage;
|
||||
}
|
||||
|
||||
+86
-55
@@ -1,6 +1,6 @@
|
||||
#!/bin/bash
|
||||
# =============================================================================
|
||||
# MedAssist Release Script
|
||||
# MedAssist Release Script (non-interactive)
|
||||
# =============================================================================
|
||||
# Usage:
|
||||
# ./scripts/release.sh patch # 1.0.0 -> 1.0.1 (bugfixes)
|
||||
@@ -8,8 +8,9 @@
|
||||
# ./scripts/release.sh major # 1.0.0 -> 2.0.0 (breaking changes)
|
||||
# ./scripts/release.sh 1.2.3 # explicit version
|
||||
#
|
||||
# This script creates a PR for the version bump (required due to branch protection),
|
||||
# waits for CI, merges it, and then creates a signed tag for the release.
|
||||
# Fully non-interactive: no y/N prompts. Designed to be called by AI agents
|
||||
# or CI systems. Creates a PR for the version bump (required due to branch
|
||||
# protection), waits for CI with retry logic, merges, and creates a signed tag.
|
||||
# =============================================================================
|
||||
|
||||
set -e
|
||||
@@ -21,45 +22,98 @@ YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# GitHub repo
|
||||
# Configuration
|
||||
GITHUB_REPO="DanielVolz/medassist-ng"
|
||||
CI_POLL_INTERVAL=15 # seconds between CI status polls
|
||||
CI_INITIAL_DELAY=20 # seconds to wait before first CI check
|
||||
CI_MAX_WAIT=600 # maximum seconds to wait for CI (10 minutes)
|
||||
|
||||
# Get script directory and project root
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# Check for gh CLI
|
||||
# Detect git remote name (prefer 'origin', fall back to 'github')
|
||||
detect_remote() {
|
||||
if git remote | grep -q '^origin$'; then
|
||||
echo "origin"
|
||||
elif git remote | grep -q '^github$'; then
|
||||
echo "github"
|
||||
else
|
||||
echo -e "${RED}Error: No 'origin' or 'github' remote found.${NC}" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
GIT_REMOTE=$(detect_remote)
|
||||
|
||||
# Wait for CI checks on a PR with retry logic
|
||||
# GitHub Actions can take 10-30 seconds before checks are reported.
|
||||
# This function polls until checks appear and then watches them.
|
||||
wait_for_ci() {
|
||||
local pr_number="$1"
|
||||
local elapsed=0
|
||||
|
||||
echo -e "${BLUE}Waiting ${CI_INITIAL_DELAY}s for CI checks to be registered...${NC}"
|
||||
sleep "${CI_INITIAL_DELAY}"
|
||||
elapsed=$CI_INITIAL_DELAY
|
||||
|
||||
while [[ $elapsed -lt $CI_MAX_WAIT ]]; do
|
||||
# Check if any checks have been reported
|
||||
local check_output
|
||||
check_output=$(gh pr checks "${pr_number}" --repo "${GITHUB_REPO}" 2>&1) || true
|
||||
|
||||
if echo "$check_output" | grep -q "no checks reported"; then
|
||||
echo -e "${YELLOW}No checks reported yet (${elapsed}s elapsed). Retrying in ${CI_POLL_INTERVAL}s...${NC}"
|
||||
sleep "${CI_POLL_INTERVAL}"
|
||||
elapsed=$((elapsed + CI_POLL_INTERVAL))
|
||||
continue
|
||||
fi
|
||||
|
||||
# Checks are registered — use --watch to wait for completion
|
||||
echo -e "${BLUE}CI checks registered. Watching for completion...${NC}"
|
||||
if gh pr checks "${pr_number}" --repo "${GITHUB_REPO}" --watch; then
|
||||
echo -e "${GREEN}CI checks passed!${NC}"
|
||||
return 0
|
||||
else
|
||||
echo -e "${RED}CI checks failed!${NC}"
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo -e "${RED}Timed out waiting for CI checks after ${CI_MAX_WAIT}s.${NC}"
|
||||
return 1
|
||||
}
|
||||
|
||||
# ─── Preflight checks ────────────────────────────────────────────────────────
|
||||
|
||||
if ! command -v gh &> /dev/null; then
|
||||
echo -e "${RED}Error: GitHub CLI (gh) is required but not installed.${NC}"
|
||||
echo "Install it with: brew install gh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check gh authentication
|
||||
if ! gh auth status &> /dev/null; then
|
||||
echo -e "${RED}Error: Not authenticated with GitHub CLI.${NC}"
|
||||
echo "Run: gh auth login"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check for uncommitted changes
|
||||
if [[ -n $(git status --porcelain) ]]; then
|
||||
echo -e "${RED}Error: You have uncommitted changes. Commit or stash them first.${NC}"
|
||||
git status --short
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Make sure we're on main and up to date
|
||||
# ─── Determine version ───────────────────────────────────────────────────────
|
||||
|
||||
echo -e "${BLUE}Updating main branch...${NC}"
|
||||
git checkout main
|
||||
git pull origin main 2>/dev/null || git pull github main 2>/dev/null || true
|
||||
git pull "${GIT_REMOTE}" main
|
||||
|
||||
# Get current version from backend/package.json
|
||||
CURRENT_VERSION=$(grep '"version"' backend/package.json | sed 's/.*"version": "\(.*\)".*/\1/')
|
||||
echo -e "${BLUE}Current version: ${YELLOW}v${CURRENT_VERSION}${NC}"
|
||||
|
||||
# Calculate new version
|
||||
if [[ -z "$1" ]]; then
|
||||
echo -e "${RED}Usage: $0 <patch|minor|major|x.y.z>${NC}"
|
||||
exit 1
|
||||
@@ -79,7 +133,6 @@ case "$1" in
|
||||
NEW_VERSION="$((major + 1)).0.0"
|
||||
;;
|
||||
*)
|
||||
# Assume explicit version (validate format)
|
||||
if [[ ! "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo -e "${RED}Invalid version format. Use: x.y.z${NC}"
|
||||
exit 1
|
||||
@@ -88,45 +141,31 @@ case "$1" in
|
||||
;;
|
||||
esac
|
||||
|
||||
echo -e "${GREEN}New version: ${YELLOW}v${NEW_VERSION}${NC}"
|
||||
echo ""
|
||||
echo -e "${GREEN}Releasing: ${YELLOW}v${CURRENT_VERSION} → v${NEW_VERSION}${NC}"
|
||||
|
||||
# Confirm
|
||||
read -p "Release v${NEW_VERSION}? (y/N) " -n 1 -r
|
||||
echo ""
|
||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
||||
echo "Aborted."
|
||||
exit 1
|
||||
fi
|
||||
# ─── Create release branch and PR ────────────────────────────────────────────
|
||||
|
||||
# Branch name for the release
|
||||
RELEASE_BRANCH="chore/release-${NEW_VERSION}"
|
||||
|
||||
# Check if branch already exists
|
||||
if git show-ref --verify --quiet "refs/heads/${RELEASE_BRANCH}"; then
|
||||
echo -e "${YELLOW}Branch ${RELEASE_BRANCH} already exists locally. Deleting...${NC}"
|
||||
git branch -D "${RELEASE_BRANCH}"
|
||||
fi
|
||||
|
||||
# Create release branch
|
||||
echo -e "${BLUE}Creating release branch...${NC}"
|
||||
git checkout -b "${RELEASE_BRANCH}"
|
||||
|
||||
# Update version in package.json files
|
||||
echo -e "${BLUE}Updating package.json files...${NC}"
|
||||
sed -i '' "s/\"version\": \"${CURRENT_VERSION}\"/\"version\": \"${NEW_VERSION}\"/" backend/package.json
|
||||
sed -i '' "s/\"version\": \"${CURRENT_VERSION}\"/\"version\": \"${NEW_VERSION}\"/" frontend/package.json 2>/dev/null || true
|
||||
|
||||
# Commit version bump
|
||||
echo -e "${BLUE}Committing version bump...${NC}"
|
||||
git add backend/package.json frontend/package.json 2>/dev/null || git add backend/package.json
|
||||
git commit -m "chore: release v${NEW_VERSION}"
|
||||
|
||||
# Push branch to GitHub
|
||||
echo -e "${BLUE}Pushing release branch to GitHub...${NC}"
|
||||
git push -u origin "${RELEASE_BRANCH}" 2>/dev/null || git push -u github "${RELEASE_BRANCH}"
|
||||
echo -e "${BLUE}Pushing release branch...${NC}"
|
||||
git push -u "${GIT_REMOTE}" "${RELEASE_BRANCH}"
|
||||
|
||||
# Create PR
|
||||
echo -e "${BLUE}Creating Pull Request...${NC}"
|
||||
PR_URL=$(gh pr create \
|
||||
--repo "${GITHUB_REPO}" \
|
||||
@@ -136,57 +175,49 @@ PR_URL=$(gh pr create \
|
||||
|
||||
Automated version bump for release v${NEW_VERSION}.
|
||||
|
||||
This PR was created by the release script." \
|
||||
2>&1)
|
||||
This PR was created by the release script.")
|
||||
|
||||
echo -e "${GREEN}PR created: ${YELLOW}${PR_URL}${NC}"
|
||||
|
||||
# Extract PR number
|
||||
PR_NUMBER=$(echo "$PR_URL" | grep -oE '[0-9]+$')
|
||||
|
||||
# Wait for CI checks
|
||||
echo -e "${BLUE}Waiting for CI checks to complete...${NC}"
|
||||
if ! gh pr checks "${PR_NUMBER}" --repo "${GITHUB_REPO}" --watch; then
|
||||
# ─── Wait for CI and merge ────────────────────────────────────────────────────
|
||||
|
||||
if ! wait_for_ci "${PR_NUMBER}"; then
|
||||
echo -e "${RED}CI checks failed! Please fix the issues and try again.${NC}"
|
||||
echo -e "${RED}Release branch '${RELEASE_BRANCH}' and PR #${PR_NUMBER} are still open.${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}CI checks passed!${NC}"
|
||||
|
||||
# Merge PR
|
||||
echo -e "${BLUE}Merging PR...${NC}"
|
||||
echo -e "${BLUE}Merging PR #${PR_NUMBER}...${NC}"
|
||||
gh pr merge "${PR_NUMBER}" --repo "${GITHUB_REPO}" --squash --delete-branch
|
||||
|
||||
# Switch back to main and pull
|
||||
echo -e "${BLUE}Updating main branch with merged changes...${NC}"
|
||||
echo -e "${BLUE}Updating main branch...${NC}"
|
||||
git checkout main
|
||||
git pull origin main 2>/dev/null || git pull github main 2>/dev/null || true
|
||||
git pull "${GIT_REMOTE}" main
|
||||
|
||||
# ─── Create and push signed tag ──────────────────────────────────────────────
|
||||
|
||||
# Check if tag exists and delete it
|
||||
if git rev-parse "v${NEW_VERSION}" >/dev/null 2>&1; then
|
||||
echo -e "${YELLOW}Tag v${NEW_VERSION} already exists locally. Deleting...${NC}"
|
||||
git tag -d "v${NEW_VERSION}"
|
||||
fi
|
||||
|
||||
# Check if remote tag exists
|
||||
if git ls-remote --tags origin "v${NEW_VERSION}" 2>/dev/null | grep -q "v${NEW_VERSION}" || \
|
||||
git ls-remote --tags github "v${NEW_VERSION}" 2>/dev/null | grep -q "v${NEW_VERSION}"; then
|
||||
if git ls-remote --tags "${GIT_REMOTE}" "v${NEW_VERSION}" 2>/dev/null | grep -q "v${NEW_VERSION}"; then
|
||||
echo -e "${YELLOW}Tag v${NEW_VERSION} exists on remote. Deleting...${NC}"
|
||||
git push origin ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true
|
||||
git push github ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true
|
||||
git push "${GIT_REMOTE}" ":refs/tags/v${NEW_VERSION}" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Create signed tag
|
||||
echo -e "${BLUE}Creating signed tag v${NEW_VERSION}...${NC}"
|
||||
git tag -s "v${NEW_VERSION}" -m "Release v${NEW_VERSION}"
|
||||
|
||||
# Push tag
|
||||
echo -e "${BLUE}Pushing tag to GitHub...${NC}"
|
||||
git push origin "v${NEW_VERSION}" 2>/dev/null || git push github "v${NEW_VERSION}"
|
||||
echo -e "${BLUE}Pushing tag...${NC}"
|
||||
git push "${GIT_REMOTE}" "v${NEW_VERSION}"
|
||||
|
||||
# ─── Done ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
|
||||
echo -e "${GREEN}✓ Released v${NEW_VERSION}${NC}"
|
||||
echo -e "${GREEN} ✓ Released v${NEW_VERSION}${NC}"
|
||||
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
|
||||
echo ""
|
||||
echo -e "${BLUE}GitHub Actions will now build and publish Docker images.${NC}"
|
||||
|
||||
Reference in New Issue
Block a user