Monorepo: consolidate 7 repos into one
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m5s
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m5s
Combines shared, blog, market, cart, events, federation, and account into a single repository. Eliminates submodule sync, sibling model copying at build time, and per-app CI orchestration. Changes: - Remove per-app .git, .gitmodules, .gitea, submodule shared/ dirs - Remove stale sibling model copies from each app - Update all 6 Dockerfiles for monorepo build context (root = .) - Add build directives to docker-compose.yml - Add single .gitea/workflows/ci.yml with change detection - Add .dockerignore for monorepo build context - Create __init__.py for federation and account (cross-app imports)
This commit is contained in:
688
blog/bp/post/admin/routes.py
Normal file
688
blog/bp/post/admin/routes.py
Normal file
@@ -0,0 +1,688 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
from quart import (
|
||||
render_template,
|
||||
make_response,
|
||||
Blueprint,
|
||||
g,
|
||||
request,
|
||||
redirect,
|
||||
url_for,
|
||||
)
|
||||
from shared.browser.app.authz import require_admin, require_post_author
|
||||
from shared.browser.app.utils.htmx import is_htmx_request
|
||||
from shared.utils import host_url
|
||||
|
||||
def register():
|
||||
bp = Blueprint("admin", __name__, url_prefix='/admin')
|
||||
|
||||
|
||||
@bp.get("/")
|
||||
@require_admin
|
||||
async def admin(slug: str):
|
||||
from shared.browser.app.utils.htmx import is_htmx_request
|
||||
from shared.models.page_config import PageConfig
|
||||
from sqlalchemy import select as sa_select
|
||||
|
||||
# Load features for page admin
|
||||
post = (g.post_data or {}).get("post", {})
|
||||
features = {}
|
||||
sumup_configured = False
|
||||
sumup_merchant_code = ""
|
||||
sumup_checkout_prefix = ""
|
||||
if post.get("is_page"):
|
||||
pc = (await g.s.execute(
|
||||
sa_select(PageConfig).where(PageConfig.container_type == "page", PageConfig.container_id == post["id"])
|
||||
)).scalar_one_or_none()
|
||||
if pc:
|
||||
features = pc.features or {}
|
||||
sumup_configured = bool(pc.sumup_api_key)
|
||||
sumup_merchant_code = pc.sumup_merchant_code or ""
|
||||
sumup_checkout_prefix = pc.sumup_checkout_prefix or ""
|
||||
|
||||
ctx = {
|
||||
"features": features,
|
||||
"sumup_configured": sumup_configured,
|
||||
"sumup_merchant_code": sumup_merchant_code,
|
||||
"sumup_checkout_prefix": sumup_checkout_prefix,
|
||||
}
|
||||
|
||||
# Determine which template to use based on request type
|
||||
if not is_htmx_request():
|
||||
# Normal browser request: full page with layout
|
||||
html = await render_template("_types/post/admin/index.html", **ctx)
|
||||
else:
|
||||
# HTMX request: main panel + OOB elements
|
||||
html = await render_template("_types/post/admin/_oob_elements.html", **ctx)
|
||||
|
||||
return await make_response(html)
|
||||
|
||||
@bp.put("/features/")
|
||||
@require_admin
|
||||
async def update_features(slug: str):
|
||||
"""Update PageConfig.features for a page."""
|
||||
from shared.models.page_config import PageConfig
|
||||
from models.ghost_content import Post
|
||||
from sqlalchemy import select as sa_select
|
||||
from quart import jsonify
|
||||
import json
|
||||
|
||||
post = g.post_data.get("post")
|
||||
if not post or not post.get("is_page"):
|
||||
return jsonify({"error": "This is not a page."}), 400
|
||||
|
||||
post_id = post["id"]
|
||||
|
||||
# Load or create PageConfig
|
||||
pc = (await g.s.execute(
|
||||
sa_select(PageConfig).where(PageConfig.container_type == "page", PageConfig.container_id == post_id)
|
||||
)).scalar_one_or_none()
|
||||
if pc is None:
|
||||
pc = PageConfig(container_type="page", container_id=post_id, features={})
|
||||
g.s.add(pc)
|
||||
await g.s.flush()
|
||||
from shared.services.relationships import attach_child
|
||||
await attach_child(g.s, "page", post_id, "page_config", pc.id)
|
||||
|
||||
# Parse request body
|
||||
body = await request.get_json()
|
||||
if body is None:
|
||||
# Fall back to form data
|
||||
form = await request.form
|
||||
body = {}
|
||||
for key in ("calendar", "market"):
|
||||
val = form.get(key)
|
||||
if val is not None:
|
||||
body[key] = val in ("true", "1", "on")
|
||||
|
||||
if not isinstance(body, dict):
|
||||
return jsonify({"error": "Expected JSON object with feature flags."}), 400
|
||||
|
||||
# Merge features
|
||||
features = dict(pc.features or {})
|
||||
for key, val in body.items():
|
||||
if isinstance(val, bool):
|
||||
features[key] = val
|
||||
elif val in ("true", "1", "on"):
|
||||
features[key] = True
|
||||
elif val in ("false", "0", "off", None):
|
||||
features[key] = False
|
||||
|
||||
pc.features = features
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
flag_modified(pc, "features")
|
||||
await g.s.flush()
|
||||
|
||||
# Return updated features panel
|
||||
html = await render_template(
|
||||
"_types/post/admin/_features_panel.html",
|
||||
features=features,
|
||||
post=post,
|
||||
sumup_configured=bool(pc.sumup_api_key),
|
||||
sumup_merchant_code=pc.sumup_merchant_code or "",
|
||||
sumup_checkout_prefix=pc.sumup_checkout_prefix or "",
|
||||
)
|
||||
return await make_response(html)
|
||||
|
||||
@bp.put("/admin/sumup/")
|
||||
@require_admin
|
||||
async def update_sumup(slug: str):
|
||||
"""Update PageConfig SumUp credentials for a page."""
|
||||
from shared.models.page_config import PageConfig
|
||||
from sqlalchemy import select as sa_select
|
||||
from quart import jsonify
|
||||
|
||||
post = g.post_data.get("post")
|
||||
if not post or not post.get("is_page"):
|
||||
return jsonify({"error": "This is not a page."}), 400
|
||||
|
||||
post_id = post["id"]
|
||||
|
||||
pc = (await g.s.execute(
|
||||
sa_select(PageConfig).where(PageConfig.container_type == "page", PageConfig.container_id == post_id)
|
||||
)).scalar_one_or_none()
|
||||
if pc is None:
|
||||
pc = PageConfig(container_type="page", container_id=post_id, features={})
|
||||
g.s.add(pc)
|
||||
await g.s.flush()
|
||||
from shared.services.relationships import attach_child
|
||||
await attach_child(g.s, "page", post_id, "page_config", pc.id)
|
||||
|
||||
form = await request.form
|
||||
merchant_code = (form.get("merchant_code") or "").strip()
|
||||
api_key = (form.get("api_key") or "").strip()
|
||||
checkout_prefix = (form.get("checkout_prefix") or "").strip()
|
||||
|
||||
pc.sumup_merchant_code = merchant_code or None
|
||||
pc.sumup_checkout_prefix = checkout_prefix or None
|
||||
# Only update API key if non-empty (allows updating other fields without re-entering key)
|
||||
if api_key:
|
||||
pc.sumup_api_key = api_key
|
||||
|
||||
await g.s.flush()
|
||||
|
||||
features = pc.features or {}
|
||||
html = await render_template(
|
||||
"_types/post/admin/_features_panel.html",
|
||||
features=features,
|
||||
post=post,
|
||||
sumup_configured=bool(pc.sumup_api_key),
|
||||
sumup_merchant_code=pc.sumup_merchant_code or "",
|
||||
sumup_checkout_prefix=pc.sumup_checkout_prefix or "",
|
||||
)
|
||||
return await make_response(html)
|
||||
|
||||
@bp.get("/data/")
|
||||
@require_admin
|
||||
async def data(slug: str):
|
||||
if not is_htmx_request():
|
||||
html = await render_template(
|
||||
"_types/post_data/index.html",
|
||||
)
|
||||
else:
|
||||
html = await render_template(
|
||||
"_types/post_data/_oob_elements.html",
|
||||
)
|
||||
|
||||
return await make_response(html)
|
||||
|
||||
@bp.get("/entries/calendar/<int:calendar_id>/")
|
||||
@require_admin
|
||||
async def calendar_view(slug: str, calendar_id: int):
|
||||
"""Show calendar month view for browsing entries"""
|
||||
from shared.models.calendars import Calendar
|
||||
from shared.utils.calendar_helpers import parse_int_arg, add_months, build_calendar_weeks
|
||||
from shared.services.registry import services
|
||||
from sqlalchemy import select
|
||||
from datetime import datetime, timezone
|
||||
import calendar as pycalendar
|
||||
from quart import session as qsession
|
||||
from ..services.entry_associations import get_post_entry_ids
|
||||
|
||||
# Get month/year from query params
|
||||
today = datetime.now(timezone.utc).date()
|
||||
month = parse_int_arg("month")
|
||||
year = parse_int_arg("year")
|
||||
|
||||
if year is None:
|
||||
year = today.year
|
||||
if month is None or not (1 <= month <= 12):
|
||||
month = today.month
|
||||
|
||||
# Load calendar
|
||||
result = await g.s.execute(
|
||||
select(Calendar).where(Calendar.id == calendar_id, Calendar.deleted_at.is_(None))
|
||||
)
|
||||
calendar_obj = result.scalar_one_or_none()
|
||||
if not calendar_obj:
|
||||
return await make_response("Calendar not found", 404)
|
||||
|
||||
# Build calendar data
|
||||
prev_month_year, prev_month = add_months(year, month, -1)
|
||||
next_month_year, next_month = add_months(year, month, +1)
|
||||
prev_year = year - 1
|
||||
next_year = year + 1
|
||||
|
||||
weeks = build_calendar_weeks(year, month)
|
||||
month_name = pycalendar.month_name[month]
|
||||
weekday_names = [pycalendar.day_abbr[i] for i in range(7)]
|
||||
|
||||
# Get entries for this month
|
||||
period_start = datetime(year, month, 1, tzinfo=timezone.utc)
|
||||
next_y, next_m = add_months(year, month, +1)
|
||||
period_end = datetime(next_y, next_m, 1, tzinfo=timezone.utc)
|
||||
|
||||
user = getattr(g, "user", None)
|
||||
user_id = user.id if user else None
|
||||
is_admin = bool(user and getattr(user, "is_admin", False))
|
||||
session_id = qsession.get("calendar_sid")
|
||||
|
||||
month_entries = await services.calendar.visible_entries_for_period(
|
||||
g.s, calendar_obj.id, period_start, period_end,
|
||||
user_id=user_id, is_admin=is_admin, session_id=session_id,
|
||||
)
|
||||
|
||||
# Get associated entry IDs for this post
|
||||
post_id = g.post_data["post"]["id"]
|
||||
associated_entry_ids = await get_post_entry_ids(g.s, post_id)
|
||||
|
||||
html = await render_template(
|
||||
"_types/post/admin/_calendar_view.html",
|
||||
calendar=calendar_obj,
|
||||
year=year,
|
||||
month=month,
|
||||
month_name=month_name,
|
||||
weekday_names=weekday_names,
|
||||
weeks=weeks,
|
||||
prev_month=prev_month,
|
||||
prev_month_year=prev_month_year,
|
||||
next_month=next_month,
|
||||
next_month_year=next_month_year,
|
||||
prev_year=prev_year,
|
||||
next_year=next_year,
|
||||
month_entries=month_entries,
|
||||
associated_entry_ids=associated_entry_ids,
|
||||
)
|
||||
return await make_response(html)
|
||||
|
||||
@bp.get("/entries/")
|
||||
@require_admin
|
||||
async def entries(slug: str):
|
||||
from ..services.entry_associations import get_post_entry_ids
|
||||
from shared.models.calendars import Calendar
|
||||
from sqlalchemy import select
|
||||
|
||||
post_id = g.post_data["post"]["id"]
|
||||
associated_entry_ids = await get_post_entry_ids(g.s, post_id)
|
||||
|
||||
# Load ALL calendars (not just this post's calendars)
|
||||
result = await g.s.execute(
|
||||
select(Calendar)
|
||||
.where(Calendar.deleted_at.is_(None))
|
||||
.order_by(Calendar.name.asc())
|
||||
)
|
||||
all_calendars = result.scalars().all()
|
||||
|
||||
# Load entries and post for each calendar
|
||||
for calendar in all_calendars:
|
||||
await g.s.refresh(calendar, ["entries", "post"])
|
||||
if not is_htmx_request():
|
||||
html = await render_template(
|
||||
"_types/post_entries/index.html",
|
||||
all_calendars=all_calendars,
|
||||
associated_entry_ids=associated_entry_ids,
|
||||
)
|
||||
else:
|
||||
html = await render_template(
|
||||
"_types/post_entries/_oob_elements.html",
|
||||
all_calendars=all_calendars,
|
||||
associated_entry_ids=associated_entry_ids,
|
||||
)
|
||||
|
||||
return await make_response(html)
|
||||
|
||||
@bp.post("/entries/<int:entry_id>/toggle/")
|
||||
@require_admin
|
||||
async def toggle_entry(slug: str, entry_id: int):
|
||||
from ..services.entry_associations import toggle_entry_association, get_post_entry_ids, get_associated_entries
|
||||
from shared.models.calendars import Calendar
|
||||
from sqlalchemy import select
|
||||
from quart import jsonify
|
||||
|
||||
post_id = g.post_data["post"]["id"]
|
||||
is_associated, error = await toggle_entry_association(g.s, post_id, entry_id)
|
||||
|
||||
if error:
|
||||
return jsonify({"message": error, "errors": {}}), 400
|
||||
|
||||
await g.s.flush()
|
||||
|
||||
# Return updated association status
|
||||
associated_entry_ids = await get_post_entry_ids(g.s, post_id)
|
||||
|
||||
# Load ALL calendars
|
||||
result = await g.s.execute(
|
||||
select(Calendar)
|
||||
.where(Calendar.deleted_at.is_(None))
|
||||
.order_by(Calendar.name.asc())
|
||||
)
|
||||
all_calendars = result.scalars().all()
|
||||
|
||||
# Load entries and post for each calendar
|
||||
for calendar in all_calendars:
|
||||
await g.s.refresh(calendar, ["entries", "post"])
|
||||
|
||||
# Fetch associated entries for nav display
|
||||
associated_entries = await get_associated_entries(g.s, post_id)
|
||||
|
||||
# Load calendars for this post (for nav display)
|
||||
calendars = (
|
||||
await g.s.execute(
|
||||
select(Calendar)
|
||||
.where(Calendar.container_type == "page", Calendar.container_id == post_id, Calendar.deleted_at.is_(None))
|
||||
.order_by(Calendar.name.asc())
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
# Return the associated entries admin list + OOB update for nav entries
|
||||
admin_list = await render_template(
|
||||
"_types/post/admin/_associated_entries.html",
|
||||
all_calendars=all_calendars,
|
||||
associated_entry_ids=associated_entry_ids,
|
||||
)
|
||||
|
||||
nav_entries_oob = await render_template(
|
||||
"_types/post/admin/_nav_entries_oob.html",
|
||||
associated_entries=associated_entries,
|
||||
calendars=calendars,
|
||||
post=g.post_data["post"],
|
||||
)
|
||||
|
||||
return await make_response(admin_list + nav_entries_oob)
|
||||
|
||||
@bp.get("/settings/")
|
||||
@require_post_author
|
||||
async def settings(slug: str):
|
||||
from ...blog.ghost.ghost_posts import get_post_for_edit
|
||||
|
||||
ghost_id = g.post_data["post"]["ghost_id"]
|
||||
is_page = bool(g.post_data["post"].get("is_page"))
|
||||
ghost_post = await get_post_for_edit(ghost_id, is_page=is_page)
|
||||
save_success = request.args.get("saved") == "1"
|
||||
|
||||
if not is_htmx_request():
|
||||
html = await render_template(
|
||||
"_types/post_settings/index.html",
|
||||
ghost_post=ghost_post,
|
||||
save_success=save_success,
|
||||
)
|
||||
else:
|
||||
html = await render_template(
|
||||
"_types/post_settings/_oob_elements.html",
|
||||
ghost_post=ghost_post,
|
||||
save_success=save_success,
|
||||
)
|
||||
|
||||
return await make_response(html)
|
||||
|
||||
@bp.post("/settings/")
|
||||
@require_post_author
|
||||
async def settings_save(slug: str):
|
||||
from ...blog.ghost.ghost_posts import update_post_settings
|
||||
from ...blog.ghost.ghost_sync import sync_single_post, sync_single_page
|
||||
from shared.browser.app.redis_cacher import invalidate_tag_cache
|
||||
|
||||
ghost_id = g.post_data["post"]["ghost_id"]
|
||||
is_page = bool(g.post_data["post"].get("is_page"))
|
||||
form = await request.form
|
||||
|
||||
updated_at = form.get("updated_at", "")
|
||||
|
||||
# Build kwargs — only include fields that were submitted
|
||||
kwargs: dict = {}
|
||||
|
||||
# Text fields
|
||||
for field in (
|
||||
"slug", "custom_template", "meta_title", "meta_description",
|
||||
"canonical_url", "og_image", "og_title", "og_description",
|
||||
"twitter_image", "twitter_title", "twitter_description",
|
||||
"feature_image_alt",
|
||||
):
|
||||
val = form.get(field)
|
||||
if val is not None:
|
||||
kwargs[field] = val.strip()
|
||||
|
||||
# Select fields
|
||||
visibility = form.get("visibility")
|
||||
if visibility is not None:
|
||||
kwargs["visibility"] = visibility
|
||||
|
||||
# Datetime
|
||||
published_at = form.get("published_at", "").strip()
|
||||
if published_at:
|
||||
kwargs["published_at"] = published_at
|
||||
|
||||
# Checkbox fields: present = True, absent = False
|
||||
kwargs["featured"] = form.get("featured") == "on"
|
||||
kwargs["email_only"] = form.get("email_only") == "on"
|
||||
|
||||
# Tags — comma-separated string → list of {"name": "..."} dicts
|
||||
tags_str = form.get("tags", "").strip()
|
||||
if tags_str:
|
||||
kwargs["tags"] = [{"name": t.strip()} for t in tags_str.split(",") if t.strip()]
|
||||
else:
|
||||
kwargs["tags"] = []
|
||||
|
||||
# Update in Ghost
|
||||
await update_post_settings(
|
||||
ghost_id=ghost_id,
|
||||
updated_at=updated_at,
|
||||
is_page=is_page,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
# Sync to local DB
|
||||
if is_page:
|
||||
await sync_single_page(g.s, ghost_id)
|
||||
else:
|
||||
await sync_single_post(g.s, ghost_id)
|
||||
await g.s.flush()
|
||||
|
||||
# Clear caches
|
||||
await invalidate_tag_cache("blog")
|
||||
await invalidate_tag_cache("post.post_detail")
|
||||
|
||||
return redirect(host_url(url_for("blog.post.admin.settings", slug=slug)) + "?saved=1")
|
||||
|
||||
@bp.get("/edit/")
|
||||
@require_post_author
|
||||
async def edit(slug: str):
|
||||
from ...blog.ghost.ghost_posts import get_post_for_edit
|
||||
from shared.models.ghost_membership_entities import GhostNewsletter
|
||||
from sqlalchemy import select as sa_select
|
||||
|
||||
ghost_id = g.post_data["post"]["ghost_id"]
|
||||
is_page = bool(g.post_data["post"].get("is_page"))
|
||||
ghost_post = await get_post_for_edit(ghost_id, is_page=is_page)
|
||||
save_success = request.args.get("saved") == "1"
|
||||
|
||||
newsletters = (await g.s.execute(
|
||||
sa_select(GhostNewsletter).order_by(GhostNewsletter.name)
|
||||
)).scalars().all()
|
||||
|
||||
if not is_htmx_request():
|
||||
html = await render_template(
|
||||
"_types/post_edit/index.html",
|
||||
ghost_post=ghost_post,
|
||||
save_success=save_success,
|
||||
newsletters=newsletters,
|
||||
)
|
||||
else:
|
||||
html = await render_template(
|
||||
"_types/post_edit/_oob_elements.html",
|
||||
ghost_post=ghost_post,
|
||||
save_success=save_success,
|
||||
newsletters=newsletters,
|
||||
)
|
||||
|
||||
return await make_response(html)
|
||||
|
||||
@bp.post("/edit/")
|
||||
@require_post_author
|
||||
async def edit_save(slug: str):
|
||||
import json
|
||||
from ...blog.ghost.ghost_posts import update_post
|
||||
from ...blog.ghost.lexical_validator import validate_lexical
|
||||
from ...blog.ghost.ghost_sync import sync_single_post, sync_single_page
|
||||
from shared.browser.app.redis_cacher import invalidate_tag_cache
|
||||
|
||||
ghost_id = g.post_data["post"]["ghost_id"]
|
||||
is_page = bool(g.post_data["post"].get("is_page"))
|
||||
form = await request.form
|
||||
title = form.get("title", "").strip()
|
||||
lexical_raw = form.get("lexical", "")
|
||||
updated_at = form.get("updated_at", "")
|
||||
status = form.get("status", "draft")
|
||||
publish_mode = form.get("publish_mode", "web")
|
||||
newsletter_slug = form.get("newsletter_slug", "").strip() or None
|
||||
feature_image = form.get("feature_image", "").strip()
|
||||
custom_excerpt = form.get("custom_excerpt", "").strip()
|
||||
feature_image_caption = form.get("feature_image_caption", "").strip()
|
||||
|
||||
# Validate the lexical JSON
|
||||
try:
|
||||
lexical_doc = json.loads(lexical_raw)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
from ...blog.ghost.ghost_posts import get_post_for_edit
|
||||
ghost_post = await get_post_for_edit(ghost_id, is_page=is_page)
|
||||
html = await render_template(
|
||||
"_types/post_edit/index.html",
|
||||
ghost_post=ghost_post,
|
||||
save_error="Invalid JSON in editor content.",
|
||||
)
|
||||
return await make_response(html, 400)
|
||||
|
||||
ok, reason = validate_lexical(lexical_doc)
|
||||
if not ok:
|
||||
from ...blog.ghost.ghost_posts import get_post_for_edit
|
||||
ghost_post = await get_post_for_edit(ghost_id, is_page=is_page)
|
||||
html = await render_template(
|
||||
"_types/post_edit/index.html",
|
||||
ghost_post=ghost_post,
|
||||
save_error=reason,
|
||||
)
|
||||
return await make_response(html, 400)
|
||||
|
||||
# Update in Ghost (content save — no status change yet)
|
||||
ghost_post = await update_post(
|
||||
ghost_id=ghost_id,
|
||||
lexical_json=lexical_raw,
|
||||
title=title or None,
|
||||
updated_at=updated_at,
|
||||
feature_image=feature_image,
|
||||
custom_excerpt=custom_excerpt,
|
||||
feature_image_caption=feature_image_caption,
|
||||
is_page=is_page,
|
||||
)
|
||||
|
||||
# Publish workflow
|
||||
is_admin = bool((g.get("rights") or {}).get("admin"))
|
||||
publish_requested_msg = None
|
||||
|
||||
# Guard: if already emailed, force publish_mode to "web" to prevent re-send
|
||||
already_emailed = bool(ghost_post.get("email") and ghost_post["email"].get("status"))
|
||||
if already_emailed and publish_mode in ("email", "both"):
|
||||
publish_mode = "web"
|
||||
|
||||
if status == "published" and ghost_post.get("status") != "published" and not is_admin:
|
||||
# Non-admin requesting publish: don't send status to Ghost, set local flag
|
||||
publish_requested_msg = "Publish requested — an admin will review."
|
||||
elif status and status != ghost_post.get("status"):
|
||||
# Status is changing — determine email params based on publish_mode
|
||||
email_kwargs: dict = {}
|
||||
if status == "published" and publish_mode in ("email", "both") and newsletter_slug:
|
||||
email_kwargs["newsletter_slug"] = newsletter_slug
|
||||
email_kwargs["email_segment"] = "all"
|
||||
if publish_mode == "email":
|
||||
email_kwargs["email_only"] = True
|
||||
|
||||
from ...blog.ghost.ghost_posts import update_post as _up
|
||||
ghost_post = await _up(
|
||||
ghost_id=ghost_id,
|
||||
lexical_json=lexical_raw,
|
||||
title=None,
|
||||
updated_at=ghost_post["updated_at"],
|
||||
status=status,
|
||||
is_page=is_page,
|
||||
**email_kwargs,
|
||||
)
|
||||
|
||||
# Sync to local DB
|
||||
if is_page:
|
||||
await sync_single_page(g.s, ghost_id)
|
||||
else:
|
||||
await sync_single_post(g.s, ghost_id)
|
||||
await g.s.flush()
|
||||
|
||||
# Handle publish_requested flag on the local post
|
||||
from models.ghost_content import Post
|
||||
from sqlalchemy import select as sa_select
|
||||
local_post = (await g.s.execute(
|
||||
sa_select(Post).where(Post.ghost_id == ghost_id)
|
||||
)).scalar_one_or_none()
|
||||
if local_post:
|
||||
if publish_requested_msg:
|
||||
local_post.publish_requested = True
|
||||
elif status == "published" and is_admin:
|
||||
local_post.publish_requested = False
|
||||
await g.s.flush()
|
||||
|
||||
# Clear caches
|
||||
await invalidate_tag_cache("blog")
|
||||
await invalidate_tag_cache("post.post_detail")
|
||||
|
||||
# Redirect to GET to avoid resubmit warning on refresh (PRG pattern)
|
||||
redirect_url = host_url(url_for("blog.post.admin.edit", slug=slug)) + "?saved=1"
|
||||
if publish_requested_msg:
|
||||
redirect_url += "&publish_requested=1"
|
||||
return redirect(redirect_url)
|
||||
|
||||
|
||||
@bp.get("/markets/")
|
||||
@require_admin
|
||||
async def markets(slug: str):
|
||||
"""List markets for this page."""
|
||||
from shared.services.registry import services
|
||||
|
||||
post = (g.post_data or {}).get("post", {})
|
||||
post_id = post.get("id")
|
||||
if not post_id:
|
||||
return await make_response("Post not found", 404)
|
||||
|
||||
page_markets = await services.market.marketplaces_for_container(g.s, "page", post_id)
|
||||
|
||||
html = await render_template(
|
||||
"_types/post/admin/_markets_panel.html",
|
||||
markets=page_markets,
|
||||
post=post,
|
||||
)
|
||||
return await make_response(html)
|
||||
|
||||
@bp.post("/markets/new/")
|
||||
@require_admin
|
||||
async def create_market(slug: str):
|
||||
"""Create a new market for this page."""
|
||||
from ..services.markets import create_market as _create_market, MarketError
|
||||
from shared.services.registry import services
|
||||
from quart import jsonify
|
||||
|
||||
post = (g.post_data or {}).get("post", {})
|
||||
post_id = post.get("id")
|
||||
if not post_id:
|
||||
return jsonify({"error": "Post not found"}), 404
|
||||
|
||||
form = await request.form
|
||||
name = (form.get("name") or "").strip()
|
||||
|
||||
try:
|
||||
await _create_market(g.s, post_id, name)
|
||||
except MarketError as e:
|
||||
return jsonify({"error": str(e)}), 400
|
||||
|
||||
# Return updated markets list
|
||||
page_markets = await services.market.marketplaces_for_container(g.s, "page", post_id)
|
||||
|
||||
html = await render_template(
|
||||
"_types/post/admin/_markets_panel.html",
|
||||
markets=page_markets,
|
||||
post=post,
|
||||
)
|
||||
return await make_response(html)
|
||||
|
||||
@bp.delete("/markets/<market_slug>/")
|
||||
@require_admin
|
||||
async def delete_market(slug: str, market_slug: str):
|
||||
"""Soft-delete a market."""
|
||||
from ..services.markets import soft_delete_market
|
||||
from shared.services.registry import services
|
||||
from quart import jsonify
|
||||
|
||||
post = (g.post_data or {}).get("post", {})
|
||||
post_id = post.get("id")
|
||||
|
||||
deleted = await soft_delete_market(g.s, slug, market_slug)
|
||||
if not deleted:
|
||||
return jsonify({"error": "Market not found"}), 404
|
||||
|
||||
# Return updated markets list
|
||||
page_markets = await services.market.marketplaces_for_container(g.s, "page", post_id)
|
||||
|
||||
html = await render_template(
|
||||
"_types/post/admin/_markets_panel.html",
|
||||
markets=page_markets,
|
||||
post=post,
|
||||
)
|
||||
return await make_response(html)
|
||||
|
||||
return bp
|
||||
180
blog/bp/post/routes.py
Normal file
180
blog/bp/post/routes.py
Normal file
@@ -0,0 +1,180 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
from quart import (
|
||||
render_template,
|
||||
make_response,
|
||||
g,
|
||||
Blueprint,
|
||||
abort,
|
||||
url_for,
|
||||
request,
|
||||
)
|
||||
from .services.post_data import post_data
|
||||
from .services.post_operations import toggle_post_like
|
||||
from shared.services.registry import services
|
||||
from shared.infrastructure.fragments import fetch_fragment, fetch_fragments
|
||||
|
||||
from shared.browser.app.redis_cacher import cache_page, clear_cache
|
||||
|
||||
|
||||
from .admin.routes import register as register_admin
|
||||
from shared.config import config
|
||||
from shared.browser.app.utils.htmx import is_htmx_request
|
||||
|
||||
def register():
|
||||
bp = Blueprint("post", __name__, url_prefix='/<slug>')
|
||||
bp.register_blueprint(
|
||||
register_admin()
|
||||
)
|
||||
|
||||
# Calendar blueprints now live in the events service.
|
||||
# Post pages link to events_url() instead of embedding calendars.
|
||||
|
||||
@bp.url_value_preprocessor
|
||||
def pull_blog(endpoint, values):
|
||||
g.post_slug = values.get("slug")
|
||||
|
||||
@bp.before_request
|
||||
async def hydrate_post_data():
|
||||
slug = getattr(g, "post_slug", None)
|
||||
if not slug:
|
||||
return # not a blog route or no slug in this URL
|
||||
|
||||
is_admin = bool((g.get("rights") or {}).get("admin"))
|
||||
# Always include drafts so we can check ownership below
|
||||
p_data = await post_data(slug, g.s, include_drafts=True)
|
||||
if not p_data:
|
||||
abort(404)
|
||||
return
|
||||
|
||||
# Access control for draft posts
|
||||
if p_data["post"].get("status") != "published":
|
||||
if is_admin:
|
||||
pass # admin can see all drafts
|
||||
elif g.user and p_data["post"].get("user_id") == g.user.id:
|
||||
pass # author can see their own drafts
|
||||
else:
|
||||
abort(404)
|
||||
return
|
||||
|
||||
g.post_data = p_data
|
||||
|
||||
@bp.context_processor
|
||||
async def context():
|
||||
p_data = getattr(g, "post_data", None)
|
||||
if p_data:
|
||||
from shared.infrastructure.cart_identity import current_cart_identity
|
||||
|
||||
db_post_id = (g.post_data.get("post") or {}).get("id")
|
||||
post_slug = (g.post_data.get("post") or {}).get("slug", "")
|
||||
|
||||
# Fetch container nav fragments from events + market
|
||||
paginate_url = url_for(
|
||||
'blog.post.widget_paginate',
|
||||
slug=post_slug, widget_domain='calendar',
|
||||
)
|
||||
nav_params = {
|
||||
"container_type": "page",
|
||||
"container_id": str(db_post_id),
|
||||
"post_slug": post_slug,
|
||||
"paginate_url": paginate_url,
|
||||
}
|
||||
events_nav_html, market_nav_html = await fetch_fragments([
|
||||
("events", "container-nav", nav_params),
|
||||
("market", "container-nav", nav_params),
|
||||
])
|
||||
container_nav_html = events_nav_html + market_nav_html
|
||||
|
||||
ctx = {
|
||||
**p_data,
|
||||
"base_title": f"{config()['title']} {p_data['post']['title']}",
|
||||
"container_nav_html": container_nav_html,
|
||||
}
|
||||
|
||||
# Page cart badge via service
|
||||
post_dict = p_data.get("post") or {}
|
||||
if post_dict.get("is_page"):
|
||||
ident = current_cart_identity()
|
||||
page_summary = await services.cart.cart_summary(
|
||||
g.s, user_id=ident["user_id"], session_id=ident["session_id"],
|
||||
page_slug=post_dict["slug"],
|
||||
)
|
||||
ctx["page_cart_count"] = page_summary.count + page_summary.calendar_count + page_summary.ticket_count
|
||||
ctx["page_cart_total"] = float(page_summary.total + page_summary.calendar_total + page_summary.ticket_total)
|
||||
|
||||
return ctx
|
||||
else:
|
||||
return {}
|
||||
|
||||
@bp.get("/")
|
||||
@cache_page(tag="post.post_detail")
|
||||
async def post_detail(slug: str):
|
||||
# Determine which template to use based on request type
|
||||
if not is_htmx_request():
|
||||
# Normal browser request: full page with layout
|
||||
html = await render_template("_types/post/index.html")
|
||||
else:
|
||||
# HTMX request: main panel + OOB elements
|
||||
html = await render_template("_types/post/_oob_elements.html")
|
||||
|
||||
return await make_response(html)
|
||||
|
||||
@bp.post("/like/toggle/")
|
||||
@clear_cache(tag="post.post_detail", tag_scope="user")
|
||||
async def like_toggle(slug: str):
|
||||
from shared.utils import host_url
|
||||
|
||||
# Get post_id from g.post_data
|
||||
if not g.user:
|
||||
html = await render_template(
|
||||
"_types/browse/like/button.html",
|
||||
slug=slug,
|
||||
liked=False,
|
||||
like_url=host_url(url_for('blog.post.like_toggle', slug=slug)),
|
||||
item_type='post',
|
||||
)
|
||||
resp = make_response(html, 403)
|
||||
return resp
|
||||
|
||||
post_id = g.post_data["post"]["id"]
|
||||
user_id = g.user.id
|
||||
|
||||
liked, error = await toggle_post_like(g.s, user_id, post_id)
|
||||
|
||||
if error:
|
||||
resp = make_response(error, 404)
|
||||
return resp
|
||||
|
||||
html = await render_template(
|
||||
"_types/browse/like/button.html",
|
||||
slug=slug,
|
||||
liked=liked,
|
||||
like_url=host_url(url_for('blog.post.like_toggle', slug=slug)),
|
||||
item_type='post',
|
||||
)
|
||||
return html
|
||||
|
||||
@bp.get("/w/<widget_domain>/")
|
||||
async def widget_paginate(slug: str, widget_domain: str):
|
||||
"""Proxies paginated widget requests to the appropriate fragment provider."""
|
||||
page = int(request.args.get("page", 1))
|
||||
post_id = g.post_data["post"]["id"]
|
||||
|
||||
if widget_domain == "calendar":
|
||||
html = await fetch_fragment("events", "container-nav", params={
|
||||
"container_type": "page",
|
||||
"container_id": str(post_id),
|
||||
"post_slug": slug,
|
||||
"page": str(page),
|
||||
"paginate_url": url_for(
|
||||
'blog.post.widget_paginate',
|
||||
slug=slug, widget_domain='calendar',
|
||||
),
|
||||
})
|
||||
return await make_response(html or "")
|
||||
abort(404)
|
||||
|
||||
return bp
|
||||
|
||||
|
||||
60
blog/bp/post/services/entry_associations.py
Normal file
60
blog/bp/post/services/entry_associations.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from shared.services.registry import services
|
||||
|
||||
|
||||
async def toggle_entry_association(
|
||||
session: AsyncSession,
|
||||
post_id: int,
|
||||
entry_id: int
|
||||
) -> tuple[bool, str | None]:
|
||||
"""
|
||||
Toggle association between a post and calendar entry.
|
||||
Returns (is_now_associated, error_message).
|
||||
"""
|
||||
post = await services.blog.get_post_by_id(session, post_id)
|
||||
if not post:
|
||||
return False, "Post not found"
|
||||
|
||||
is_associated = await services.calendar.toggle_entry_post(
|
||||
session, entry_id, "post", post_id,
|
||||
)
|
||||
return is_associated, None
|
||||
|
||||
|
||||
async def get_post_entry_ids(
|
||||
session: AsyncSession,
|
||||
post_id: int
|
||||
) -> set[int]:
|
||||
"""
|
||||
Get all entry IDs associated with this post.
|
||||
Returns a set of entry IDs.
|
||||
"""
|
||||
return await services.calendar.entry_ids_for_content(session, "post", post_id)
|
||||
|
||||
|
||||
async def get_associated_entries(
|
||||
session: AsyncSession,
|
||||
post_id: int,
|
||||
page: int = 1,
|
||||
per_page: int = 10
|
||||
) -> dict:
|
||||
"""
|
||||
Get paginated associated entries for this post.
|
||||
Returns dict with entries (CalendarEntryDTOs), total_count, and has_more.
|
||||
"""
|
||||
entries, has_more = await services.calendar.associated_entries(
|
||||
session, "post", post_id, page,
|
||||
)
|
||||
total_count = len(entries) + (page - 1) * per_page
|
||||
if has_more:
|
||||
total_count += 1 # at least one more
|
||||
|
||||
return {
|
||||
"entries": entries,
|
||||
"total_count": total_count,
|
||||
"has_more": has_more,
|
||||
"page": page,
|
||||
}
|
||||
61
blog/bp/post/services/markets.py
Normal file
61
blog/bp/post/services/markets.py
Normal file
@@ -0,0 +1,61 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from shared.models.page_config import PageConfig
|
||||
from shared.contracts.dtos import MarketPlaceDTO
|
||||
from shared.services.registry import services
|
||||
|
||||
|
||||
class MarketError(ValueError):
|
||||
"""Base error for market service operations."""
|
||||
|
||||
|
||||
def slugify(value: str, max_len: int = 255) -> str:
|
||||
if value is None:
|
||||
value = ""
|
||||
value = unicodedata.normalize("NFKD", value)
|
||||
value = value.encode("ascii", "ignore").decode("ascii")
|
||||
value = value.lower()
|
||||
value = value.replace("/", "-")
|
||||
value = re.sub(r"[^a-z0-9]+", "-", value)
|
||||
value = re.sub(r"-{2,}", "-", value)
|
||||
value = value.strip("-")[:max_len].strip("-")
|
||||
return value or "market"
|
||||
|
||||
|
||||
async def create_market(sess: AsyncSession, post_id: int, name: str) -> MarketPlaceDTO:
|
||||
name = (name or "").strip()
|
||||
if not name:
|
||||
raise MarketError("Market name must not be empty.")
|
||||
slug = slugify(name)
|
||||
|
||||
post = await services.blog.get_post_by_id(sess, post_id)
|
||||
if not post:
|
||||
raise MarketError(f"Post {post_id} does not exist.")
|
||||
|
||||
if not post.is_page:
|
||||
raise MarketError("Markets can only be created on pages, not posts.")
|
||||
|
||||
pc = (await sess.execute(
|
||||
select(PageConfig).where(PageConfig.container_type == "page", PageConfig.container_id == post_id)
|
||||
)).scalar_one_or_none()
|
||||
if pc is None or not (pc.features or {}).get("market"):
|
||||
raise MarketError("Market feature is not enabled for this page. Enable it in page settings first.")
|
||||
|
||||
try:
|
||||
return await services.market.create_marketplace(sess, "page", post_id, name, slug)
|
||||
except ValueError as e:
|
||||
raise MarketError(str(e)) from e
|
||||
|
||||
|
||||
async def soft_delete_market(sess: AsyncSession, post_slug: str, market_slug: str) -> bool:
|
||||
post = await services.blog.get_post_by_slug(sess, post_slug)
|
||||
if not post:
|
||||
return False
|
||||
|
||||
return await services.market.soft_delete_marketplace(sess, "page", post.id, market_slug)
|
||||
42
blog/bp/post/services/post_data.py
Normal file
42
blog/bp/post/services/post_data.py
Normal file
@@ -0,0 +1,42 @@
|
||||
from ...blog.ghost_db import DBClient # adjust import path
|
||||
from sqlalchemy import select
|
||||
from models.ghost_content import PostLike
|
||||
from quart import g
|
||||
|
||||
async def post_data(slug, session, include_drafts=False):
|
||||
client = DBClient(session)
|
||||
posts = (await client.posts_by_slug(slug, include_drafts=include_drafts))
|
||||
|
||||
if not posts:
|
||||
# 404 page (you can make a template for this if you want)
|
||||
return None
|
||||
post, original_post = posts[0]
|
||||
|
||||
# Check if current user has liked this post
|
||||
is_liked = False
|
||||
if g.user:
|
||||
liked_record = await session.scalar(
|
||||
select(PostLike).where(
|
||||
PostLike.user_id == g.user.id,
|
||||
PostLike.post_id == post["id"],
|
||||
PostLike.deleted_at.is_(None),
|
||||
)
|
||||
)
|
||||
is_liked = liked_record is not None
|
||||
|
||||
# Add is_liked to post dict
|
||||
post["is_liked"] = is_liked
|
||||
|
||||
tags=await client.list_tags(
|
||||
limit=50000
|
||||
) # <-- new
|
||||
authors=await client.list_authors(
|
||||
limit=50000
|
||||
)
|
||||
|
||||
return {
|
||||
"post": post,
|
||||
"original_post": original_post,
|
||||
"tags": tags,
|
||||
"authors": authors,
|
||||
}
|
||||
58
blog/bp/post/services/post_operations.py
Normal file
58
blog/bp/post/services/post_operations.py
Normal file
@@ -0,0 +1,58 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select, func, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from models.ghost_content import Post, PostLike
|
||||
|
||||
|
||||
async def toggle_post_like(
|
||||
session: AsyncSession,
|
||||
user_id: int,
|
||||
post_id: int,
|
||||
) -> tuple[bool, Optional[str]]:
|
||||
"""
|
||||
Toggle a post like for a given user using soft deletes.
|
||||
Returns (liked_state, error_message).
|
||||
- If error_message is not None, an error occurred.
|
||||
- liked_state indicates whether post is now liked (True) or unliked (False).
|
||||
"""
|
||||
|
||||
# Verify post exists
|
||||
post_exists = await session.scalar(
|
||||
select(Post.id).where(Post.id == post_id, Post.deleted_at.is_(None))
|
||||
)
|
||||
if not post_exists:
|
||||
return False, "Post not found"
|
||||
|
||||
# Check if like exists (not deleted)
|
||||
existing = await session.scalar(
|
||||
select(PostLike).where(
|
||||
PostLike.user_id == user_id,
|
||||
PostLike.post_id == post_id,
|
||||
PostLike.deleted_at.is_(None),
|
||||
)
|
||||
)
|
||||
|
||||
if existing:
|
||||
# Unlike: soft delete the like
|
||||
await session.execute(
|
||||
update(PostLike)
|
||||
.where(
|
||||
PostLike.user_id == user_id,
|
||||
PostLike.post_id == post_id,
|
||||
PostLike.deleted_at.is_(None),
|
||||
)
|
||||
.values(deleted_at=func.now())
|
||||
)
|
||||
return False, None
|
||||
else:
|
||||
# Like: add a new like
|
||||
new_like = PostLike(
|
||||
user_id=user_id,
|
||||
post_id=post_id,
|
||||
)
|
||||
session.add(new_like)
|
||||
return True, None
|
||||
Reference in New Issue
Block a user