mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 01:48:08 +09:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec703d4ca7 |
No files matched your search
@@ -10,7 +10,7 @@ Handles:
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
|
||||
from backend.api.dependencies import require_auth, require_admin
|
||||
from backend.models.referral import (
|
||||
@@ -165,6 +165,51 @@ async def list_links(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/admin/apply-discount")
|
||||
async def admin_apply_discount(
|
||||
request: Request,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
"""Admin: apply a referral discount to any user, even without a referral link."""
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
body = await request.json()
|
||||
user_email = body.get("email", "").lower()
|
||||
discount_percent = body.get("discount_percent", 10)
|
||||
duration_days = body.get("duration_days", 30)
|
||||
referral_code = body.get("referral_code", "admin-grant")
|
||||
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=400, detail="Email is required")
|
||||
|
||||
user_service = get_user_service()
|
||||
user = user_service.get_user(user_email)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
now = datetime.utcnow()
|
||||
|
||||
user_service.update_user(
|
||||
user_email,
|
||||
referred_by_code=referral_code,
|
||||
referred_at=now,
|
||||
referral_discount_expires_at=now + timedelta(days=duration_days),
|
||||
)
|
||||
|
||||
# Create/ensure the Stripe coupon exists for this discount percent
|
||||
service = get_referral_service()
|
||||
service.get_or_create_stripe_coupon(discount_percent)
|
||||
|
||||
logger.info(f"Admin applied {discount_percent}% discount for {duration_days} days to {user_email}")
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"message": f"Applied {discount_percent}% discount for {duration_days} days",
|
||||
"discount_expires_at": (now + timedelta(days=duration_days)).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.put("/admin/links/{code}")
|
||||
async def update_link(
|
||||
code: str,
|
||||
|
||||
@@ -1492,6 +1492,10 @@ class UserDetailResponse(BaseModel):
|
||||
device_fingerprint: Optional[str] = None
|
||||
welcome_credits_granted: bool = False
|
||||
has_submitted_feedback: bool = False
|
||||
# Referral fields
|
||||
referred_by_code: Optional[str] = None
|
||||
referral_discount_expires_at: Optional[str] = None
|
||||
referral_code: Optional[str] = None
|
||||
# Recent session details (IP, user agent, fingerprint)
|
||||
recent_sessions: list[dict] = []
|
||||
|
||||
@@ -1687,6 +1691,9 @@ async def get_user_detail(
|
||||
device_fingerprint=user.device_fingerprint,
|
||||
welcome_credits_granted=user.welcome_credits_granted,
|
||||
has_submitted_feedback=user.has_submitted_feedback,
|
||||
referred_by_code=user.referred_by_code,
|
||||
referral_discount_expires_at=user.referral_discount_expires_at.isoformat() if user.referral_discount_expires_at and hasattr(user.referral_discount_expires_at, 'isoformat') else str(user.referral_discount_expires_at) if user.referral_discount_expires_at else None,
|
||||
referral_code=user.referral_code,
|
||||
recent_sessions=active_sessions,
|
||||
)
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
Trash2,
|
||||
DollarSign,
|
||||
LogIn,
|
||||
Tag,
|
||||
} from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
@@ -74,6 +75,13 @@ export default function AdminUserDetailPage() {
|
||||
const [creditAmount, setCreditAmount] = useState("")
|
||||
const [creditReason, setCreditReason] = useState("")
|
||||
|
||||
// Discount dialog
|
||||
const [discountDialogOpen, setDiscountDialogOpen] = useState(false)
|
||||
const [discountPercent, setDiscountPercent] = useState("50")
|
||||
const [discountDays, setDiscountDays] = useState("365")
|
||||
const [discountCode, setDiscountCode] = useState("loyalty")
|
||||
const [applyingDiscount, setApplyingDiscount] = useState(false)
|
||||
|
||||
const loadUser = async () => {
|
||||
if (!email) {
|
||||
setLoading(false)
|
||||
@@ -148,6 +156,28 @@ export default function AdminUserDetailPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleApplyDiscount = async () => {
|
||||
setApplyingDiscount(true)
|
||||
try {
|
||||
const result = await adminApi.applyDiscount(email, {
|
||||
discount_percent: Number(discountPercent) || 50,
|
||||
duration_days: Number(discountDays) || 365,
|
||||
referral_code: discountCode || "loyalty",
|
||||
})
|
||||
toast({ title: "Discount Applied", description: result.message })
|
||||
setDiscountDialogOpen(false)
|
||||
loadUser()
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: "Failed",
|
||||
description: err instanceof Error ? err.message : "Failed to apply discount",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setApplyingDiscount(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleStatus = async () => {
|
||||
if (!user) return
|
||||
|
||||
@@ -311,6 +341,15 @@ export default function AdminUserDetailPage() {
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Add Credits
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setDiscountDialogOpen(true)}
|
||||
disabled={actionLoading}
|
||||
title="Apply a referral discount to this user"
|
||||
>
|
||||
<Tag className="w-4 h-4 mr-2" />
|
||||
Apply Discount
|
||||
</Button>
|
||||
<Button
|
||||
variant={user.is_active ? "destructive" : "outline"}
|
||||
onClick={handleToggleStatus}
|
||||
@@ -425,6 +464,16 @@ export default function AdminUserDetailPage() {
|
||||
{user.has_submitted_feedback ? "Yes" : "No"}
|
||||
</Badge>
|
||||
</div>
|
||||
{user.referral_discount_expires_at && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Tag className="w-4 h-4 text-purple-500" />
|
||||
<span>
|
||||
Referral discount active
|
||||
{user.referred_by_code && <> (code: <code className="bg-muted px-1 rounded">{user.referred_by_code}</code>)</>}
|
||||
{' · '}Expires {new Date(user.referral_discount_expires_at).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -675,6 +724,59 @@ export default function AdminUserDetailPage() {
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Apply Discount Dialog */}
|
||||
<Dialog open={discountDialogOpen} onOpenChange={setDiscountDialogOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Apply Discount</DialogTitle>
|
||||
<DialogDescription>
|
||||
Apply a referral discount to {email}. This sets the same discount fields as if they used a referral link.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Discount %</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
value={discountPercent}
|
||||
onChange={(e) => setDiscountPercent(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">Percentage off credit purchases at Stripe checkout</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Duration (days)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
value={discountDays}
|
||||
onChange={(e) => setDiscountDays(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">How long the discount stays active. Use 3650 for ~10 years.</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Referral Code</Label>
|
||||
<Input
|
||||
value={discountCode}
|
||||
onChange={(e) => setDiscountCode(e.target.value)}
|
||||
placeholder="loyalty"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">Shows as the referral source. Use "loyalty" for grandfathered pricing, or an actual referral code.</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDiscountDialogOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleApplyDiscount} disabled={applyingDiscount}>
|
||||
{applyingDiscount && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
Apply Discount
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete User Confirmation Dialog */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
|
||||
@@ -1677,6 +1677,10 @@ export interface AdminUserDetail {
|
||||
device_fingerprint?: string | null;
|
||||
welcome_credits_granted?: boolean;
|
||||
has_submitted_feedback?: boolean;
|
||||
// Referral fields
|
||||
referred_by_code?: string | null;
|
||||
referral_discount_expires_at?: string | null;
|
||||
referral_code?: string | null;
|
||||
recent_sessions?: Array<{
|
||||
ip_address?: string;
|
||||
user_agent?: string;
|
||||
@@ -1825,6 +1829,22 @@ export const adminApi = {
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
/**
|
||||
* Apply a referral discount to a user (admin only)
|
||||
*/
|
||||
async applyDiscount(email: string, data: {
|
||||
discount_percent?: number;
|
||||
duration_days?: number;
|
||||
referral_code?: string;
|
||||
}): Promise<{ ok: boolean; message: string; discount_expires_at: string }> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/referrals/admin/apply-discount`, {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, ...data }),
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
/**
|
||||
* Impersonate a user (admin only)
|
||||
* Creates a session token that allows viewing the app as the target user
|
||||
|
||||
Reference in new issue
Block a user