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

[pull] develop from medusajs:develop #14

Merged
merged 6 commits into from
Jan 14, 2025
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
8 changes: 8 additions & 0 deletions .changeset/eight-nails-act.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@medusajs/admin-bundler": patch
"@medusajs/cli": patch
"@medusajs/framework": patch
"@medusajs/medusa": patch
---

feat(medusa,admin-bundler,cli,framework): Integrate admin extensions into plugin build
6 changes: 6 additions & 0 deletions .changeset/eleven-rules-battle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@medusajs/dashboard": patch
"@medusajs/core-flows": patch
---

fix(dashboard, core-flows): improvements to order page on canceled orders
5 changes: 5 additions & 0 deletions .changeset/sixty-peaches-hug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@medusajs/core-flows": patch
---

fix(core-flows): return refunded when all captured payments have been refunded
13 changes: 6 additions & 7 deletions integration-tests/http/__tests__/order/admin/order.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,11 +443,12 @@ medusaIntegrationTestRunner({
amount: 106,
payments: [
expect.objectContaining({
// canceled_at: expect.any(String),
canceled_at: null,
refunds: [
expect.objectContaining({
id: expect.any(String),
amount: 106,
created_by: expect.any(String),
}),
],
captures: [
Expand Down Expand Up @@ -488,11 +489,9 @@ medusaIntegrationTestRunner({
})
)

const response = await api.post(
`/admin/orders/${order.id}/cancel`,
{},
adminHeaders
)
const response = await api
.post(`/admin/orders/${order.id}/cancel`, {}, adminHeaders)
.catch((e) => e)

expect(response.status).toBe(200)
expect(response.data.order).toEqual(
Expand All @@ -514,11 +513,11 @@ medusaIntegrationTestRunner({
amount: 106,
payments: [
expect.objectContaining({
// canceled_at: expect.any(String),
refunds: [
expect.objectContaining({
id: expect.any(String),
amount: 50,
created_by: expect.any(String),
}),
],
captures: [
Expand Down
2 changes: 1 addition & 1 deletion packages/admin/admin-bundler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.16",
"compression": "^1.7.4",
"glob": "^11.0.0",
"glob": "^10.3.10",
"postcss": "^8.4.32",
"tailwindcss": "^3.3.6",
"vite": "^5.2.11"
Expand Down
1 change: 1 addition & 0 deletions packages/admin/admin-bundler/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { build } from "./lib/build"
export { develop } from "./lib/develop"
export { plugin } from "./lib/plugin"
export { serve } from "./lib/serve"

export * from "./types"
58 changes: 51 additions & 7 deletions packages/admin/admin-bundler/src/lib/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,37 @@
import react from "@vitejs/plugin-react"
import { readFileSync } from "fs"
import { rm } from "fs/promises"
import { glob } from "glob"
import path from "path"
import { UserConfig } from "vite"

export async function plugin() {
interface PluginOptions {
root: string
outDir: string
}

export async function plugin(options: PluginOptions) {
const vite = await import("vite")
const entries = await glob("src/admin/**/*.{ts,tsx,js,jsx}")
const entries = await glob(`${options.root}/src/admin/**/*.{ts,tsx,js,jsx}`)

/**
* If there is no entry point, we can skip the build
*/
if (entries.length === 0) {
return
}

const entryPoints = entries.reduce((acc, entry) => {
// Convert src/admin/routes/brands/page.tsx -> admin/routes/brands/page
const outPath = entry
.replace(/^src\//, "")
.replace(/\.(ts|tsx|js|jsx)$/, "")

acc[outPath] = path.resolve(process.cwd(), entry)
acc[outPath] = path.resolve(options.root, entry)
return acc
}, {} as Record<string, string>)

const pkg = JSON.parse(
readFileSync(path.resolve(process.cwd(), "package.json"), "utf-8")
readFileSync(path.resolve(options.root, "package.json"), "utf-8")
)
const external = new Set([
...Object.keys(pkg.dependencies || {}),
Expand All @@ -30,14 +43,22 @@ export async function plugin() {
"@medusajs/admin-sdk",
])

/**
* We need to ensure that the NODE_ENV is set to production,
* otherwise Vite will build the dev version of React.
*/
const originalNodeEnv = process.env.NODE_ENV
process.env.NODE_ENV = "production"

const pluginConfig: UserConfig = {
build: {
lib: {
entry: entryPoints,
formats: ["es"],
},
emptyOutDir: false,
minify: false,
outDir: path.resolve(process.cwd(), "dist"),
outDir: path.resolve(options.root, options.outDir),
rollupOptions: {
external: [...external],
output: {
Expand All @@ -47,11 +68,34 @@ export async function plugin() {
"react/jsx-runtime": "react/jsx-runtime",
},
preserveModules: true,
entryFileNames: `[name].js`,
entryFileNames: (chunkInfo) => {
return `${chunkInfo.name.replace(`${options.root}/`, "")}.js`
},
},
},
},
plugins: [
react(),
{
name: "clear-admin-plugin",
buildStart: async () => {
const adminDir = path.join(options.root, options.outDir, "admin")
try {
await rm(adminDir, { recursive: true, force: true })
} catch (e) {
// Directory might not exist, ignore
}
},
},
],
logLevel: "silent",
clearScreen: false,
}

await vite.build(pluginConfig)

/**
* Restore the original NODE_ENV
*/
process.env.NODE_ENV = originalNodeEnv
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ export const CreateRefundForm = ({
const paymentId = searchParams.get("paymentId")
const payments = getPaymentsFromOrder(order)
const payment = payments.find((p) => p.id === paymentId)!
const paymentAmount = (payment?.amount || 0) as number

const paymentAmount = payment.amount || 0
const form = useForm<zod.infer<typeof CreateRefundSchema>>({
defaultValues: {
amount: paymentAmount,
Expand Down Expand Up @@ -121,19 +120,32 @@ export const CreateRefundForm = ({
</Select.Trigger>

<Select.Content>
{payments.map((payment) => (
<Select.Item value={payment!.id} key={payment.id}>
<span>
{getLocaleAmount(
payment.amount as number,
payment.currency_code
)}
{" - "}
</span>
<span>{payment.provider_id}</span>
<span> - ({payment.id.replace("pay_", "")})</span>
</Select.Item>
))}
{payments.map((payment) => {
const totalRefunded = payment.refunds.reduce(
(acc, next) => next.amount + acc,
0
)

return (
<Select.Item
value={payment!.id}
key={payment.id}
disabled={
!!payment.canceled_at || totalRefunded >= payment.amount
}
>
<span>
{getLocaleAmount(
payment.amount as number,
payment.currency_code
)}
{" - "}
</span>
<span>{payment.provider_id}</span>
<span> - ({payment.id.replace("pay_", "")})</span>
</Select.Item>
)
})}
</Select.Content>
</Select>

Expand All @@ -154,16 +166,11 @@ export const CreateRefundForm = ({
<CurrencyInput
{...field}
min={0}
onChange={(e) => {
const val =
e.target.value === ""
? null
: Number(e.target.value)
onValueChange={(value) => {
const fieldValue = value ? parseInt(value) : ""

onChange(val)

if (val && !isNaN(val)) {
if (val < 0 || val > paymentAmount) {
if (fieldValue && !isNaN(fieldValue)) {
if (fieldValue < 0 || fieldValue > paymentAmount) {
form.setError(`amount`, {
type: "manual",
message: t(
Expand All @@ -175,6 +182,8 @@ export const CreateRefundForm = ({
form.clearErrors(`amount`)
}
}

onChange(fieldValue)
}}
code={order.currency_code}
symbol={getCurrencySymbol(order.currency_code)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ const UnfulfilledItemDisplay = ({
}) => {
const { t } = useTranslation()

if (order.status === "canceled") {
return
}

return (
<Container className="divide-y p-0">
<div className="flex items-center justify-between px-6 py-4">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { ArrowDownRightMini, DocumentText, XCircle } from "@medusajs/icons"
import {
AdminPayment,
AdminPaymentCollection,
HttpTypes,
} from "@medusajs/types"
import { AdminOrder, AdminPayment, HttpTypes } from "@medusajs/types"
import {
Badge,
Button,
Expand Down Expand Up @@ -58,10 +54,7 @@ export const OrderPaymentSection = ({ order }: OrderPaymentSectionProps) => {
currencyCode={order.currency_code}
/>

<Total
paymentCollections={order.payment_collections}
currencyCode={order.currency_code}
/>
<Total order={order} />
</Container>
)
}
Expand Down Expand Up @@ -195,6 +188,11 @@ const Payment = ({
const showCapture =
payment.captured_at === null && payment.canceled_at === null

const totalRefunded = payment.refunds.reduce(
(acc, next) => next.amount + acc,
0
)

return (
<div className="divide-y divide-dashed">
<div className="text-ui-fg-subtle grid grid-cols-[1fr_1fr_1fr_20px] items-center gap-x-4 px-6 py-4 sm:grid-cols-[1fr_1fr_1fr_1fr_20px]">
Expand Down Expand Up @@ -237,7 +235,10 @@ const Payment = ({
label: t("orders.payment.refund"),
icon: <XCircle />,
to: `/orders/${order.id}/refund?paymentId=${payment.id}`,
disabled: !payment.captured_at,
disabled:
!payment.captured_at ||
!!payment.canceled_at ||
totalRefunded >= payment.amount,
},
],
},
Expand Down Expand Up @@ -341,15 +342,9 @@ const PaymentBreakdown = ({
)
}

const Total = ({
paymentCollections,
currencyCode,
}: {
paymentCollections: AdminPaymentCollection[]
currencyCode: string
}) => {
const Total = ({ order }: { order: AdminOrder }) => {
const { t } = useTranslation()
const totalPending = getTotalPending(paymentCollections)
const totalPending = getTotalPending(order.payment_collections)

return (
<div>
Expand All @@ -360,20 +355,20 @@ const Total = ({

<Text size="small" weight="plus" leading="compact">
{getStylizedAmount(
getTotalCaptured(paymentCollections),
currencyCode
getTotalCaptured(order.payment_collections),
order.currency_code
)}
</Text>
</div>

{totalPending > 0 && (
{order.status !== "canceled" && totalPending > 0 && (
<div className="flex items-center justify-between px-6 py-4">
<Text size="small" weight="plus" leading="compact">
Total pending
</Text>

<Text size="small" weight="plus" leading="compact">
{getStylizedAmount(totalPending, currencyCode)}
{getStylizedAmount(totalPending, order.currency_code)}
</Text>
</div>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
AdminOrderPreview,
AdminRegion,
AdminReturn,
AdminPaymentCollection,
} from "@medusajs/types"
import {
Badge,
Expand All @@ -36,7 +37,6 @@ import {
} from "@medusajs/ui"

import { AdminReservation } from "@medusajs/types/src/http"
import { AdminPaymentCollection } from "../../../../../../../../core/types/dist/http/payment/admin/entities"
import { ActionMenu } from "../../../../../components/common/action-menu"
import { Thumbnail } from "../../../../../components/common/thumbnail"
import { useClaims } from "../../../../../hooks/api/claims"
Expand Down Expand Up @@ -309,6 +309,7 @@ const Header = ({
to: `/orders/${order.id}/edits`,
icon: <PencilSquare />,
disabled:
order.status === "canceled" ||
(orderPreview?.order_change &&
orderPreview?.order_change?.change_type !== "edit") ||
(orderPreview?.order_change?.change_type === "edit" &&
Expand Down
Loading
Loading