zc2 0.0.52

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
import { useEffect, useState } from "react";
import type { Overview } from "../lib/overview";
import type { AgentHook } from "../lib/useAgent";
import { MACHINE, perHour, yen } from "../lib/format";
import { Button, Field, Go, Notice } from "../components/ui";
import { Card, CardGrid, CardHead, Facts, Section, Tile } from "../components/kit";

/** What this machine's time costs: its own price and the account default,
 * one card each, on the Earnings screen. How much it lends is on Resources;
 * whether it lends at all is the Sharing switch in the sidebar.
 * `prefill` is a hub proposal from a confirmed `zakuro://share/budget` link:
 * it fills the form, and nothing is saved until the owner saves. */
export function Price({ hook, ov, prefill, onPrefillDone, onResources }: { hook: AgentHook; ov: Overview | null; prefill?: Record<string, unknown> | null; onPrefillDone?: () => void; onResources: () => void }) {
  const [price, setPrice] = useState<string>("");
  const [defaultPrice, setDefaultPrice] = useState<string>("");
  const proposed = typeof prefill?.price_per_hour === "number" ? (prefill.price_per_hour as number) : null;
  useEffect(() => {
    if (!ov) return;
    setDefaultPrice(ov.prices.accountDefault?.toString() ?? "");
    // Reset the inputs only when the agent's values change, not on every poll.
  }, [ov?.prices.accountDefault]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    // A hub proposal owns the field until it is saved or dismissed: the
    // agent's price arriving (or moving) must not put back the old value.
    if (!ov || proposed !== null) return;
    setPrice(ov.prices.thisNode.perHour?.toString() ?? "");
  }, [ov?.prices.thisNode.perHour, proposed]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    // Keyed on the prefill object, not the number: a second link with the
    // same proposal fills the field again.
    if (proposed !== null) setPrice(String(proposed));
  }, [prefill]); // eslint-disable-line react-hooks/exhaustive-deps

  const parse = (s: string) => (s.trim() === "" ? null : Number(s));
  const valid = (s: string) => {
    const n = parse(s);
    return n === null || (ov !== null && Number.isFinite(n) && n >= ov.prices.min && n <= ov.prices.max);
  };

  const t = ov?.prices.thisNode;
  return (
    <Section title="Your price" aside={ov ? `per hour, between ${yen(ov.prices.min)} and ${yen(ov.prices.max)}` : "per hour"}>
      {prefill && (
        <Notice title="Proposed from the hub" onClose={onPrefillDone}>
          {proposed !== null ? `This ${MACHINE}'s price is filled in at ¥${proposed}/h. Review it, then Save to apply.` : "The link proposed no change this zc can apply yet."}
          {Object.keys(prefill).some((k) => k !== "price_per_hour") && (
            <>
              {" "}
              The link also proposed limits: set those on <Go onClick={onResources}>Resources</Go>
            </>
          )}
        </Notice>
      )}
      <CardGrid min={300}>
        <PriceCard
          eyebrow={`This ${MACHINE}`}
          title={ov?.thisNode.name ?? `This ${MACHINE}`}
          now={perHour(t?.effective)}
          note={!t ? "Waiting for the agent" : t.state === "inherited" ? "Using the account default" : t.state === "disabled" ? "Not offered right now" : t.state === "mixed" ? "Its workers have different prices" : "Its own price"}
          hint="Leave empty to use the account default"
          value={price}
          onChange={setPrice}
          valid={valid(price)}
          disabled={!ov || hook.busy}
          accent={proposed !== null}
          onSave={() => {
            hook.setPrice("device", parse(price));
            onPrefillDone?.();
          }}
        />
        <PriceCard
          eyebrow="Account default"
          title="Every node without its own price"
          now={perHour(ov?.prices.accountDefault)}
          note={ov ? (ov.prices.accountDefault == null ? "None set: the market price applies" : "Applies to all your nodes") : "Waiting for the agent"}
          hint="Leave empty for none"
          value={defaultPrice}
          onChange={setDefaultPrice}
          valid={valid(defaultPrice)}
          disabled={!ov || hook.busy}
          onSave={() => hook.setPrice("default", parse(defaultPrice))}
        />
      </CardGrid>
    </Section>
  );
}

function PriceCard(props: { eyebrow: string; title: string; now: string; note: string; hint: string; value: string; onChange: (s: string) => void; valid: boolean; disabled: boolean; accent?: boolean; onSave: () => void }) {
  return (
    <Card accent={props.accent}>
      <CardHead tile={<Tile icon="tag" />} eyebrow={props.eyebrow} title={props.title} />
      <div className="flex items-baseline gap-2">
        <b className="tnum text-[24px] font-semibold tracking-tight">{props.now}</b>
        <span className="text-[11.5px] text-fg-dim">{props.note}</span>
      </div>
      <form
        className="flex items-center gap-1.5"
        onSubmit={(e) => {
          e.preventDefault();
          if (!props.disabled && props.valid) props.onSave();
        }}
      >
        <span className="text-fg-dim">¥</span>
        <Field aria-label={`${props.eyebrow} price per hour`} inputMode="decimal" placeholder="new price" value={props.value} invalid={!props.valid} onChange={(e) => props.onChange(e.target.value)} className="w-28" />
        <span className="text-[12px] text-fg-dim">/ h</span>
        <Button type="submit" size="sm" variant="primary" className="ml-auto" disabled={props.disabled || !props.valid}>
          Save
        </Button>
      </form>
      <Facts>{props.valid ? props.hint : "Outside the allowed range"}</Facts>
    </Card>
  );
}