feat(services): Add deposit percentage option for fixed-price services

- Add deposit_percent field back to Service model for percentage-based deposits
- Reorganize service form: variable pricing toggle at top, deposit toggle with
  amount/percent options (percent only available for fixed pricing)
- Disable price field when variable pricing is enabled
- Add backend validation: variable pricing cannot use percentage deposits
- Update frontend types and hooks to handle deposit_percent field

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
poduck
2025-12-04 13:52:51 -05:00
parent c7308ad167
commit cf91bae24f
6 changed files with 279 additions and 48 deletions

View File

@@ -26,7 +26,8 @@ export const useServices = () => {
photos: s.photos || [], photos: s.photos || [],
// Pricing fields // Pricing fields
variable_pricing: s.variable_pricing ?? false, variable_pricing: s.variable_pricing ?? false,
deposit_amount: s.deposit_amount ? parseFloat(s.deposit_amount) : 0, deposit_amount: s.deposit_amount ? parseFloat(s.deposit_amount) : null,
deposit_percent: s.deposit_percent ? parseFloat(s.deposit_percent) : null,
requires_deposit: s.requires_deposit ?? false, requires_deposit: s.requires_deposit ?? false,
requires_saved_payment_method: s.requires_saved_payment_method ?? false, requires_saved_payment_method: s.requires_saved_payment_method ?? false,
deposit_display: s.deposit_display || null, deposit_display: s.deposit_display || null,
@@ -68,7 +69,8 @@ interface ServiceInput {
description?: string; description?: string;
photos?: string[]; photos?: string[];
variable_pricing?: boolean; variable_pricing?: boolean;
deposit_amount?: number; // 0 = no deposit deposit_amount?: number | null;
deposit_percent?: number | null;
} }
/** /**
@@ -94,6 +96,9 @@ export const useCreateService = () => {
if (serviceData.deposit_amount !== undefined) { if (serviceData.deposit_amount !== undefined) {
backendData.deposit_amount = serviceData.deposit_amount; backendData.deposit_amount = serviceData.deposit_amount;
} }
if (serviceData.deposit_percent !== undefined) {
backendData.deposit_percent = serviceData.deposit_percent;
}
const { data } = await apiClient.post('/services/', backendData); const { data } = await apiClient.post('/services/', backendData);
return data; return data;
@@ -121,6 +126,7 @@ export const useUpdateService = () => {
// Pricing fields // Pricing fields
if (updates.variable_pricing !== undefined) backendData.variable_pricing = updates.variable_pricing; if (updates.variable_pricing !== undefined) backendData.variable_pricing = updates.variable_pricing;
if (updates.deposit_amount !== undefined) backendData.deposit_amount = updates.deposit_amount; if (updates.deposit_amount !== undefined) backendData.deposit_amount = updates.deposit_amount;
if (updates.deposit_percent !== undefined) backendData.deposit_percent = updates.deposit_percent;
const { data } = await apiClient.patch(`/services/${id}/`, backendData); const { data } = await apiClient.patch(`/services/${id}/`, backendData);
return data; return data;

View File

@@ -14,7 +14,10 @@ interface ServiceFormData {
photos: string[]; photos: string[];
// Pricing fields // Pricing fields
variable_pricing: boolean; variable_pricing: boolean;
deposit_amount: number; // 0 = no deposit deposit_enabled: boolean;
deposit_type: 'amount' | 'percent';
deposit_amount: number | null;
deposit_percent: number | null;
} }
const Services: React.FC = () => { const Services: React.FC = () => {
@@ -41,7 +44,10 @@ const Services: React.FC = () => {
description: '', description: '',
photos: [], photos: [],
variable_pricing: false, variable_pricing: false,
deposit_amount: 0, deposit_enabled: false,
deposit_type: 'amount',
deposit_amount: null,
deposit_percent: null,
}); });
// Photo gallery state // Photo gallery state
@@ -209,13 +215,21 @@ const Services: React.FC = () => {
description: '', description: '',
photos: [], photos: [],
variable_pricing: false, variable_pricing: false,
deposit_amount: 0, deposit_enabled: false,
deposit_type: 'amount',
deposit_amount: null,
deposit_percent: null,
}); });
setIsModalOpen(true); setIsModalOpen(true);
}; };
const openEditModal = (service: Service) => { const openEditModal = (service: Service) => {
setEditingService(service); setEditingService(service);
// Determine deposit configuration from existing data
const hasDeposit = (service.deposit_amount && service.deposit_amount > 0) ||
(service.deposit_percent && service.deposit_percent > 0);
const depositType = service.deposit_percent && service.deposit_percent > 0 ? 'percent' : 'amount';
setFormData({ setFormData({
name: service.name, name: service.name,
durationMinutes: service.durationMinutes, durationMinutes: service.durationMinutes,
@@ -223,7 +237,10 @@ const Services: React.FC = () => {
description: service.description || '', description: service.description || '',
photos: service.photos || [], photos: service.photos || [],
variable_pricing: service.variable_pricing || false, variable_pricing: service.variable_pricing || false,
deposit_amount: service.deposit_amount || 0, deposit_enabled: hasDeposit,
deposit_type: depositType,
deposit_amount: service.deposit_amount || null,
deposit_percent: service.deposit_percent || null,
}); });
setIsModalOpen(true); setIsModalOpen(true);
}; };
@@ -236,14 +253,21 @@ const Services: React.FC = () => {
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
// Build API data based on form state
const apiData = { const apiData = {
name: formData.name, name: formData.name,
durationMinutes: formData.durationMinutes, durationMinutes: formData.durationMinutes,
price: formData.price, price: formData.variable_pricing ? 0 : formData.price, // Price is 0 for variable pricing
description: formData.description, description: formData.description,
photos: formData.photos, photos: formData.photos,
variable_pricing: formData.variable_pricing, variable_pricing: formData.variable_pricing,
deposit_amount: formData.deposit_amount, // Only send deposit values if deposit is enabled
deposit_amount: formData.deposit_enabled && formData.deposit_type === 'amount'
? formData.deposit_amount
: null,
deposit_percent: formData.deposit_enabled && formData.deposit_type === 'percent'
? formData.deposit_percent
: null,
}; };
try { try {
@@ -523,6 +547,40 @@ const Services: React.FC = () => {
<form onSubmit={handleSubmit} className="flex flex-col flex-1 overflow-hidden"> <form onSubmit={handleSubmit} className="flex flex-col flex-1 overflow-hidden">
<div className="p-6 space-y-4 overflow-y-auto flex-1"> <div className="p-6 space-y-4 overflow-y-auto flex-1">
{/* Variable Pricing Toggle - At the top */}
<div className="p-4 bg-purple-50 dark:bg-purple-900/20 rounded-lg border border-purple-200 dark:border-purple-700">
<div className="flex items-center justify-between">
<div>
<label className="text-sm font-medium text-purple-900 dark:text-purple-100">
{t('services.variablePricing', 'Variable Pricing')}
</label>
<p className="text-xs text-purple-600 dark:text-purple-300 mt-0.5">
{t('services.variablePricingDescription', 'Final price is determined after service completion')}
</p>
</div>
<button
type="button"
onClick={() => setFormData({
...formData,
variable_pricing: !formData.variable_pricing,
// When enabling variable pricing, switch deposit to amount only
deposit_type: !formData.variable_pricing ? 'amount' : formData.deposit_type,
deposit_percent: !formData.variable_pricing ? null : formData.deposit_percent,
})}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
formData.variable_pricing ? 'bg-purple-600' : 'bg-gray-300 dark:bg-gray-600'
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
formData.variable_pricing ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button>
</div>
</div>
{/* Name */}
<div> <div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('services.name', 'Name')} * {t('services.name', 'Name')} *
@@ -537,6 +595,7 @@ const Services: React.FC = () => {
/> />
</div> </div>
{/* Duration and Price */}
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div> <div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
@@ -554,74 +613,164 @@ const Services: React.FC = () => {
</div> </div>
<div> <div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('services.price', 'Price ($)')} {formData.variable_pricing ? t('services.estimated', '(Estimated)') : '*'} {t('services.price', 'Price ($)')} {!formData.variable_pricing && '*'}
</label> </label>
<input <input
type="number" type="number"
value={formData.price} value={formData.variable_pricing ? '' : formData.price}
onChange={(e) => setFormData({ ...formData, price: parseFloat(e.target.value) || 0 })} onChange={(e) => setFormData({ ...formData, price: parseFloat(e.target.value) || 0 })}
required={!formData.variable_pricing} required={!formData.variable_pricing}
disabled={formData.variable_pricing}
min={0} min={0}
step={0.01} step={0.01}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500" placeholder={formData.variable_pricing ? t('services.priceNA', 'N/A') : '0.00'}
className={`w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 ${
formData.variable_pricing
? 'bg-gray-100 dark:bg-gray-900 cursor-not-allowed'
: 'bg-white dark:bg-gray-700'
}`}
/> />
{formData.variable_pricing && (
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
{t('services.variablePriceNote', 'Price determined after service')}
</p>
)}
</div> </div>
</div> </div>
{/* Deposit Amount */} {/* Deposit Toggle and Configuration */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('services.depositAmount', 'Deposit Amount ($)')}
</label>
<input
type="number"
value={formData.deposit_amount}
onChange={(e) => setFormData({ ...formData, deposit_amount: parseFloat(e.target.value) || 0 })}
min={0}
step={0.01}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
placeholder="0.00"
/>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
{t('services.depositHint', 'Set to 0 for no deposit. When set, customers must save a payment method to book.')}
</p>
</div>
{/* Variable Pricing Toggle */}
<div className="p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700"> <div className="p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<label className="text-sm font-medium text-gray-900 dark:text-white"> <label className="text-sm font-medium text-gray-900 dark:text-white">
{t('services.variablePricing', 'Variable Pricing')} {t('services.requireDeposit', 'Require Deposit')}
</label> </label>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5"> <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
{t('services.variablePricingDescription', 'Final price is determined after service completion')} {t('services.depositDescription', 'Collect a deposit when customer books')}
</p> </p>
</div> </div>
<button <button
type="button" type="button"
onClick={() => setFormData({ onClick={() => setFormData({
...formData, ...formData,
variable_pricing: !formData.variable_pricing, deposit_enabled: !formData.deposit_enabled,
deposit_amount: !formData.deposit_enabled ? 50 : null,
deposit_percent: null,
})} })}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${ className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
formData.variable_pricing ? 'bg-brand-600' : 'bg-gray-300 dark:bg-gray-600' formData.deposit_enabled ? 'bg-brand-600' : 'bg-gray-300 dark:bg-gray-600'
}`} }`}
> >
<span <span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${ className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
formData.variable_pricing ? 'translate-x-6' : 'translate-x-1' formData.deposit_enabled ? 'translate-x-6' : 'translate-x-1'
}`} }`}
/> />
</button> </button>
</div> </div>
{formData.variable_pricing && (
<p className="text-xs text-gray-500 dark:text-gray-400 mt-3 pt-3 border-t border-gray-200 dark:border-gray-600"> {/* Deposit Configuration - only shown when enabled */}
{t('services.variablePricingNote', 'The price above is shown as an estimate. The final price will be determined and charged after service completion.')} {formData.deposit_enabled && (
</p> <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-600 space-y-3">
{/* Deposit Type Selection - only show for fixed pricing */}
{!formData.variable_pricing && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('services.depositType', 'Deposit Type')}
</label>
<div className="flex gap-4">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="deposit_type"
checked={formData.deposit_type === 'amount'}
onChange={() => setFormData({
...formData,
deposit_type: 'amount',
deposit_percent: null,
deposit_amount: formData.deposit_amount || 50,
})}
className="w-4 h-4 text-brand-600 border-gray-300 focus:ring-brand-500"
/>
<span className="text-sm text-gray-700 dark:text-gray-300">
{t('services.fixedAmount', 'Fixed Amount')}
</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="deposit_type"
checked={formData.deposit_type === 'percent'}
onChange={() => setFormData({
...formData,
deposit_type: 'percent',
deposit_amount: null,
deposit_percent: formData.deposit_percent || 25,
})}
className="w-4 h-4 text-brand-600 border-gray-300 focus:ring-brand-500"
/>
<span className="text-sm text-gray-700 dark:text-gray-300">
{t('services.percentage', 'Percentage')}
</span>
</label>
</div>
</div>
)}
{/* Amount Input */}
{(formData.variable_pricing || formData.deposit_type === 'amount') && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('services.depositAmount', 'Deposit Amount ($)')} *
</label>
<input
type="number"
value={formData.deposit_amount || ''}
onChange={(e) => setFormData({ ...formData, deposit_amount: parseFloat(e.target.value) || null })}
required
min={1}
step={0.01}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
placeholder="50.00"
/>
</div>
)}
{/* Percent Input - only for fixed pricing */}
{!formData.variable_pricing && formData.deposit_type === 'percent' && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('services.depositPercent', 'Deposit Percentage (%)')} *
</label>
<input
type="number"
value={formData.deposit_percent || ''}
onChange={(e) => setFormData({ ...formData, deposit_percent: parseFloat(e.target.value) || null })}
required
min={1}
max={100}
step={1}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
placeholder="25"
/>
{formData.deposit_percent && formData.price > 0 && (
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
{t('services.depositCalculated', 'Deposit: ${amount}', {
amount: ((formData.price * formData.deposit_percent) / 100).toFixed(2)
})}
</p>
)}
</div>
)}
<p className="text-xs text-gray-500 dark:text-gray-400">
{t('services.depositNote', 'Customers must save a payment method to book this service.')}
</p>
</div>
)} )}
</div> </div>
{/* Description */}
<div> <div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('services.descriptionLabel', 'Description')} {t('services.descriptionLabel', 'Description')}

View File

@@ -211,8 +211,9 @@ export interface Service {
is_archived_by_quota?: boolean; // True if archived due to quota overage is_archived_by_quota?: boolean; // True if archived due to quota overage
// Pricing fields // Pricing fields
variable_pricing?: boolean; // If true, final price is determined after service completion variable_pricing?: boolean; // If true, final price is determined after service completion
deposit_amount?: number; // Deposit amount (0 = no deposit required) deposit_amount?: number | null; // Fixed deposit amount
requires_deposit?: boolean; // True if deposit_amount > 0 (computed) deposit_percent?: number | null; // Deposit as percentage (only for fixed pricing)
requires_deposit?: boolean; // True if deposit configured (computed)
requires_saved_payment_method?: boolean; // True if deposit > 0 or variable pricing (computed) requires_saved_payment_method?: boolean; // True if deposit > 0 or variable pricing (computed)
deposit_display?: string | null; // Human-readable deposit description deposit_display?: string | null; // Human-readable deposit description
} }

View File

@@ -0,0 +1,25 @@
# Generated by Django 5.2.8 on 2025-12-04 18:48
import django.core.validators
from decimal import Decimal
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedule', '0026_simplify_deposit_fields'),
]
operations = [
migrations.AddField(
model_name='service',
name='deposit_percent',
field=models.DecimalField(blank=True, decimal_places=2, help_text='Deposit as percentage of price (0-100), only for fixed pricing', max_digits=5, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0'))]),
),
migrations.AlterField(
model_name='service',
name='deposit_amount',
field=models.DecimalField(blank=True, decimal_places=2, help_text='Fixed deposit amount to collect at booking', max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0'))]),
),
]

View File

@@ -39,14 +39,24 @@ class Service(models.Model):
default=False, default=False,
help_text="If true, final price is determined after service completion" help_text="If true, final price is determined after service completion"
) )
# Deposit - applies to both variable and fixed pricing # Deposit configuration
# 0 = no deposit required, > 0 = deposit amount to collect at booking # - For fixed pricing: can use either deposit_amount OR deposit_percent
# - For variable pricing: can only use deposit_amount (percent doesn't make sense)
deposit_amount = models.DecimalField( deposit_amount = models.DecimalField(
max_digits=10, max_digits=10,
decimal_places=2, decimal_places=2,
default=Decimal('0.00'), null=True,
blank=True,
validators=[MinValueValidator(Decimal('0'))], validators=[MinValueValidator(Decimal('0'))],
help_text="Deposit amount to collect at booking (0 = no deposit)" help_text="Fixed deposit amount to collect at booking"
)
deposit_percent = models.DecimalField(
max_digits=5,
decimal_places=2,
null=True,
blank=True,
validators=[MinValueValidator(Decimal('0')), ],
help_text="Deposit as percentage of price (0-100), only for fixed pricing"
) )
# Quota overage archiving # Quota overage archiving
@@ -73,13 +83,32 @@ class Service(models.Model):
@property @property
def requires_deposit(self): def requires_deposit(self):
"""Check if this service requires a deposit""" """Check if this service requires a deposit"""
return self.deposit_amount and self.deposit_amount > 0 has_amount = self.deposit_amount and self.deposit_amount > 0
has_percent = self.deposit_percent and self.deposit_percent > 0
return has_amount or has_percent
@property @property
def requires_saved_payment_method(self): def requires_saved_payment_method(self):
"""Customer must have a saved payment method if deposit > 0 or variable pricing""" """Customer must have a saved payment method if deposit > 0 or variable pricing"""
return self.requires_deposit or self.variable_pricing return self.requires_deposit or self.variable_pricing
def get_deposit_amount(self, price=None):
"""
Calculate the actual deposit amount.
Args:
price: Price to use for percentage calculation (defaults to self.price)
Returns:
Decimal: The deposit amount, or None if no deposit required.
"""
if self.deposit_amount and self.deposit_amount > 0:
return self.deposit_amount
if self.deposit_percent and self.deposit_percent > 0:
base_price = price if price is not None else self.price
return (base_price * self.deposit_percent / 100).quantize(Decimal('0.01'))
return None
class ResourceType(models.Model): class ResourceType(models.Model):
""" """

View File

@@ -156,7 +156,7 @@ class ServiceSerializer(serializers.ModelSerializer):
'price', 'display_order', 'photos', 'is_active', 'created_at', 'updated_at', 'price', 'display_order', 'photos', 'is_active', 'created_at', 'updated_at',
'is_archived_by_quota', 'is_archived_by_quota',
# Pricing fields # Pricing fields
'variable_pricing', 'deposit_amount', 'variable_pricing', 'deposit_amount', 'deposit_percent',
'requires_deposit', 'requires_saved_payment_method', 'deposit_display', 'requires_deposit', 'requires_saved_payment_method', 'deposit_display',
] ]
read_only_fields = ['created_at', 'updated_at', 'is_archived_by_quota', read_only_fields = ['created_at', 'updated_at', 'is_archived_by_quota',
@@ -166,8 +166,29 @@ class ServiceSerializer(serializers.ModelSerializer):
"""Get a human-readable description of the deposit requirement""" """Get a human-readable description of the deposit requirement"""
if obj.deposit_amount and obj.deposit_amount > 0: if obj.deposit_amount and obj.deposit_amount > 0:
return f"${obj.deposit_amount} deposit" return f"${obj.deposit_amount} deposit"
if obj.deposit_percent and obj.deposit_percent > 0:
return f"{obj.deposit_percent}% deposit"
return None return None
def validate(self, attrs):
"""Validate deposit configuration"""
variable_pricing = attrs.get('variable_pricing', getattr(self.instance, 'variable_pricing', False))
deposit_percent = attrs.get('deposit_percent', getattr(self.instance, 'deposit_percent', None))
# Variable pricing cannot use percentage deposit
if variable_pricing and deposit_percent and deposit_percent > 0:
raise serializers.ValidationError({
'deposit_percent': 'Variable pricing services cannot use percentage deposits. Use a fixed amount instead.'
})
# Validate deposit_percent range
if deposit_percent and deposit_percent > 100:
raise serializers.ValidationError({
'deposit_percent': 'Deposit percentage cannot exceed 100%'
})
return attrs
class ResourceSerializer(serializers.ModelSerializer): class ResourceSerializer(serializers.ModelSerializer):
"""Serializer for Resource model""" """Serializer for Resource model"""