A calculator with prices from Seamlet
A calculator is the site’s code: what to ask the visitor and how to count is the developer’s decision. The prices in it are content: the owner changes them in Seamlet, publishes, and the calculator counts anew.
It needs @seamlet/astro 1.5 or newer.
Rates in the schema
Section titled “Rates in the schema”import { defineSchema, ratesField } from "@seamlet/astro/schema";
export const schema = defineSchema({ rates: ratesField(),});ratesField() is a list of rates: «Что считаем» (What is counted), «Единица» (Unit), «Цена за единицу, ₽» (Price per unit, ₽). The owner edits it like any list — as a table too. In the initial content give the rates fixed ids: the calculator’s code finds the rate it needs by them.
rates: [ { id: "timber", name: "Брус 150×150", unit: "м³", price: 32000 }, { id: "roof", name: "Кровля", unit: "м²", price: 1250 },],Counting
Section titled “Counting”The page gives the rates to the script in an attribute, and the script counts with estimateOf: the sum of the amounts by their rates, in whole rubles. A rate without a price and an unknown amount add nothing.
---import type { Rate } from "@seamlet/astro/schema";
interface Props { rates: readonly Rate[];}
const { rates } = Astro.props;---
<form class="calculator" data-rates={JSON.stringify(rates)}> <label> Брус, м³ <input name="timber" type="number" min="0" step="0.1" /> </label> <label> Кровля, м² <input name="roof" type="number" min="0" /> </label> <output name="total">0 ₽</output></form>
<script> import { estimateOf, type Rate } from "@seamlet/astro/schema";
for (const form of document.querySelectorAll<HTMLFormElement>( ".calculator", )) { const rates = JSON.parse(form.dataset.rates ?? "[]") as Rate[]; form.addEventListener("input", () => { const amounts = Object.fromEntries( [...new FormData(form)].map(([id, value]) => [id, Number(value)]), ); const total = estimateOf(rates, amounts); form.elements.namedItem("total")!.textContent = `${total.toLocaleString("ru-RU")} ₽`; }); }</script>The sum in the request
Section titled “The sum in the request”For the owner to see the estimate in a request, write it into a field of the request form — for example, into «Комментарий» (Comment, a requestLongText named comment) — every time the sum changes. The form sends the field as usual, and the visitor sees what goes into the request and can add their own words.
// in the calculator's "input" listener, after counting total:const request = document.querySelector<HTMLFormElement>(".seamlet-form");const comment = request?.elements.namedItem("comment");if (comment instanceof HTMLTextAreaElement) { comment.value = `Расчёт на сайте: ${total.toLocaleString("ru-RU")} ₽`;}