feat: ref codes
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2025-03-05 11:10:28 +00:00
parent c5d45b0843
commit d05c69af9c
4 changed files with 44 additions and 3 deletions

View File

@ -187,12 +187,13 @@ export class LNVpsApi {
return data;
}
async orderVm(template_id: number, image_id: number, ssh_key_id: number) {
async orderVm(template_id: number, image_id: number, ssh_key_id: number, ref_code?: string) {
const { data } = await this.#handleResponse<ApiResponse<VmInstance>>(
await this.#req("/api/v1/vm", "POST", {
template_id,
image_id,
ssh_key_id,
ref_code
}),
);
return data;

View File

@ -1,7 +1,10 @@
import { Link, Outlet } from "react-router-dom";
import LoginButton from "../components/login-button";
import { saveRefCode } from "../ref";
export default function Layout() {
saveRefCode();
return (
<div className="w-[700px] mx-auto m-2 p-2">
<div className="flex items-center justify-between mb-4">

View File

@ -8,6 +8,7 @@ import classNames from "classnames";
import VpsResources from "../components/vps-resources";
import OsImageName from "../components/os-image-name";
import SSHKeySelector from "../components/ssh-keys";
import { clearRefCode, getRefCode } from "../ref";
export default function OrderPage() {
const { state } = useLocation();
@ -29,7 +30,9 @@ export default function OrderPage() {
setOrderError("");
try {
const newVm = await login.api.orderVm(template.id, useImage, useSshKey);
const ref = getRefCode();
const newVm = await login.api.orderVm(template.id, useImage, useSshKey, ref?.code);
clearRefCode();
navigate("/vm/renew", {
state: newVm,
});

34
src/ref.ts Normal file
View File

@ -0,0 +1,34 @@
export interface RefCode {
code: string;
saved: number;
}
export function saveRefCode() {
const search = new URLSearchParams(window.location.search);
const code = search.get("ref");
if (code) {
// save or overwrite new code from landing
window.localStorage.setItem("ref", JSON.stringify({
code,
saved: Math.floor(new Date().getTime() / 1000)
}));
window.location.search = "";
}
}
export function getRefCode() {
const ref = window.localStorage.getItem("ref");
if (ref) {
const refObj = JSON.parse(ref) as RefCode;
const now = Math.floor(new Date().getTime() / 1000);
// treat code as stale if > 7days old
if (Math.abs(refObj.saved - now) > 604800) {
window.localStorage.removeItem("ref");
}
return refObj;
}
}
export function clearRefCode() {
window.localStorage.removeItem("ref");
}