Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: migrate segment subscribers + typescript support #5904

Merged
merged 6 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 0 additions & 13 deletions packages/medusa-plugin-segment/.babelrc

This file was deleted.

23 changes: 7 additions & 16 deletions packages/medusa-plugin-segment/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,36 +14,27 @@
"author": "Sebastian Rindom",
"license": "MIT",
"devDependencies": {
"@babel/cli": "^7.7.5",
"@babel/core": "^7.7.5",
"@babel/node": "^7.7.4",
"@babel/plugin-proposal-class-properties": "^7.7.4",
"@babel/plugin-transform-classes": "^7.9.5",
"@babel/plugin-transform-instanceof": "^7.8.3",
"@babel/plugin-transform-runtime": "^7.7.6",
"@babel/preset-env": "^7.7.5",
"@babel/register": "^7.7.4",
"@babel/runtime": "^7.9.6",
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
"jest": "^25.5.4",
"medusa-interfaces": "^1.3.7",
"medusa-test-utils": "^1.1.40"
"medusa-test-utils": "^1.1.40",
"rimraf": "^5.0.1",
"typescript": "^4.9.5"
},
"scripts": {
"prepare": "cross-env NODE_ENV=production yarn run build",
"prepublishOnly": "cross-env NODE_ENV=production tsc --build",
"test": "jest --passWithNoTests src",
"build": "babel src --out-dir . --ignore '**/__tests__','**/__mocks__'",
"watch": "babel -w src --out-dir . --ignore '**/__tests__','**/__mocks__'"
"build": "rimraf dist && tsc -p ./tsconfig.server.json",
"watch": "tsc --watch"
},
"peerDependencies": {
"@medusajs/medusa": ">= 1.18.0 < 2",
"medusa-interfaces": "^1.3.7"
},
"dependencies": {
"analytics-node": "^3.4.0-beta.1",
"axios": "^0.19.2",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.2.0"
},
"gitHead": "cd1f5afa5aa8c0b15ea957008ee19f1d695cbd2e",
Expand Down
6 changes: 3 additions & 3 deletions packages/medusa-plugin-segment/src/services/segment.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,10 @@ class SegmentService extends BaseService {
order_id: order.id,
email: order.email,
region_id: order.region_id,
payment_provider: order.payments.map((p) => p.provider_id).join(","),
payment_provider: order.payments?.map((p) => p.provider_id).join(","),
shipping_methods: order.shipping_methods,
shipping_country: order.shipping_address.country_code,
shipping_city: order.shipping_address.city,
shipping_country: order.shipping_address?.country_code,
shipping_city: order.shipping_address?.city,
reporting_total: await this.getReportingValue(order.currency_code, total),
reporting_subtotal: await this.getReportingValue(
order.currency_code,
Expand Down
46 changes: 46 additions & 0 deletions packages/medusa-plugin-segment/src/subscribers/claim-created.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
export default async function handler({ data: { id }, container }) {
const segmentService = container.resolve("segmentService")
const claimService = container.resolve("claimService")

const claim = await claimService.retrieve(id, {
relations: [
"order",
"claim_items",
"claim_items.item",
"claim_items.tags",
"claim_items.variant",
],
})

for (const ci of claim.claim_items) {
const price = ci.item.unit_price / 100
const reporting_price = await segmentService.getReportingValue(
claim.order.currency_code,
price
)
const event = {
event: "Item Claimed",
userId: claim.order.customer_id,
timestamp: claim.created_at,
properties: {
price,
reporting_price,
order_id: claim.order_id,
claim_id: claim.id,
claim_item_id: ci.id,
type: claim.type,
quantity: ci.quantity,
variant: ci.variant.sku,
product_id: ci.variant.product_id,
reason: ci.reason,
note: ci.note,
tags: ci.tags.map((t) => ({ id: t.id, value: t.value })),
},
}
await segmentService.track(event)
}
}

export const config = {
event: "claim.created",
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export default async function handler({ data: { id }, container }) {
const orderService = container.resolve("orderService")
const segmentService = container.resolve("segmentService")

const order = await orderService.retrieveWithTotals(id)

const date = new Date()
const orderData = await segmentService.buildOrder(order)
const orderEvent = {
event: "Order Cancelled",
userId: order.customer_id,
properties: orderData,
timestamp: date,
}

segmentService.track(orderEvent)
}

export const config = {
event: "order.canceled",
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
export default async function handler({ data: { id, return_id }, container }) {
const orderService = container.resolve("orderService")
const returnService = container.resolve("returnService")
const segmentService = container.resolve("segmentService")

const order = await orderService.retrieveWithTotals(id, {
relations: [
"customer",
"billing_address",
"shipping_address",
"discounts",
"discounts.rule",
"shipping_methods",
"shipping_methods.shipping_option",
"payments",
"fulfillments",
"returns",
"items",
"gift_cards",
"gift_card_transactions",
"swaps",
"swaps.return_order",
"swaps.payment",
"swaps.shipping_methods",
"swaps.shipping_methods.shipping_option",
"swaps.shipping_address",
"swaps.additional_items",
"swaps.fulfillments",
],
})

const ret = await returnService.retrieve(return_id, {
relations: ["items", "items.reason"],
})

const shipping: object[] = []
if (ret.shipping_method && ret.shipping_method.price) {
shipping.push({
...ret.shipping_method,
price: -1 * (ret.shipping_method.price / 100),
})
}

let merged = [...order.items]

// merge items from order with items from order swaps
if (order.swaps && order.swaps.length) {
for (const s of order.swaps) {
merged = [...merged, ...s.additional_items]
}
}

const toBuildFrom = {
...order,
shipping_methods: shipping,
items: ret.items.map((i) => {
const li = merged.find((l) => l.id === i.item_id)
if (i.reason) {
li.reason = i.reason
}

if (i.note) {
li.note = i.note
}
return li
}),
}

const orderData = await segmentService.buildOrder(toBuildFrom)
const orderEvent = {
event: "Order Refunded",
userId: order.customer_id,
properties: orderData,
timestamp: new Date(),
}

segmentService.track(orderEvent)
}

export const config = {
event: "order.items-returned",
}
87 changes: 87 additions & 0 deletions packages/medusa-plugin-segment/src/subscribers/order-placed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
export default async function handler({ data: { id }, container }) {
const orderService = container.resolve("orderService")
const cartService = container.resolve("cartService")
const segmentService = container.resolve("segmentService")
const order = await orderService.retrieveWithTotals(id, {
relations: [
"customer",
"billing_address",
"shipping_address",
"discounts",
"discounts.rule",
"shipping_methods",
"shipping_methods.shipping_option",
"payments",
"fulfillments",
"items",
"returns",
"gift_cards",
"gift_card_transactions",
"swaps",
"swaps.return_order",
"swaps.payment",
"swaps.shipping_methods",
"swaps.shipping_methods.shipping_option",
"swaps.shipping_address",
"swaps.additional_items",
"swaps.fulfillments",
],
})

const eventContext: Record<string, unknown> = {}
const integrations: Record<string, unknown> = {}

if (order.cart_id) {
try {
const cart = await cartService.retrieve(order.cart_id, {
select: ["context"],
})

if (cart.context) {
if (cart.context.ip) {
eventContext.ip = cart.context.ip
}

if (cart.context.user_agent) {
eventContext.user_agent = cart.context.user_agent
}

if (segmentService.options_ && segmentService.options_.use_ga_id) {
if (cart.context.ga_id) {
integrations["Google Analytics"] = {
clientId: cart.context.ga_id,
}
}
}
}
} catch (err) {
console.log(err)
console.warn("Failed to gather context for order")
}
}

const orderData = await segmentService.buildOrder(order)
const orderEvent = {
event: "Order Completed",
userId: order.customer_id,
properties: orderData,
timestamp: order.created_at,
context: eventContext,
integrations,
}

segmentService.identify({
userId: order.customer_id,
traits: {
email: order.email,
firstName: order.shipping_address.first_name,
lastName: order.shipping_address.last_name,
},
})

segmentService.track(orderEvent)
}

export const config = {
event: "order.placed",
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
export default async function handler({
data: { id, fulfillment_id },
container,
}) {
const orderService = container.resolve("orderService")
const fulfillmentService = container.resolve("fulfillmentService")
const segmentService = container.resolve("segmentService")

const order = await orderService.retrieveWithTotals(id, {
relations: [
"customer",
"billing_address",
"shipping_address",
"discounts",
"discounts.rule",
"shipping_methods",
"shipping_methods.shipping_option",
"payments",
"fulfillments",
"returns",
"items",
"gift_cards",
"gift_card_transactions",
"swaps",
"swaps.return_order",
"swaps.payment",
"swaps.shipping_methods",
"swaps.shipping_methods.shipping_option",
"swaps.shipping_address",
"swaps.additional_items",
"swaps.fulfillments",
],
})

const fulfillment = await fulfillmentService.retrieve(fulfillment_id, {
relations: ["items"],
})

const toBuildFrom = {
...order,
provider_id: fulfillment.provider,
items: fulfillment.items.map((i) =>
order.items.find((l) => l.id === i.item_id)
),
}

const orderData = await segmentService.buildOrder(toBuildFrom)
const orderEvent = {
event: "Order Shipped",
userId: order.customer_id,
properties: orderData,
timestamp: fulfillment.shipped_at,
}

segmentService.track(orderEvent)
}

export const config = {
event: "order.shipment_created",
}
Loading