93 lines
2.5 KiB
TypeScript
93 lines
2.5 KiB
TypeScript
// routes/api/payments/set_auto_pay.ts
|
|
import { define } from "../../../utils.ts";
|
|
import { setAutoPayment } from "../../../services/paymentService.ts";
|
|
import { SessionCookie } from "../../auth/callback.ts";
|
|
|
|
export const handler = define.handlers({
|
|
async POST(ctx) {
|
|
try {
|
|
const stateData: SessionCookie = ctx.state.data;
|
|
const user_id = stateData.user_id;
|
|
|
|
if (!user_id) {
|
|
return new Response(
|
|
JSON.stringify({
|
|
error: "User not authenticated",
|
|
}),
|
|
{
|
|
status: 401,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
}
|
|
|
|
const contentType = ctx.req.headers.get("content-type") || "";
|
|
let data: Record<string, string> = {};
|
|
|
|
// Handle both JSON and form data
|
|
if (contentType.includes("application/json")) {
|
|
const jsonData = await ctx.req.json();
|
|
data = jsonData;
|
|
} else {
|
|
const formData = await ctx.req.formData();
|
|
data = {
|
|
lease_id: formData.get("lease_id")?.toString() || "",
|
|
payment_method_id: formData.get("payment_method_id")?.toString() ||
|
|
"",
|
|
};
|
|
}
|
|
|
|
const lease_id = data.lease_id as string;
|
|
const payment_method_id = data.payment_method_id as string;
|
|
|
|
if (!lease_id) {
|
|
return new Response(
|
|
JSON.stringify({
|
|
error: "Lease ID is required",
|
|
}),
|
|
{
|
|
status: 400,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
}
|
|
|
|
if (!payment_method_id) {
|
|
return new Response(
|
|
JSON.stringify({
|
|
error: "Payment method ID is required",
|
|
}),
|
|
{
|
|
status: 400,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
}
|
|
|
|
const result = await setAutoPayment(lease_id, user_id, payment_method_id);
|
|
|
|
return new Response(
|
|
JSON.stringify({
|
|
success: true,
|
|
lease: result[0],
|
|
}),
|
|
{
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
} catch (e) {
|
|
console.error("Error setting auto payment:", e);
|
|
return new Response(
|
|
JSON.stringify({
|
|
error: e instanceof Error ? e.message : "Failed to set auto payment",
|
|
}),
|
|
{
|
|
status: 500,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
}
|
|
},
|
|
});
|