-
Notifications
You must be signed in to change notification settings - Fork 781
Expand file tree
/
Copy pathCustomerSeatQuantityManager.tsx
More file actions
185 lines (170 loc) · 5.8 KB
/
Copy pathCustomerSeatQuantityManager.tsx
File metadata and controls
185 lines (170 loc) · 5.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
'use client'
import { useCustomerUpdateSubscription } from '@/hooks/queries/customerPortal'
import { setValidationErrors } from '@/utils/api/errors'
import { Client, isValidationError, schemas } from '@polar-sh/client'
import { Button } from '@polar-sh/orbit'
import { MinusIcon, PlusIcon } from 'lucide-react'
import { useCallback, useMemo } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from '../Toast/use-toast'
interface CustomerSeatQuantityManagerProps {
api: Client
subscriptionId: string
totalSeats: number
availableSeats: number
prorationBehavior?: schemas['CustomerOrganization']['proration_behavior']
onUpdate?: () => void
}
export const CustomerSeatQuantityManager = ({
api,
subscriptionId,
totalSeats,
availableSeats,
prorationBehavior,
onUpdate,
}: CustomerSeatQuantityManagerProps) => {
const updateSubscription = useCustomerUpdateSubscription(api)
const assignedSeats = totalSeats - availableSeats
const { handleSubmit, watch, setValue, setError } = useForm<{
seats: number
}>({
values: {
seats: totalSeats,
},
})
// eslint-disable-next-line react-hooks/incompatible-library
const seats = watch('seats')
const canDecrease = seats !== undefined && seats > assignedSeats
const hasChanges = seats !== totalSeats
const invoicingMessage = useMemo((): string | null => {
if (!prorationBehavior) return null
switch (prorationBehavior) {
case 'invoice':
return "You'll be charged immediately, with a proration for the current period."
case 'prorate':
return 'Your next invoice will include the updated seats plus the proration for the current period.'
case 'next_period':
return 'The seat update will be applied on your next billing cycle.'
case 'reset':
return "You'll be charged the full new amount immediately, and your billing period restarts today."
}
}, [prorationBehavior])
const onSubmit = useCallback(
async (data: { seats: number }) => {
try {
const result = await updateSubscription.mutateAsync({
id: subscriptionId,
body: {
seats: data.seats,
},
})
if (result.error) {
const errorMessage =
typeof result.error.detail === 'string'
? result.error.detail
: 'Failed to update seats'
toast({
title: 'Error updating seats',
description: errorMessage,
variant: 'error',
})
} else {
const descriptionMessage = (() => {
const seatText = `${data.seats} ${data.seats === 1 ? 'seat' : 'seats'}`
switch (prorationBehavior) {
case 'invoice':
return `Subscription now has ${seatText}. You'll be charged immediately with a proration for the current month.`
case 'prorate':
return `Subscription now has ${seatText}. Your next invoice will include the updated seats plus the proration for the current month.`
case 'next_period':
return `Subscription will have ${seatText} starting on your next billing cycle.`
default:
return `Subscription now has ${seatText}.`
}
})()
toast({
title: 'Seats updated',
description: descriptionMessage,
})
onUpdate?.()
}
} catch (error) {
if (isValidationError(error)) {
setValidationErrors(error, setError)
} else {
toast({
title: 'Error updating seats',
description:
error instanceof Error
? error.message
: 'An unexpected error occurred',
variant: 'error',
})
}
}
},
[updateSubscription, subscriptionId, prorationBehavior, onUpdate, setError],
)
const handleIncrement = () => {
if (seats !== undefined) {
setValue('seats', seats + 1, { shouldValidate: true })
}
}
const handleDecrement = () => {
if (seats !== undefined && canDecrease) {
setValue('seats', seats - 1, { shouldValidate: true })
}
}
return (
<form onSubmit={handleSubmit(onSubmit)} className="rounded-2xl border p-4">
<div className="flex flex-col gap-2 text-sm">
<div className="flex items-center justify-between">
<div>
<span className="font-medium">Total seats</span>
</div>
<div className="flex items-center gap-1">
<Button
type="button"
variant="secondary"
size="icon"
onClick={handleDecrement}
disabled={!canDecrease || updateSubscription.isPending}
>
<MinusIcon className="h-4 w-4" />
</Button>
<span className="dark:text-polar-200 flex h-8 min-w-8 items-center justify-center px-2 font-medium">
{seats}
</span>
<Button
type="button"
variant="secondary"
size="icon"
onClick={handleIncrement}
disabled={updateSubscription.isPending}
>
<PlusIcon className="h-4 w-4" />
</Button>
</div>
</div>
</div>
{hasChanges && (
<div className="mt-4 flex flex-col gap-3">
{invoicingMessage && (
<span className="dark:text-polar-500 text-sm text-gray-500">
{invoicingMessage}
</span>
)}
<div className="flex flex-row-reverse gap-3">
<Button
loading={updateSubscription.isPending}
onClick={handleSubmit(onSubmit)}
className="w-full"
>
Update seats
</Button>
</div>
</div>
)}
</form>
)
}