Skip to content

Commit adc71df

Browse files
committed
bugfix(shopify): only set shopify current_period_end on cancel
1 parent 6122012 commit adc71df

3 files changed

Lines changed: 25 additions & 36 deletions

File tree

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
import type { ActionFunctionArgs } from "@remix-run/node";
22
import { authenticate } from "../shopify.server";
3-
import { useAppBridge } from "@shopify/app-bridge-react";
43
import { ShopifyPlanChangePayload } from "trieve-ts-sdk";
54
import db from "../db.server";
6-
import { useTrieve } from "app/context/trieveContext";
75
import { sdkFromKey, validateTrieveAuthWehbook } from "app/auth";
86

97
async function hashString(str: string) {
108
const textEncoder = new TextEncoder();
119
const data = textEncoder.encode(str);
12-
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
10+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1311
const hashArray = Array.from(new Uint8Array(hashBuffer));
14-
const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
12+
const hashHex = hashArray
13+
.map((byte) => byte.toString(16).padStart(2, "0"))
14+
.join("");
1515
return hashHex;
1616
}
1717

@@ -20,13 +20,12 @@ export const action = async ({ request }: ActionFunctionArgs) => {
2020
const key = await validateTrieveAuthWehbook(shop);
2121
const trieve = sdkFromKey(key);
2222

23-
2423
console.log(`Received ${topic} webhook for ${shop}`);
2524
const organization_id = await db.apiKey.findFirst({
2625
where: {
2726
shop: `https://${shop}`,
28-
}
29-
})
27+
},
28+
});
3029
if (!organization_id) {
3130
return new Response("Organization not found", { status: 404 });
3231
}
@@ -40,22 +39,30 @@ export const action = async ({ request }: ActionFunctionArgs) => {
4039
}
4140
}
4241
}
43-
`
44-
)
42+
`,
43+
);
4544

4645
const trievePayload: ShopifyPlanChangePayload = {
4746
organization_id: organization_id?.organizationId,
48-
idempotency_key: await hashString(`${payload.app_subscription.updated_at}-${payload.app_subscription.admin_graphql_api_id}`),
47+
idempotency_key: await hashString(
48+
`${payload.app_subscription.updated_at}-${payload.app_subscription.admin_graphql_api_id}`,
49+
),
4950
shopify_plan: {
50-
handle: payload.app_subscription.name.replace("\n", "").replace(/ /g, "-").toLowerCase(),
51+
handle: payload.app_subscription.name
52+
.replace("\n", "")
53+
.replace(/ /g, "-")
54+
.toLowerCase(),
5155
status: payload.app_subscription.status,
52-
current_period_end: (await data?.json())?.data.currentAppInstallation.activeSubscriptions?.[0]?.currentPeriodEnd ?? undefined,
56+
current_period_end:
57+
(await data?.json())?.data.currentAppInstallation
58+
.activeSubscriptions?.[0]?.currentPeriodEnd ?? undefined,
5359
},
5460
};
5561

56-
console.log(trievePayload)
57-
58-
await trieve.handleShopifyPlanChange(trievePayload, process.env.SHOPIFY_SECRET_KEY || "");
62+
await trieve.handleShopifyPlanChange(
63+
trievePayload,
64+
process.env.SHOPIFY_SECRET_KEY || "",
65+
);
5966

6067
return new Response();
6168
};

server/src/data/models.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3922,7 +3922,7 @@ impl Default for StripePlan {
39223922
updated_at: chrono::Utc::now().naive_local(),
39233923
name: "Free".to_string(),
39243924
visible: true,
3925-
messages_per_month: Some(1000),
3925+
messages_per_month: Some(50),
39263926
}
39273927
}
39283928
}

server/src/handlers/payment_handler.rs

Lines changed: 2 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ use crate::{
2727
},
2828
};
2929
use actix_web::{web, HttpRequest, HttpResponse};
30-
use dateparser::DateTimeUtc;
3130
use serde::{Deserialize, Serialize};
3231
use stripe::{EventObject, EventType, Object, Webhook};
3332
use utoipa::ToSchema;
@@ -777,19 +776,16 @@ pub async fn handle_shopify_plan_change(
777776

778777
if let Some(organization_plan) = organization_plan {
779778
if organization_plan.stripe_id == payload.idempotency_key {
780-
// No changes
781779
return Ok(HttpResponse::NoContent().finish());
782780
}
783781

784782
if organization_plan.plan_id == plan.id
785783
&& payload.shopify_plan.status.to_lowercase() == "active"
786784
{
787-
// No changes
788785
return Ok(HttpResponse::NoContent().finish());
789786
} else if organization_plan.plan_id == plan.id
790787
&& payload.shopify_plan.status.to_lowercase() != "active"
791788
{
792-
// Cancel the old plan
793789
set_stripe_subscription_current_period_end(
794790
organization_plan.stripe_id,
795791
chrono::Utc::now().naive_utc(),
@@ -799,35 +795,21 @@ pub async fn handle_shopify_plan_change(
799795
} else if organization_plan.plan_id != plan.id
800796
&& payload.shopify_plan.status.to_lowercase() == "active"
801797
{
802-
// Create a new plan
803798
create_stripe_subscription_query(
804799
payload.idempotency_key.clone(),
805800
plan.id,
806801
payload.organization_id,
807-
payload.shopify_plan.current_period_end.clone().map(|s| {
808-
s.parse::<DateTimeUtc>()
809-
.unwrap()
810-
.0
811-
.with_timezone(&chrono::Utc)
812-
.naive_utc()
813-
}),
802+
None,
814803
pool.clone(),
815804
)
816805
.await?;
817806
}
818807
} else if payload.shopify_plan.status.to_lowercase() == "active" {
819-
// Create a new plan
820808
create_stripe_subscription_query(
821809
payload.idempotency_key.clone(),
822810
plan.id,
823811
payload.organization_id,
824-
payload.shopify_plan.current_period_end.clone().map(|s| {
825-
s.parse::<DateTimeUtc>()
826-
.unwrap()
827-
.0
828-
.with_timezone(&chrono::Utc)
829-
.naive_utc()
830-
}),
812+
None,
831813
pool.clone(),
832814
)
833815
.await?;

0 commit comments

Comments
 (0)