Skip to content

Commit

Permalink
clients: Update cancellation to use new endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
birkjernstrom committed Dec 18, 2024
1 parent 61a0222 commit b9fd9f7
Show file tree
Hide file tree
Showing 7 changed files with 151 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -673,10 +673,10 @@ interface CancelSubscriptionViewProps {
) => void
}

type CancellationDateSelections = 'now' | 'period-end'
type CancellationAction = 'revoke' | 'cancel_at_period_end'

interface SubscriptionCancelForm extends SubscriptionCancel {
cancellation_date: CancellationDateSelections
cancellation_action: CancellationAction
}

const CancelSubscriptionView = ({
Expand All @@ -686,22 +686,27 @@ const CancelSubscriptionView = ({
const cancelSubscription = useCancelSubscription()
const form = useForm<SubscriptionCancelForm>({
defaultValues: {
cancellation_date: 'period-end',
now: false,
customer_reason: undefined,
cancellation_action: 'cancel_at_period_end',
customer_cancellation_reason: undefined,
},
})
const { control, handleSubmit, setError, setValue } = form

const onSubmit = useCallback(
async (cancellation: SubscriptionCancel) => {
async (cancellation: SubscriptionCancelForm) => {
try {
let body: SubscriptionCancel = {
customer_cancellation_reason: cancellation.customer_cancellation_reason
}
if (cancellation.cancellation_action === 'revoke') {
body.revoke = true
} else {
body.cancel_at_period_end = true
}

await cancelSubscription.mutateAsync({
id: subscription.id,
body: {
now: cancellation.now,
customer_reason: cancellation.customer_reason,
},
body: body
})
} catch (e) {
if (e instanceof ResponseError) {
Expand Down Expand Up @@ -749,24 +754,23 @@ const CancelSubscriptionView = ({
<div className="flex flex-col gap-y-6">
<FormField
control={control}
name="cancellation_date"
name="cancellation_action"
render={({ field }) => (
<FormItem>
<FormLabel>Cancellation Date</FormLabel>
<FormControl>
<Select
value={field.value}
onValueChange={(value: CancellationDateSelections) => {
setValue('now', value === 'now')
setValue('cancellation_date', value)
onValueChange={(value: CancellationAction) => {
setValue('cancellation_action', value)
}}
>
<SelectTrigger>
<SelectValue placeholder="Select Cancellation Time" />
</SelectTrigger>
<SelectContent>
<SelectItem value="now">Immediately</SelectItem>
<SelectItem value="period-end">
<SelectItem value="revoke">Immediately</SelectItem>
<SelectItem value="cancel_at_period_end">
End of current period
{periodEndOutput && (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@ import { ReceiptOutlined } from '@mui/icons-material'
import {
CustomerOrder,
CustomerSubscription,
CustomerSubscriptionCancel,
PolarAPI,
CustomerCancellationReason,
CustomerPortalSubscriptionsApiCancelRequest,
CustomerSubscriptionCancel,
ResponseError,
ValidationError,
} from '@polar-sh/sdk'
Expand Down Expand Up @@ -274,12 +273,12 @@ const CustomerPortalSubscription = ({
interface CustomerCancellationModalProps
extends Omit<ModalProps, 'modalContent'> {
subscription: CustomerSubscription
cancelSubscription: UseMutationResult<CustomerSubscription, Error, CustomerPortalSubscriptionsApiCancelRequest, unknown>
cancelSubscription: UseMutationResult<CustomerSubscription, Error, { id: string, body: CustomerSubscriptionCancel }, unknown>
onAbort?: () => void
}

interface CustomerSubscriptionCancelForm extends CustomerSubscriptionCancel {
comment: string | undefined
cancellation_comment: string | undefined
}

const CustomerCancellationModal = ({
Expand All @@ -297,8 +296,9 @@ const CustomerCancellationModal = ({

const form = useForm<CustomerSubscriptionCancelForm>({
defaultValues: {
reason: undefined,
comment: undefined,
cancel_at_period_end: true,
cancellation_reason: undefined,
cancellation_comment: undefined,
},
})
const { control, handleSubmit, setError, setValue } = form
Expand Down Expand Up @@ -330,7 +330,7 @@ const CustomerCancellationModal = ({
)

const onReasonSelect = (value: CustomerCancellationReason) => {
setValue('reason', value ?? '')
setValue('cancellation_reason', value ?? '')
}

return (
Expand All @@ -350,7 +350,7 @@ const CustomerCancellationModal = ({
<form onSubmit={handleSubmit(handleCancellation)}>
<FormField
control={control}
name="reason"
name="cancellation_reason"
render={({ field }) => (
<FormItem>
<FormControl>
Expand Down Expand Up @@ -398,7 +398,7 @@ const CustomerCancellationModal = ({
/>
<FormField
control={control}
name="comment"
name="cancellation_comment"
render={({ field }) => (
<FormItem className="mt-8">
<FormControl>
Expand Down
9 changes: 6 additions & 3 deletions clients/apps/web/src/hooks/queries/customerPortal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
CustomerPortalLicenseKeysApiListRequest,
CustomerPortalOrdersApiListRequest,
CustomerPortalSubscriptionsApiListRequest,
CustomerPortalSubscriptionsApiCancelRequest,
CustomerSubscriptionCancel,
CustomerSubscriptionUpdate,
PolarAPI,
} from '@polar-sh/sdk'
Expand Down Expand Up @@ -156,8 +156,11 @@ export const useCustomerUpdateSubscription = (api: PolarAPI) =>

export const useCustomerCancelSubscription = (api: PolarAPI) =>
useMutation({
mutationFn: (variables: CustomerPortalSubscriptionsApiCancelRequest) => {
return api.customerPortalSubscriptions.cancel(variables)
mutationFn: (variables: {
id: string,
body: CustomerSubscriptionCancel
}) => {
return api.customerPortalSubscriptions.update(variables)
},
onSuccess: (_result, _variables, _ctx) => {
queryClient.invalidateQueries({
Expand Down
2 changes: 1 addition & 1 deletion clients/apps/web/src/hooks/queries/subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const useListSubscriptions = (
export const useCancelSubscription = () =>
useMutation({
mutationFn: (variables: { id: string, body: SubscriptionCancel }) => {
return api.subscriptions.cancel(variables)
return api.subscriptions.update(variables)
},
onSuccess: (result, _variables, _ctx) => {
queryClient.setQueriesData<ListResourceSubscription>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@

import * as runtime from '../runtime';
import type {
AlreadyCanceledCustomerSubscription,
AlreadyCanceledSubscription,
CustomerSubscription,
CustomerSubscriptionCancel,
CustomerSubscriptionSortProperty,
CustomerSubscriptionUpdate,
HTTPValidationError,
Expand All @@ -29,7 +28,6 @@ import type {

export interface CustomerPortalSubscriptionsApiCancelRequest {
id: string;
body: CustomerSubscriptionCancel;
}

export interface CustomerPortalSubscriptionsApiGetRequest {
Expand Down Expand Up @@ -68,19 +66,10 @@ export class CustomerPortalSubscriptionsApi extends runtime.BaseAPI {
);
}

if (requestParameters['body'] == null) {
throw new runtime.RequiredError(
'body',
'Required parameter "body" was null or undefined when calling cancel().'
);
}

const queryParameters: any = {};

const headerParameters: runtime.HTTPHeaders = {};

headerParameters['Content-Type'] = 'application/json';

if (this.configuration && this.configuration.accessToken) {
const token = this.configuration.accessToken;
const tokenString = await token("pat", []);
Expand All @@ -102,7 +91,6 @@ export class CustomerPortalSubscriptionsApi extends runtime.BaseAPI {
method: 'DELETE',
headers: headerParameters,
query: queryParameters,
body: requestParameters['body'],
}, initOverrides);

return new runtime.JSONApiResponse(response);
Expand Down
75 changes: 61 additions & 14 deletions clients/packages/sdk/src/client/apis/SubscriptionsApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@ import type {
ProductIDFilter,
ResourceNotFound,
Subscription,
SubscriptionCancel,
SubscriptionSortProperty,
SubscriptionUpdate,
} from '../models/index';

export interface SubscriptionsApiCancelRequest {
id: string;
body: SubscriptionCancel;
}

export interface SubscriptionsApiExportRequest {
Expand All @@ -49,13 +48,18 @@ export interface SubscriptionsApiListRequest {
sorting?: Array<SubscriptionSortProperty>;
}

export interface SubscriptionsApiUpdateRequest {
id: string;
body: SubscriptionUpdate;
}

/**
*
*/
export class SubscriptionsApi extends runtime.BaseAPI {

/**
* Cancel a subscription.
* Cancel a subscription immediately.
* Cancel Subscription
*/
async cancelRaw(requestParameters: SubscriptionsApiCancelRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<Subscription>> {
Expand All @@ -66,19 +70,10 @@ export class SubscriptionsApi extends runtime.BaseAPI {
);
}

if (requestParameters['body'] == null) {
throw new runtime.RequiredError(
'body',
'Required parameter "body" was null or undefined when calling cancel().'
);
}

const queryParameters: any = {};

const headerParameters: runtime.HTTPHeaders = {};

headerParameters['Content-Type'] = 'application/json';

if (this.configuration && this.configuration.accessToken) {
const token = this.configuration.accessToken;
const tokenString = await token("pat", []);
Expand All @@ -92,14 +87,13 @@ export class SubscriptionsApi extends runtime.BaseAPI {
method: 'DELETE',
headers: headerParameters,
query: queryParameters,
body: requestParameters['body'],
}, initOverrides);

return new runtime.JSONApiResponse(response);
}

/**
* Cancel a subscription.
* Cancel a subscription immediately.
* Cancel Subscription
*/
async cancel(requestParameters: SubscriptionsApiCancelRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Subscription> {
Expand Down Expand Up @@ -219,4 +213,57 @@ export class SubscriptionsApi extends runtime.BaseAPI {
return await response.value();
}

/**
* Update a subscription of the authenticated customer or user.
* Update Subscription
*/
async updateRaw(requestParameters: SubscriptionsApiUpdateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<Subscription>> {
if (requestParameters['id'] == null) {
throw new runtime.RequiredError(
'id',
'Required parameter "id" was null or undefined when calling update().'
);
}

if (requestParameters['body'] == null) {
throw new runtime.RequiredError(
'body',
'Required parameter "body" was null or undefined when calling update().'
);
}

const queryParameters: any = {};

const headerParameters: runtime.HTTPHeaders = {};

headerParameters['Content-Type'] = 'application/json';

if (this.configuration && this.configuration.accessToken) {
const token = this.configuration.accessToken;
const tokenString = await token("pat", []);

if (tokenString) {
headerParameters["Authorization"] = `Bearer ${tokenString}`;
}
}
const response = await this.request({
path: `/v1/subscriptions/{id}`.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id']))),
method: 'PATCH',
headers: headerParameters,
query: queryParameters,
body: requestParameters['body'],
}, initOverrides);

return new runtime.JSONApiResponse(response);
}

/**
* Update a subscription of the authenticated customer or user.
* Update Subscription
*/
async update(requestParameters: SubscriptionsApiUpdateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Subscription> {
const response = await this.updateRaw(requestParameters, initOverrides);
return await response.value();
}

}
Loading

0 comments on commit b9fd9f7

Please sign in to comment.