Files
redefined-designs/frontend/src/components/ItemCard.tsx
T
bermudalambandClaude Opus 5 f626f27e75
SonarQube Analysis / sonarqube (pull_request) Successful in 2m46s
Tests / backend-unit (pull_request) Successful in 44s
Tests / frontend-e2e (pull_request) Failing after 9m48s
feat: favorite items and notify when a favorite is sold (#34)
Customers can favorite and unfavorite items from the storefront, opt in to being told when a favorite is sold to someone else, and manage that preference from their account page.

The opt-in is a consent of its own rather than the existing marketing flag. Being told that a specific item you asked about has gone is a narrower thing than agreeing to marketing, and folding one into the other would leave marketing_consent_text no longer describing what was actually agreed to. It is recorded the same way as the marketing consent — flag, timestamp, and the exact wording shown — and accepting it does not set marketing_consent.

The prompt appears only after a customer has actually favorited something, so the reason for asking is concrete rather than an abstract marketing ask, and it says plainly that it is separate from marketing email. Declining keeps the favorite.

Notifications fire when an item reaches sold, either through checkout or an admin marking it sold, and never to the buyer — telling someone the item they just bought is unavailable reads as a bug. Reserved is deliberately not a trigger: reservations expire and get released, so a "gone" email would often be about an item still for sale. Disabled accounts are excluded, per #33.

completeCheckout now returns the sold item ids and the buyer so its three call sites can notify after COMMIT. Sending inside the transaction would email people about a sale that then rolled back, and would hold the transaction open for SMTP. Each message is sent independently so one bad address cannot stop the rest, and the sale has already succeeded regardless.

Favoriting while signed out opens the existing inline register/login modal, exactly as Add to Cart does, and completes the favorite on success.

Also fixes a latent bug in the same component: while the session was still resolving, `customer` is null for a signed-in visitor too, so clicking Add to Cart or the new heart in that window prompted them to sign in again. Both now ignore clicks until the session has resolved, and the control shows as loading meanwhile.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-18 13:29:11 -05:00

198 lines
6.8 KiB
TypeScript
Executable File

import { useState, useRef } from 'react';
import { Card, Badge, Typography, Carousel, Button, message, Tag, Modal, Tooltip } from 'antd';
import { LeftOutlined, RightOutlined, HeartOutlined, HeartFilled } from '@ant-design/icons';
import type { CarouselRef } from 'antd/es/carousel';
import { Item } from '../api';
import MarkdownView from './MarkdownView';
import { addToCart } from '../cart/cartApi';
import { useCart } from '../cart/CartContext';
import { useCustomerAuth } from '../customer/CustomerAuthContext';
import AuthPromptModal from '../customer/AuthPromptModal';
import { useFavorites } from '../customer/FavoritesContext';
import { addFavorite, removeFavorite, setFavoriteAlerts } from '../customer/favoritesApi';
const { Text, Title } = Typography;
interface Props {
item: Item;
onChanged: () => void;
}
export default function ItemCard({ item, onChanged }: Props) {
const carouselRef = useRef<CarouselRef>(null);
const [authModalOpen, setAuthModalOpen] = useState(false);
const [adding, setAdding] = useState(false);
const [favoriting, setFavoriting] = useState(false);
// Which action to run once the auth modal succeeds — the modal is shared by
// Add to Cart and the heart.
const [pendingAction, setPendingAction] = useState<'cart' | 'favorite'>('cart');
const { customer, loading: authLoading, refresh: refreshCustomer } = useCustomerAuth();
const { itemIds, refresh: refreshCart } = useCart();
const { itemIds: favoriteIds, refresh: refreshFavorites } = useFavorites();
const inMyCart = itemIds.has(item.id);
const isFavorite = favoriteIds.has(item.id);
async function doAddToCart() {
setAdding(true);
try {
await addToCart(item.id);
message.success('Added to cart');
refreshCart();
onChanged();
} catch (err) {
message.error((err as Error).message);
} finally {
setAdding(false);
}
}
function handleAddClick() {
// Until the session has resolved, `customer` is null for a signed-in
// visitor too, and prompting them to sign in again would be wrong.
if (authLoading) return;
if (!customer) {
setPendingAction('cart');
setAuthModalOpen(true);
return;
}
doAddToCart();
}
// Asked only once a customer has actually favorited something, so the reason
// for asking is concrete rather than an abstract marketing prompt. This is a
// consent of its own — accepting it does not sign anyone up for marketing.
function offerAlerts() {
Modal.confirm({
title: 'Want to know if this sells?',
content:
'Every piece is one of a kind, so a favorite can be bought by someone else at any time. ' +
'We can email you if that happens, so you are not left waiting on something that has gone. ' +
'This is only about items you favorite — it is separate from any marketing email.',
okText: 'Yes, email me',
cancelText: 'No thanks',
onOk: async () => {
try {
await setFavoriteAlerts(true);
refreshCustomer();
message.success('We will let you know');
} catch (err) {
message.error((err as Error).message);
}
}
});
}
async function doToggleFavorite() {
setFavoriting(true);
const wasFavorite = isFavorite;
try {
if (wasFavorite) {
await removeFavorite(item.id);
} else {
await addFavorite(item.id);
}
refreshFavorites();
} catch (err) {
message.error((err as Error).message);
return;
} finally {
setFavoriting(false);
}
if (!wasFavorite && customer && !customer.favorite_alerts) offerAlerts();
}
function handleFavoriteClick() {
if (authLoading) return;
if (!customer) {
setPendingAction('favorite');
setAuthModalOpen(true);
return;
}
doToggleFavorite();
}
const hasMultiple = item.images.length > 1;
const cover = item.images.length ? (
<div className="carousel-wrap">
<Carousel ref={carouselRef} dots={hasMultiple}>
{item.images.map(img => (
<div key={img.id}>
<img src={img.image_path} alt={item.name} className="card-cover-img" />
</div>
))}
</Carousel>
{hasMultiple && (
<>
<Button className="carousel-arrow carousel-arrow-left" shape="circle" size="small" icon={<LeftOutlined />}
onClick={(e) => { e.stopPropagation(); carouselRef.current?.prev(); }} />
<Button className="carousel-arrow carousel-arrow-right" shape="circle" size="small" icon={<RightOutlined />}
onClick={(e) => { e.stopPropagation(); carouselRef.current?.next(); }} />
<div className="carousel-count">{item.images.length} photos</div>
</>
)}
</div>
) : (
<div className="card-cover-placeholder" />
);
let actionButton = null;
if (item.status === 'available') {
actionButton = (
<Button block type="primary" loading={adding} onClick={handleAddClick} style={{ marginTop: 8 }}>
Add to Cart
</Button>
);
} else if (item.status === 'reserved') {
actionButton = inMyCart
? <Button block disabled style={{ marginTop: 8 }}>In Your Cart</Button>
: <Button block disabled style={{ marginTop: 8 }}>Reserved</Button>;
}
const card = (
<Card hoverable cover={cover} className="item-card">
<div className="item-card-title">
<Title level={5} style={{ marginBottom: 4 }}>{item.name}</Title>
<Tooltip title={isFavorite ? 'Remove from favorites' : 'Add to favorites'}>
<Button
type="text"
shape="circle"
loading={favoriting || authLoading}
aria-pressed={isFavorite}
aria-label={isFavorite ? `Remove ${item.name} from favorites` : `Add ${item.name} to favorites`}
icon={isFavorite ? <HeartFilled style={{ color: '#c41d7f' }} /> : <HeartOutlined />}
onClick={handleFavoriteClick}
/>
</Tooltip>
</div>
{item.category_name && <Text type="secondary" className="item-category">{item.category_name}</Text>}
<MarkdownView content={item.description} />
{item.tags.length > 0 && (
<div className="item-tags">
{item.tags.map(tag => (
<Tag key={tag.id} color={tag.color} style={{ marginInlineEnd: 4 }}>{tag.name}</Tag>
))}
</div>
)}
<div className="price">${(item.price_cents / 100).toFixed(2)}</div>
{actionButton}
<AuthPromptModal
open={authModalOpen}
onClose={() => setAuthModalOpen(false)}
onSuccess={() => {
setAuthModalOpen(false);
if (pendingAction === 'favorite') doToggleFavorite();
else doAddToCart();
}}
/>
</Card>
);
if (item.status === 'sold') {
return <Badge.Ribbon text="SOLD" color="black">{card}</Badge.Ribbon>;
}
return card;
}