mirror of
https://github.com/Sea-Haven-Industries/meal-order-manager.git
synced 2026-10-02 14:13:11 +00:00
Add admin summary-PDF download endpoint and button
The weekly summary PDF generated at Thursday close was stored in the reports bucket with no way to reach it from the UI — admins had to pull it from S3 manually. Surface it in the admin panel: - submit_order: GET /api/admin/summary-pdf?week= (admin-gated) returns a 5-minute presigned URL from the SUMMARY item's stamped PDF key; 404 for weeks that haven't closed. - template.yaml: REPORTS_BUCKET env var + read-only s3:GetObject on reports/* for SubmitOrderFunction (needed so the presigned URL is signed with sufficient permissions). - generate_form.py: "Download summary PDF" button in the admin header; explains Thursday-close timing on 404. - Tests: presign happy path, 404 open week, 400 missing week, 401 unauthenticated. - README updated.
This commit is contained in:
parent
9c1717a77c
commit
b6733703ab
5 changed files with 160 additions and 1 deletions
|
|
@ -42,7 +42,7 @@ who haven't ordered
|
|||
|-----|----------|
|
||||
| `reports/{week}/order-summary.csv` | Meal-level aggregate (meal, qty, unit price, line total) for the Redefine order |
|
||||
| `reports/{week}/payroll-deductions.csv` | Per-employee payroll deduction totals |
|
||||
| `reports/{week}/weekly-summary-{week}.pdf` | Per-person summary (employee → item → quantity, **no pricing**); stored only, not emailed |
|
||||
| `reports/{week}/weekly-summary-{week}.pdf` | Per-person summary (employee → item → quantity, **no pricing**); downloadable from the admin panel via presigned URL |
|
||||
|
||||
## AWS Resources
|
||||
|
||||
|
|
@ -69,6 +69,7 @@ Admins (configured in DynamoDB `CONFIG/SETTINGS` → `admin_emails` list) get an
|
|||
- Edit order quantities, add new menu items, remove items
|
||||
- Delete orders entirely
|
||||
- **Download order list** — a CSV rollup of item → total quantity across all employees (no per-employee breakdown, no prices) to drive the bulk Redefine order. Generated client-side from the loaded week, so it works for open weeks too.
|
||||
- **Download summary PDF** — fetches a short-lived presigned URL for the week's per-person summary PDF (generated at Thursday close) and opens it. Returns 404 for weeks that haven't closed yet.
|
||||
|
||||
All admin operations enforce server-side price recalculation from the menu.
|
||||
|
||||
|
|
@ -80,6 +81,7 @@ All admin operations enforce server-side price recalculation from the menu.
|
|||
| GET | `/api/admin/orders?week=YYYY-WNN` | Get all orders for a week |
|
||||
| PUT | `/api/admin/orders` | Update an order (recalculates prices) |
|
||||
| DELETE | `/api/admin/orders?week=...&email=...` | Delete an order |
|
||||
| GET | `/api/admin/summary-pdf?week=YYYY-WNN` | Presigned URL for the week's summary PDF (404 if week not closed) |
|
||||
|
||||
## Setup
|
||||
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ from shared.db import (
|
|||
get_orders,
|
||||
get_roster,
|
||||
get_settings,
|
||||
get_summary,
|
||||
list_weeks,
|
||||
put_order,
|
||||
)
|
||||
|
|
@ -191,6 +192,9 @@ def lambda_handler(event, context):
|
|||
return handle_admin_update(event)
|
||||
return handle_admin_orders(event)
|
||||
|
||||
if "/admin/summary-pdf" in path:
|
||||
return handle_admin_summary_pdf(event)
|
||||
|
||||
if "/form-status/" in path:
|
||||
return handle_form_status(event)
|
||||
|
||||
|
|
@ -250,6 +254,31 @@ def handle_admin_orders(event):
|
|||
)
|
||||
|
||||
|
||||
def handle_admin_summary_pdf(event):
|
||||
"""Return a short-lived presigned URL for the week's summary PDF."""
|
||||
user, err = _verify_admin(event)
|
||||
if err:
|
||||
return err
|
||||
|
||||
qs = event.get("queryStringParameters") or {}
|
||||
week = qs.get("week", "")
|
||||
if not week:
|
||||
return response(400, {"error": "week query param is required"})
|
||||
|
||||
summary = get_summary(week)
|
||||
pdf_key = (summary or {}).get("weekly_summary_pdf_s3_key")
|
||||
if not pdf_key:
|
||||
return response(404, {"error": "No summary PDF available for this week"})
|
||||
|
||||
url = boto3.client("s3").generate_presigned_url(
|
||||
"get_object",
|
||||
Params={"Bucket": os.environ["REPORTS_BUCKET"], "Key": pdf_key},
|
||||
ExpiresIn=300,
|
||||
)
|
||||
logger.info("Admin %s requested summary PDF for %s", user["email"], week)
|
||||
return response(200, {"week": week, "url": url})
|
||||
|
||||
|
||||
def handle_admin_delete(event):
|
||||
user, err = _verify_admin(event)
|
||||
if err:
|
||||
|
|
|
|||
|
|
@ -60,6 +60,9 @@ def generate_form(
|
|||
admin_url = (
|
||||
f"{api_url}/api/admin/orders" if api_url else "/api/admin/orders"
|
||||
).replace("</", "<\\/")
|
||||
admin_pdf_url = (
|
||||
f"{api_url}/api/admin/summary-pdf" if api_url else "/api/admin/summary-pdf"
|
||||
).replace("</", "<\\/")
|
||||
api_key_json = json.dumps(api_key).replace("</", "<\\/")
|
||||
has_discount = bulk_discount > 0 or company_subsidy > 0
|
||||
use_google_auth = bool(google_client_id)
|
||||
|
|
@ -416,6 +419,7 @@ body {{ padding-bottom: 80px; }}
|
|||
<div style="display:flex;gap:8px;align-items:center;">
|
||||
<select id="admin-week" onchange="loadWeekOrders(this.value)" style="padding:8px 12px;border:1px solid #d1d5db;border-radius:8px;font-size:0.9rem;"></select>
|
||||
<button id="admin-download-btn" onclick="downloadOrderList()" style="margin:0;padding:8px 16px;font-size:0.85rem;background:#1a1a2e;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600;" disabled>Download order list</button>
|
||||
<button id="admin-pdf-btn" onclick="downloadSummaryPdf()" style="margin:0;padding:8px 16px;font-size:0.85rem;background:#1a1a2e;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600;">Download summary PDF</button>
|
||||
<button onclick="hideAdmin()" class="back-btn" style="margin:0;padding:8px 16px;font-size:0.85rem;">Back to Menu</button>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -452,6 +456,7 @@ const SUBMIT_URL = '{submit_url}';
|
|||
const STATUS_URL = '{status_url}';
|
||||
const ROSTER_URL = '{roster_url}';
|
||||
const ADMIN_URL = '{admin_url}';
|
||||
const ADMIN_PDF_URL = '{admin_pdf_url}';
|
||||
const API_KEY = {api_key_json};
|
||||
const WEEK = '{week}';
|
||||
const BULK_DISCOUNT = {bulk_discount};
|
||||
|
|
@ -838,6 +843,28 @@ function downloadOrderList() {{
|
|||
URL.revokeObjectURL(url);
|
||||
}}
|
||||
|
||||
// Fetch a short-lived presigned URL for the loaded week's summary PDF
|
||||
// (generated at Thursday close) and open it. 404 means the week has not
|
||||
// closed yet, so no PDF exists.
|
||||
function downloadSummaryPdf() {{
|
||||
const week = currentAdminWeek || WEEK;
|
||||
const btn = document.getElementById('admin-pdf-btn');
|
||||
if (btn) btn.disabled = true;
|
||||
fetch(ADMIN_PDF_URL + '?week=' + encodeURIComponent(week), {{ headers: adminHeaders() }})
|
||||
.then(r => r.json().then(data => ({{ ok: r.ok, status: r.status, data }})))
|
||||
.then(({{ ok, status, data }}) => {{
|
||||
if (ok && data.url) {{
|
||||
window.location.href = data.url;
|
||||
}} else if (status === 404) {{
|
||||
alert('No summary PDF for ' + week + ' yet — it is generated when the week closes on Thursday.');
|
||||
}} else {{
|
||||
alert('Could not fetch the summary PDF: ' + (data.error || 'unknown error'));
|
||||
}}
|
||||
}})
|
||||
.catch(() => alert('Could not fetch the summary PDF.'))
|
||||
.finally(() => {{ if (btn) btn.disabled = false; }});
|
||||
}}
|
||||
|
||||
let lastAdminData = null;
|
||||
const origLoadWeekOrders = loadWeekOrders;
|
||||
|
||||
|
|
|
|||
|
|
@ -257,6 +257,7 @@ Resources:
|
|||
FORM_APIKEY_SM_NAME: meal-order-manager/form-api-key
|
||||
SLACK_NOTIFIER_ARN: !GetAtt SlackNotifierFunction.Arn
|
||||
GOOGLE_CLIENT_ID_PARAM: /meal-order-manager/google-client-id
|
||||
REPORTS_BUCKET: !Ref ReportsBucket
|
||||
Policies:
|
||||
- DynamoDBCrudPolicy:
|
||||
TableName: !Ref OrdersTable
|
||||
|
|
@ -270,6 +271,11 @@ Resources:
|
|||
- Effect: Allow
|
||||
Action: ssm:GetParameter
|
||||
Resource: !Sub 'arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/meal-order-manager/*'
|
||||
# Read-only access to weekly report PDFs for the admin
|
||||
# summary-pdf presigned-URL endpoint.
|
||||
- Effect: Allow
|
||||
Action: s3:GetObject
|
||||
Resource: !Sub '${ReportsBucket.Arn}/reports/*'
|
||||
Events:
|
||||
SubmitOrder:
|
||||
Type: HttpApi
|
||||
|
|
@ -307,6 +313,12 @@ Resources:
|
|||
ApiId: !Ref OrderApi
|
||||
Path: /api/admin/orders
|
||||
Method: DELETE
|
||||
AdminSummaryPdf:
|
||||
Type: HttpApi
|
||||
Properties:
|
||||
ApiId: !Ref OrderApi
|
||||
Path: /api/admin/summary-pdf
|
||||
Method: GET
|
||||
|
||||
CloseFormFunction:
|
||||
Type: AWS::Serverless::Function
|
||||
|
|
|
|||
|
|
@ -1584,3 +1584,92 @@ def test_slack_failure_does_not_fail_order(
|
|||
assert status == 200, f"Expected 200 despite Slack failure, got {status}: {body}"
|
||||
assert body["status"] == "ok", f"Expected status='ok', got '{body['status']}'"
|
||||
mock_put.assert_called_once()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Admin summary-PDF endpoint
|
||||
# ---------------------------------------------------------------------------
|
||||
def _pdf_event(week=None):
|
||||
qs = {"week": week} if week else {}
|
||||
return {
|
||||
"rawPath": "/api/admin/summary-pdf",
|
||||
"requestContext": {"http": {"method": "GET"}},
|
||||
"queryStringParameters": qs,
|
||||
"headers": {"authorization": "Bearer admin-token"},
|
||||
}
|
||||
|
||||
|
||||
@patch.dict(os.environ, {"REPORTS_BUCKET": "test-reports-bucket"})
|
||||
@patch("submit_order_handler.boto3.client")
|
||||
@patch("submit_order_handler.get_summary")
|
||||
@patch(
|
||||
"submit_order_handler._verify_admin",
|
||||
return_value=({"email": "adam@seahavenind.com"}, None),
|
||||
)
|
||||
def test_admin_summary_pdf_returns_presigned_url(
|
||||
mock_verify, mock_get_summary, mock_boto_client
|
||||
):
|
||||
"""Closed week with a stamped PDF key returns a presigned URL."""
|
||||
from submit_order_handler import lambda_handler
|
||||
|
||||
mock_get_summary.return_value = {
|
||||
"weekly_summary_pdf_s3_key": "reports/2026-W22/weekly-summary-2026-W22.pdf"
|
||||
}
|
||||
mock_s3 = MagicMock()
|
||||
mock_s3.generate_presigned_url.return_value = "https://signed.example/pdf"
|
||||
mock_boto_client.return_value = mock_s3
|
||||
|
||||
status, body = _parse_response(lambda_handler(_pdf_event("2026-W22"), None))
|
||||
|
||||
assert status == 200, f"Expected 200, got {status}: {body}"
|
||||
assert body["url"] == "https://signed.example/pdf"
|
||||
assert body["week"] == "2026-W22"
|
||||
mock_s3.generate_presigned_url.assert_called_once_with(
|
||||
"get_object",
|
||||
Params={
|
||||
"Bucket": "test-reports-bucket",
|
||||
"Key": "reports/2026-W22/weekly-summary-2026-W22.pdf",
|
||||
},
|
||||
ExpiresIn=300,
|
||||
)
|
||||
|
||||
|
||||
@patch("submit_order_handler.get_summary", return_value=None)
|
||||
@patch(
|
||||
"submit_order_handler._verify_admin",
|
||||
return_value=({"email": "adam@seahavenind.com"}, None),
|
||||
)
|
||||
def test_admin_summary_pdf_404_when_week_not_closed(mock_verify, mock_get_summary):
|
||||
"""No SUMMARY item (week still open) returns 404."""
|
||||
from submit_order_handler import lambda_handler
|
||||
|
||||
status, body = _parse_response(lambda_handler(_pdf_event("2026-W23"), None))
|
||||
|
||||
assert status == 404, f"Expected 404, got {status}: {body}"
|
||||
assert "no summary pdf" in body["error"].lower()
|
||||
|
||||
|
||||
@patch(
|
||||
"submit_order_handler._verify_admin",
|
||||
return_value=({"email": "adam@seahavenind.com"}, None),
|
||||
)
|
||||
def test_admin_summary_pdf_400_without_week(mock_verify):
|
||||
"""Missing week query param returns 400."""
|
||||
from submit_order_handler import lambda_handler
|
||||
|
||||
status, body = _parse_response(lambda_handler(_pdf_event(), None))
|
||||
|
||||
assert status == 400, f"Expected 400, got {status}: {body}"
|
||||
|
||||
|
||||
@patch(
|
||||
"submit_order_handler._verify_admin",
|
||||
return_value=(None, submit_order_handler.response(401, {"error": "Missing token"})),
|
||||
)
|
||||
def test_admin_summary_pdf_requires_admin(mock_verify):
|
||||
"""Auth failure from _verify_admin is returned as-is."""
|
||||
from submit_order_handler import lambda_handler
|
||||
|
||||
status, body = _parse_response(lambda_handler(_pdf_event("2026-W22"), None))
|
||||
|
||||
assert status == 401, f"Expected 401, got {status}: {body}"
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue