Fix consulting order processing and display
- Fix consulting history to show continuous time range (09:00 - 11:00) instead of listing individual slots - Add foreign key relationships for consulting_slots (order_id and user_id) - Fix handle-order-paid to query profiles(email, name) instead of full_name - Add completed consulting sessions with recordings to Member Access page - Add user_id foreign key constraint to consulting_slots table - Add orders foreign key constraint for consulting_slots relationship 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
38
fix-existing-consulting-orders.sql
Normal file
38
fix-existing-consulting-orders.sql
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
-- SQL Script to manually fix existing paid consulting orders
|
||||||
|
-- This updates consulting_slots status and can be run in Supabase SQL Editor
|
||||||
|
|
||||||
|
-- Step 1: Check how many consulting orders are affected
|
||||||
|
SELECT
|
||||||
|
o.id as order_id,
|
||||||
|
o.payment_status,
|
||||||
|
COUNT(cs.id) as slot_count,
|
||||||
|
SUM(CASE WHEN cs.status = 'pending_payment' THEN 1 ELSE 0 END) as pending_slots
|
||||||
|
FROM orders o
|
||||||
|
INNER JOIN consulting_slots cs ON cs.order_id = o.id
|
||||||
|
WHERE o.payment_status = 'paid'
|
||||||
|
GROUP BY o.id, o.payment_status
|
||||||
|
HAVING SUM(CASE WHEN cs.status = 'pending_payment' THEN 1 ELSE 0 END) > 0;
|
||||||
|
|
||||||
|
-- Step 2: Update all pending_payment slots for paid orders to 'confirmed'
|
||||||
|
UPDATE consulting_slots
|
||||||
|
SET status = 'confirmed'
|
||||||
|
WHERE order_id IN (
|
||||||
|
SELECT o.id
|
||||||
|
FROM orders o
|
||||||
|
WHERE o.payment_status = 'paid'
|
||||||
|
)
|
||||||
|
AND status = 'pending_payment';
|
||||||
|
|
||||||
|
-- Step 3: Verify the update
|
||||||
|
SELECT
|
||||||
|
o.id as order_id,
|
||||||
|
o.payment_status,
|
||||||
|
cs.status as slot_status,
|
||||||
|
cs.date,
|
||||||
|
cs.start_time,
|
||||||
|
cs.end_time,
|
||||||
|
cs.meet_link
|
||||||
|
FROM orders o
|
||||||
|
INNER JOIN consulting_slots cs ON cs.order_id = o.id
|
||||||
|
WHERE o.payment_status = 'paid'
|
||||||
|
ORDER BY o.created_at DESC;
|
||||||
50
fix-trigger-settings.sql
Normal file
50
fix-trigger-settings.sql
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
-- Fixed version of handle_paid_order with hardcoded URL
|
||||||
|
-- Run this in Supabase SQL Editor
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION handle_paid_order()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
DECLARE
|
||||||
|
edge_function_url TEXT;
|
||||||
|
order_data JSON;
|
||||||
|
BEGIN
|
||||||
|
-- Only proceed if payment_status changed to 'paid'
|
||||||
|
IF (NEW.payment_status != 'paid' OR OLD.payment_status = 'paid') THEN
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
-- Log the payment event
|
||||||
|
RAISE NOTICE 'Order % payment status changed to paid', NEW.id;
|
||||||
|
|
||||||
|
-- Hardcoded edge function URL
|
||||||
|
edge_function_url := 'https://lovable.backoffice.biz.id/functions/v1/handle-order-paid';
|
||||||
|
|
||||||
|
-- Prepare order data
|
||||||
|
order_data := json_build_object(
|
||||||
|
'order_id', NEW.id,
|
||||||
|
'user_id', NEW.user_id,
|
||||||
|
'total_amount', NEW.total_amount,
|
||||||
|
'payment_method', NEW.payment_method,
|
||||||
|
'payment_provider', NEW.payment_provider
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Call the edge function asynchronously via pg_net
|
||||||
|
PERFORM net.http_post(
|
||||||
|
url := edge_function_url,
|
||||||
|
headers := json_build_object(
|
||||||
|
'Content-Type', 'application/json',
|
||||||
|
'Authorization', 'Bearer ' || current_setting('app.service_role_key', true)
|
||||||
|
),
|
||||||
|
body := order_data,
|
||||||
|
timeout_milliseconds := 10000
|
||||||
|
);
|
||||||
|
|
||||||
|
RAISE NOTICE 'Called handle-order-paid for order %', NEW.id;
|
||||||
|
|
||||||
|
RETURN NEW;
|
||||||
|
EXCEPTION
|
||||||
|
WHEN OTHERS THEN
|
||||||
|
-- Log error but don't fail the transaction
|
||||||
|
RAISE WARNING 'Failed to call handle-order-paid for order %: %', NEW.id, SQLERRM;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
@@ -20,20 +20,26 @@ interface ConsultingSlot {
|
|||||||
order_id: string | null;
|
order_id: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface GroupedOrder {
|
||||||
|
orderId: string | null;
|
||||||
|
slots: ConsultingSlot[];
|
||||||
|
firstDate: string;
|
||||||
|
meetLink: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
interface ConsultingHistoryProps {
|
interface ConsultingHistoryProps {
|
||||||
userId: string;
|
userId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ConsultingHistory({ userId }: ConsultingHistoryProps) {
|
export function ConsultingHistory({ userId }: ConsultingHistoryProps) {
|
||||||
const [slots, setSlots] = useState<ConsultingSlot[]>([]);
|
const [slots, setSlots] = useState<ConsultingSlot[]>([]);
|
||||||
const [reviewedSlotIds, setReviewedSlotIds] = useState<Set<string>>(new Set());
|
const [reviewedOrderIds, setReviewedOrderIds] = useState<Set<string>>(new Set());
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [reviewModal, setReviewModal] = useState<{
|
const [reviewModal, setReviewModal] = useState<{
|
||||||
open: boolean;
|
open: boolean;
|
||||||
slotId: string;
|
|
||||||
orderId: string | null;
|
orderId: string | null;
|
||||||
label: string;
|
label: string;
|
||||||
}>({ open: false, slotId: '', orderId: null, label: '' });
|
}>({ open: false, orderId: null, label: '' });
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchData();
|
fetchData();
|
||||||
@@ -50,9 +56,7 @@ export function ConsultingHistory({ userId }: ConsultingHistoryProps) {
|
|||||||
if (slotsData) {
|
if (slotsData) {
|
||||||
setSlots(slotsData);
|
setSlots(slotsData);
|
||||||
|
|
||||||
// Check which slots have been reviewed
|
// Check which orders have been reviewed
|
||||||
// We use a combination approach: check for consulting reviews by this user
|
|
||||||
// For consulting, we'll track by order_id since that's how we link them
|
|
||||||
const orderIds = slotsData
|
const orderIds = slotsData
|
||||||
.filter(s => s.order_id)
|
.filter(s => s.order_id)
|
||||||
.map(s => s.order_id as string);
|
.map(s => s.order_id as string);
|
||||||
@@ -66,14 +70,7 @@ export function ConsultingHistory({ userId }: ConsultingHistoryProps) {
|
|||||||
.in('order_id', orderIds);
|
.in('order_id', orderIds);
|
||||||
|
|
||||||
if (reviewsData) {
|
if (reviewsData) {
|
||||||
const reviewedOrderIds = new Set(reviewsData.map(r => r.order_id));
|
setReviewedOrderIds(new Set(reviewsData.map(r => r.order_id)));
|
||||||
// Map order_id back to slot_id
|
|
||||||
const reviewedIds = new Set(
|
|
||||||
slotsData
|
|
||||||
.filter(s => s.order_id && reviewedOrderIds.has(s.order_id))
|
|
||||||
.map(s => s.id)
|
|
||||||
);
|
|
||||||
setReviewedSlotIds(reviewedIds);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -81,6 +78,26 @@ export function ConsultingHistory({ userId }: ConsultingHistoryProps) {
|
|||||||
setLoading(false);
|
setLoading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Group slots by order_id
|
||||||
|
const groupedOrders: GroupedOrder[] = (() => {
|
||||||
|
const groups = new Map<string | null, ConsultingSlot[]>();
|
||||||
|
|
||||||
|
slots.forEach(slot => {
|
||||||
|
const orderId = slot.order_id || 'no-order';
|
||||||
|
if (!groups.has(orderId)) {
|
||||||
|
groups.set(orderId, []);
|
||||||
|
}
|
||||||
|
groups.get(orderId)!.push(slot);
|
||||||
|
});
|
||||||
|
|
||||||
|
return Array.from(groups.entries()).map(([orderId, slots]) => ({
|
||||||
|
orderId: orderId === 'no-order' ? null : orderId,
|
||||||
|
slots,
|
||||||
|
firstDate: slots[0].date,
|
||||||
|
meetLink: slots[0].meet_link, // Use meet_link from first slot
|
||||||
|
})).sort((a, b) => new Date(b.firstDate).getTime() - new Date(a.firstDate).getTime());
|
||||||
|
})();
|
||||||
|
|
||||||
const getStatusBadge = (status: string) => {
|
const getStatusBadge = (status: string) => {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case 'done':
|
case 'done':
|
||||||
@@ -96,24 +113,27 @@ export function ConsultingHistory({ userId }: ConsultingHistoryProps) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const openReviewModal = (slot: ConsultingSlot) => {
|
const openReviewModal = (order: GroupedOrder) => {
|
||||||
const dateLabel = format(new Date(slot.date), 'd MMMM yyyy', { locale: id });
|
const firstSlot = order.slots[0];
|
||||||
const timeLabel = `${slot.start_time.substring(0, 5)} - ${slot.end_time.substring(0, 5)}`;
|
const lastSlot = order.slots[order.slots.length - 1];
|
||||||
|
const dateLabel = format(new Date(firstSlot.date), 'd MMMM yyyy', { locale: id });
|
||||||
|
const timeLabel = `${firstSlot.start_time.substring(0, 5)} - ${lastSlot.end_time.substring(0, 5)}`;
|
||||||
setReviewModal({
|
setReviewModal({
|
||||||
open: true,
|
open: true,
|
||||||
slotId: slot.id,
|
orderId: order.orderId,
|
||||||
orderId: slot.order_id,
|
|
||||||
label: `Sesi konsultasi ${dateLabel}, ${timeLabel}`,
|
label: `Sesi konsultasi ${dateLabel}, ${timeLabel}`,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleReviewSuccess = () => {
|
const handleReviewSuccess = () => {
|
||||||
// Mark this slot as reviewed
|
// Mark this order as reviewed
|
||||||
setReviewedSlotIds(prev => new Set([...prev, reviewModal.slotId]));
|
if (reviewModal.orderId) {
|
||||||
|
setReviewedOrderIds(prev => new Set([...prev, reviewModal.orderId!]));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const doneSlots = slots.filter(s => s.status === 'done');
|
const doneOrders = groupedOrders.filter(o => o.slots.every(s => s.status === 'done'));
|
||||||
const upcomingSlots = slots.filter(s => s.status === 'confirmed');
|
const upcomingOrders = groupedOrders.filter(o => o.slots.some(s => s.status === 'confirmed'));
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
@@ -147,62 +167,68 @@ export function ConsultingHistory({ userId }: ConsultingHistoryProps) {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
{/* Upcoming sessions */}
|
{/* Upcoming sessions */}
|
||||||
{upcomingSlots.length > 0 && (
|
{upcomingOrders.length > 0 && (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<h4 className="text-sm font-medium text-muted-foreground">Sesi Mendatang</h4>
|
<h4 className="text-sm font-medium text-muted-foreground">Sesi Mendatang</h4>
|
||||||
{upcomingSlots.map((slot) => (
|
{upcomingOrders.map((order) => {
|
||||||
<div key={slot.id} className="flex items-center justify-between p-3 border-2 border-border bg-muted/30">
|
const firstSlot = order.slots[0];
|
||||||
<div className="flex items-center gap-3">
|
const lastSlot = order.slots[order.slots.length - 1];
|
||||||
<Calendar className="w-4 h-4 text-muted-foreground" />
|
|
||||||
<div>
|
|
||||||
<p className="font-medium">
|
|
||||||
{format(new Date(slot.date), 'd MMM yyyy', { locale: id })}
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-muted-foreground flex items-center gap-1">
|
|
||||||
<Clock className="w-3 h-3" />
|
|
||||||
{slot.start_time.substring(0, 5)} - {slot.end_time.substring(0, 5)}
|
|
||||||
{slot.topic_category && ` • ${slot.topic_category}`}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{getStatusBadge(slot.status)}
|
|
||||||
{slot.meet_link && (
|
|
||||||
<Button asChild size="sm" variant="outline" className="border-2">
|
|
||||||
<a href={slot.meet_link} target="_blank" rel="noopener noreferrer">
|
|
||||||
Join
|
|
||||||
</a>
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Completed sessions */}
|
|
||||||
{doneSlots.length > 0 && (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<h4 className="text-sm font-medium text-muted-foreground">Sesi Selesai</h4>
|
|
||||||
{doneSlots.map((slot) => {
|
|
||||||
const hasReviewed = reviewedSlotIds.has(slot.id);
|
|
||||||
return (
|
return (
|
||||||
<div key={slot.id} className="flex items-center justify-between p-3 border-2 border-border">
|
<div key={order.orderId || 'no-order'} className="flex items-center justify-between p-3 border-2 border-border bg-muted/30">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Calendar className="w-4 h-4 text-muted-foreground" />
|
<Calendar className="w-4 h-4 text-muted-foreground" />
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium">
|
<p className="font-medium">
|
||||||
{format(new Date(slot.date), 'd MMM yyyy', { locale: id })}
|
{format(new Date(firstSlot.date), 'd MMM yyyy', { locale: id })}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-sm text-muted-foreground flex items-center gap-1">
|
<p className="text-sm text-muted-foreground flex items-center gap-1">
|
||||||
<Clock className="w-3 h-3" />
|
<Clock className="w-3 h-3" />
|
||||||
{slot.start_time.substring(0, 5)} - {slot.end_time.substring(0, 5)}
|
{firstSlot.start_time.substring(0, 5)} - {lastSlot.end_time.substring(0, 5)}
|
||||||
{slot.topic_category && ` • ${slot.topic_category}`}
|
{firstSlot.topic_category && ` • ${firstSlot.topic_category}`}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{getStatusBadge(slot.status)}
|
{getStatusBadge(firstSlot.status)}
|
||||||
|
{order.meetLink && (
|
||||||
|
<Button asChild size="sm" variant="outline" className="border-2">
|
||||||
|
<a href={order.meetLink} target="_blank" rel="noopener noreferrer">
|
||||||
|
Join
|
||||||
|
</a>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Completed sessions */}
|
||||||
|
{doneOrders.length > 0 && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h4 className="text-sm font-medium text-muted-foreground">Sesi Selesai</h4>
|
||||||
|
{doneOrders.map((order) => {
|
||||||
|
const firstSlot = order.slots[0];
|
||||||
|
const lastSlot = order.slots[order.slots.length - 1];
|
||||||
|
const hasReviewed = order.orderId ? reviewedOrderIds.has(order.orderId) : false;
|
||||||
|
return (
|
||||||
|
<div key={order.orderId || 'no-order'} className="flex items-center justify-between p-3 border-2 border-border">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Calendar className="w-4 h-4 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="font-medium">
|
||||||
|
{format(new Date(firstSlot.date), 'd MMM yyyy', { locale: id })}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-muted-foreground flex items-center gap-1">
|
||||||
|
<Clock className="w-3 h-3" />
|
||||||
|
{firstSlot.start_time.substring(0, 5)} - {lastSlot.end_time.substring(0, 5)}
|
||||||
|
{firstSlot.topic_category && ` • ${firstSlot.topic_category}`}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{getStatusBadge(firstSlot.status)}
|
||||||
{hasReviewed ? (
|
{hasReviewed ? (
|
||||||
<span className="flex items-center gap-1 text-xs text-muted-foreground">
|
<span className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||||
<CheckCircle className="w-4 h-4 text-accent" />
|
<CheckCircle className="w-4 h-4 text-accent" />
|
||||||
@@ -212,7 +238,7 @@ export function ConsultingHistory({ userId }: ConsultingHistoryProps) {
|
|||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={() => openReviewModal(slot)}
|
onClick={() => openReviewModal(order)}
|
||||||
className="border-2"
|
className="border-2"
|
||||||
>
|
>
|
||||||
<Star className="w-4 h-4 mr-1" />
|
<Star className="w-4 h-4 mr-1" />
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
|||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { Video, Calendar, BookOpen, ArrowRight, Search, X } from 'lucide-react';
|
import { Video, Calendar, BookOpen, ArrowRight, Search, X, Clock } from 'lucide-react';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { format } from 'date-fns';
|
||||||
|
import { id } from 'date-fns/locale';
|
||||||
|
|
||||||
interface UserAccess {
|
interface UserAccess {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -25,10 +27,21 @@ interface UserAccess {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ConsultingSession {
|
||||||
|
id: string;
|
||||||
|
date: string;
|
||||||
|
start_time: string;
|
||||||
|
end_time: string;
|
||||||
|
status: string;
|
||||||
|
recording_url: string | null;
|
||||||
|
topic_category: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export default function MemberAccess() {
|
export default function MemberAccess() {
|
||||||
const { user, loading: authLoading } = useAuth();
|
const { user, loading: authLoading } = useAuth();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [access, setAccess] = useState<UserAccess[]>([]);
|
const [access, setAccess] = useState<UserAccess[]>([]);
|
||||||
|
const [consultingSessions, setConsultingSessions] = useState<ConsultingSession[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
const [selectedType, setSelectedType] = useState<string>('all');
|
const [selectedType, setSelectedType] = useState<string>('all');
|
||||||
@@ -39,7 +52,7 @@ export default function MemberAccess() {
|
|||||||
}, [user, authLoading]);
|
}, [user, authLoading]);
|
||||||
|
|
||||||
const fetchAccess = async () => {
|
const fetchAccess = async () => {
|
||||||
const [accessRes, paidOrdersRes] = await Promise.all([
|
const [accessRes, paidOrdersRes, consultingRes] = await Promise.all([
|
||||||
// Get direct user_access
|
// Get direct user_access
|
||||||
supabase
|
supabase
|
||||||
.from('user_access')
|
.from('user_access')
|
||||||
@@ -57,6 +70,13 @@ export default function MemberAccess() {
|
|||||||
)
|
)
|
||||||
.eq("user_id", user!.id)
|
.eq("user_id", user!.id)
|
||||||
.eq("payment_status", "paid"),
|
.eq("payment_status", "paid"),
|
||||||
|
// Get completed consulting sessions with recordings
|
||||||
|
supabase
|
||||||
|
.from('consulting_slots')
|
||||||
|
.select('id, date, start_time, end_time, status, recording_url, topic_category')
|
||||||
|
.eq('user_id', user!.id)
|
||||||
|
.eq('status', 'done')
|
||||||
|
.order('date', { ascending: false }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Combine access from user_access and paid orders
|
// Combine access from user_access and paid orders
|
||||||
@@ -81,6 +101,7 @@ export default function MemberAccess() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setAccess([...directAccess, ...paidProductAccess]);
|
setAccess([...directAccess, ...paidProductAccess]);
|
||||||
|
setConsultingSessions(consultingRes.data || []);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -249,7 +270,60 @@ export default function MemberAccess() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{access.length === 0 ? (
|
{/* Consulting Sessions with Recordings */}
|
||||||
|
{consultingSessions.length > 0 && (
|
||||||
|
<div className="mb-8">
|
||||||
|
<h2 className="text-2xl font-bold mb-4 flex items-center gap-2">
|
||||||
|
<Video className="w-6 h-6" />
|
||||||
|
Sesi Konsultasi Selesai
|
||||||
|
</h2>
|
||||||
|
<div className="grid gap-4">
|
||||||
|
{consultingSessions.map((session) => (
|
||||||
|
<Card key={session.id} className="border-2 border-border">
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-xl">
|
||||||
|
1-on-1: {session.topic_category || 'Konsultasi'}
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>Konsultasi</CardDescription>
|
||||||
|
</div>
|
||||||
|
<Badge className="bg-brand-accent text-white rounded-full">Selesai</Badge>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="flex items-center gap-2 text-sm text-muted-foreground mb-4">
|
||||||
|
<Calendar className="w-4 h-4" />
|
||||||
|
<span>{format(new Date(session.date), 'd MMMM yyyy', { locale: id })}</span>
|
||||||
|
<Clock className="w-4 h-4 ml-2" />
|
||||||
|
<span>{session.start_time.substring(0, 5)} - {session.end_time.substring(0, 5)}</span>
|
||||||
|
</div>
|
||||||
|
{session.recording_url ? (
|
||||||
|
<Button asChild className="shadow-sm">
|
||||||
|
<a href={session.recording_url} target="_blank" rel="noopener noreferrer">
|
||||||
|
<Video className="w-4 h-4 mr-2" />
|
||||||
|
Tonton Rekaman
|
||||||
|
<ArrowRight className="w-4 h-4 ml-2" />
|
||||||
|
</a>
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Badge className="bg-muted text-primary">Rekaman segera tersedia</Badge>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Products Section */}
|
||||||
|
{access.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<h2 className="text-2xl font-bold mb-4">Produk & Kursus</h2>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{access.length === 0 && consultingSessions.length === 0 ? (
|
||||||
<Card className="border-2 border-border">
|
<Card className="border-2 border-border">
|
||||||
<CardContent className="py-12 text-center">
|
<CardContent className="py-12 text-center">
|
||||||
<p className="text-muted-foreground mb-4">Anda belum memiliki akses ke produk apapun</p>
|
<p className="text-muted-foreground mb-4">Anda belum memiliki akses ke produk apapun</p>
|
||||||
@@ -258,7 +332,7 @@ export default function MemberAccess() {
|
|||||||
</Button>
|
</Button>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
) : (
|
) : access.length === 0 ? null : (
|
||||||
<div className="grid gap-4">
|
<div className="grid gap-4">
|
||||||
{filteredAccess.length === 0 && access.length > 0 && (
|
{filteredAccess.length === 0 && access.length > 0 && (
|
||||||
<div className="text-center py-16">
|
<div className="text-center py-16">
|
||||||
|
|||||||
@@ -24,17 +24,19 @@ serve(async (req: Request): Promise<Response> => {
|
|||||||
const { order_id } = body;
|
const { order_id } = body;
|
||||||
|
|
||||||
console.log("[HANDLE-PAID] Processing paid order:", order_id);
|
console.log("[HANDLE-PAID] Processing paid order:", order_id);
|
||||||
|
console.log("[HANDLE-PAID] Request body:", JSON.stringify(body));
|
||||||
|
|
||||||
const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
|
const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
|
||||||
const supabaseServiceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
|
const supabaseServiceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
|
||||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||||
|
|
||||||
// Get full order details with items AND consulting slots
|
// Get full order details with items AND consulting slots
|
||||||
|
// Use maybeSingle() in case there are no related records
|
||||||
const { data: order, error: orderError } = await supabase
|
const { data: order, error: orderError } = await supabase
|
||||||
.from("orders")
|
.from("orders")
|
||||||
.select(`
|
.select(`
|
||||||
*,
|
*,
|
||||||
profiles(email, full_name),
|
profiles(email, name),
|
||||||
order_items (
|
order_items (
|
||||||
product_id,
|
product_id,
|
||||||
product:products (title, type)
|
product:products (title, type)
|
||||||
@@ -48,12 +50,20 @@ serve(async (req: Request): Promise<Response> => {
|
|||||||
)
|
)
|
||||||
`)
|
`)
|
||||||
.eq("id", order_id)
|
.eq("id", order_id)
|
||||||
.single();
|
.maybeSingle();
|
||||||
|
|
||||||
if (orderError || !order) {
|
if (orderError) {
|
||||||
console.error("[HANDLE-PAID] Order not found:", order_id, orderError);
|
console.error("[HANDLE-PAID] Database error:", orderError);
|
||||||
return new Response(
|
return new Response(
|
||||||
JSON.stringify({ success: false, error: "Order not found" }),
|
JSON.stringify({ success: false, error: "Database error", details: orderError.message }),
|
||||||
|
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!order) {
|
||||||
|
console.error("[HANDLE-PAID] Order not found:", order_id);
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ success: false, error: "Order not found", order_id }),
|
||||||
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -67,7 +77,7 @@ serve(async (req: Request): Promise<Response> => {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
const userEmail = order.profiles?.email || "";
|
const userEmail = order.profiles?.email || "";
|
||||||
const userName = order.profiles?.full_name || "Pelanggan";
|
const userName = order.profiles?.name || userEmail.split('@')[0] || "Pelanggan";
|
||||||
const orderItems = order.order_items as Array<{
|
const orderItems = order.order_items as Array<{
|
||||||
product_id: string;
|
product_id: string;
|
||||||
product: { title: string; type: string };
|
product: { title: string; type: string };
|
||||||
@@ -140,12 +150,13 @@ serve(async (req: Request): Promise<Response> => {
|
|||||||
// Don't fail the entire process
|
// Don't fail the entire process
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Send consulting notification with the consultingSlots data
|
// Send consulting notification with the consultingSlots data
|
||||||
await sendNotification(supabase, "consulting_scheduled", {
|
await sendNotification(supabase, "consulting_scheduled", {
|
||||||
nama: userName,
|
nama: userName,
|
||||||
email: userEmail,
|
email: userEmail,
|
||||||
order_id: order_id.substring(0, 8),
|
order_id_short: order_id.substring(0, 8),
|
||||||
tanggal_pesanan: new Date().toLocaleDateString("id-ID"),
|
tanggal_pesanan: new Date().toLocaleDateString("id-ID"),
|
||||||
total: `Rp ${order.total_amount.toLocaleString("id-ID")}`,
|
total: `Rp ${order.total_amount.toLocaleString("id-ID")}`,
|
||||||
metode_pembayaran: order.payment_method || "Unknown",
|
metode_pembayaran: order.payment_method || "Unknown",
|
||||||
@@ -188,7 +199,7 @@ serve(async (req: Request): Promise<Response> => {
|
|||||||
await sendNotification(supabase, "payment_success", {
|
await sendNotification(supabase, "payment_success", {
|
||||||
nama: userName,
|
nama: userName,
|
||||||
email: userEmail,
|
email: userEmail,
|
||||||
order_id: order_id.substring(0, 8),
|
order_id_short: order_id.substring(0, 8),
|
||||||
tanggal_pesanan: new Date().toLocaleDateString("id-ID"),
|
tanggal_pesanan: new Date().toLocaleDateString("id-ID"),
|
||||||
total: `Rp ${order.total_amount.toLocaleString("id-ID")}`,
|
total: `Rp ${order.total_amount.toLocaleString("id-ID")}`,
|
||||||
metode_pembayaran: order.payment_method || "Unknown",
|
metode_pembayaran: order.payment_method || "Unknown",
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ serve(async (req) => {
|
|||||||
// Find the order by payment_reference or id
|
// Find the order by payment_reference or id
|
||||||
const { data: order, error: orderError } = await supabase
|
const { data: order, error: orderError } = await supabase
|
||||||
.from("orders")
|
.from("orders")
|
||||||
.select("id, payment_status")
|
.select("id, payment_status, user_id, total_amount")
|
||||||
.or(`payment_reference.eq.${payload.order_id},id.eq.${payload.order_id}`)
|
.or(`payment_reference.eq.${payload.order_id},id.eq.${payload.order_id}`)
|
||||||
.single();
|
.single();
|
||||||
|
|
||||||
|
|||||||
16
supabase/migrations/20251226_configure_trigger_settings.sql
Normal file
16
supabase/migrations/20251226_configure_trigger_settings.sql
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
-- Configure database settings for handle-order-paid trigger
|
||||||
|
-- These settings are required for the payment trigger to work
|
||||||
|
|
||||||
|
-- Set base URL (change if different)
|
||||||
|
DELETE FROM pg_settings WHERE name = 'app.base_url';
|
||||||
|
ALTER DATABASE postgres SET "app.base_url" = 'https://lovable.backoffice.biz.id';
|
||||||
|
|
||||||
|
-- Set service role key (you need to replace this with your actual service role key)
|
||||||
|
-- Get it from: Supabase Dashboard > Project Settings > API > service_role (confidential)
|
||||||
|
-- Uncomment and set the actual key:
|
||||||
|
-- ALTER DATABASE postgres SET "app.service_role_key" = 'YOUR_SERVICE_ROLE_KEY_HERE';
|
||||||
|
|
||||||
|
-- Verify settings
|
||||||
|
SELECT
|
||||||
|
current_setting('app.base_url', true) as base_url,
|
||||||
|
current_setting('app.service_role_key', true) as service_role_key;
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
-- Add foreign key relationship between consulting_slots and profiles (user_id)
|
||||||
|
-- This enables the relationship query in ConsultingHistory component
|
||||||
|
|
||||||
|
-- First, check if the foreign key already exists
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.table_constraints
|
||||||
|
WHERE table_name = 'consulting_slots'
|
||||||
|
AND constraint_name = 'consulting_slots_user_id_fkey'
|
||||||
|
) THEN
|
||||||
|
-- Add foreign key constraint if it doesn't exist
|
||||||
|
ALTER TABLE consulting_slots
|
||||||
|
ADD CONSTRAINT consulting_slots_user_id_fkey
|
||||||
|
FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE;
|
||||||
|
|
||||||
|
RAISE NOTICE 'Foreign key constraint added for user_id';
|
||||||
|
ELSE
|
||||||
|
RAISE NOTICE 'Foreign key constraint for user_id already exists';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Verify the relationship
|
||||||
|
SELECT
|
||||||
|
tc.table_name,
|
||||||
|
kcu.column_name,
|
||||||
|
ccu.table_name AS foreign_table_name,
|
||||||
|
ccu.column_name AS foreign_column_name
|
||||||
|
FROM information_schema.table_constraints AS tc
|
||||||
|
JOIN information_schema.key_column_usage AS kcu
|
||||||
|
ON tc.constraint_name = kcu.constraint_name
|
||||||
|
AND tc.table_schema = kcu.table_schema
|
||||||
|
JOIN information_schema.constraint_column_usage AS ccu
|
||||||
|
ON ccu.constraint_name = tc.constraint_name
|
||||||
|
WHERE tc.constraint_type = 'FOREIGN KEY'
|
||||||
|
AND tc.table_name = 'consulting_slots'
|
||||||
|
AND kcu.column_name = 'user_id';
|
||||||
36
supabase/migrations/20251227_add_orders_foreign_key.sql
Normal file
36
supabase/migrations/20251227_add_orders_foreign_key.sql
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
-- Add foreign key relationship between consulting_slots and orders
|
||||||
|
-- This enables the relationship query in handle-order-paid edge function
|
||||||
|
|
||||||
|
-- First, check if the column exists
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.table_constraints
|
||||||
|
WHERE table_name = 'consulting_slots'
|
||||||
|
AND constraint_name = 'consulting_slots_order_id_fkey'
|
||||||
|
) THEN
|
||||||
|
-- Add foreign key constraint if it doesn't exist
|
||||||
|
ALTER TABLE consulting_slots
|
||||||
|
ADD CONSTRAINT consulting_slots_order_id_fkey
|
||||||
|
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE;
|
||||||
|
|
||||||
|
RAISE NOTICE 'Foreign key constraint added successfully';
|
||||||
|
ELSE
|
||||||
|
RAISE NOTICE 'Foreign key constraint already exists';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Verify the relationship
|
||||||
|
SELECT
|
||||||
|
tc.table_name,
|
||||||
|
kcu.column_name,
|
||||||
|
ccu.table_name AS foreign_table_name,
|
||||||
|
ccu.column_name AS foreign_column_name
|
||||||
|
FROM information_schema.table_constraints AS tc
|
||||||
|
JOIN information_schema.key_column_usage AS kcu
|
||||||
|
ON tc.constraint_name = kcu.constraint_name
|
||||||
|
AND tc.table_schema = kcu.table_schema
|
||||||
|
JOIN information_schema.constraint_column_usage AS ccu
|
||||||
|
ON ccu.constraint_name = tc.constraint_name
|
||||||
|
WHERE tc.constraint_type = 'FOREIGN KEY'
|
||||||
|
AND tc.table_name = 'consulting_slots';
|
||||||
37
test-manual-trigger.js
Normal file
37
test-manual-trigger.js
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
// Test script to manually trigger handle-order-paid for existing consulting orders
|
||||||
|
// Run with: node test-manual-trigger.js <order_id>
|
||||||
|
|
||||||
|
const orderId = process.argv[2];
|
||||||
|
|
||||||
|
if (!orderId) {
|
||||||
|
console.error('Usage: node test-manual-trigger.js <order_id>');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const SUPABASE_URL = process.env.SUPABASE_URL || 'https://lovable.backoffice.biz.id';
|
||||||
|
const SUPABASE_ANON_KEY = process.env.SUPABASE_ANON_KEY || 'your-anon-key';
|
||||||
|
|
||||||
|
async function triggerManual() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${SUPABASE_URL}/functions/v1/handle-order-paid`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${SUPABASE_ANON_KEY}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
order_id: orderId,
|
||||||
|
user_id: 'test',
|
||||||
|
total_amount: 0,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
console.log('Response:', result);
|
||||||
|
console.log('Status:', response.status);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
triggerManual();
|
||||||
Reference in New Issue
Block a user