ekomat-mobilnoe-prilozhenie/web/app.js

456 lines
20 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* global __API_ORIGIN__, __SENTRY_DSN__, __SENTRY_RELEASE__, __SENTRY_ENVIRONMENT__ */
import { Capacitor } from '@capacitor/core'
import { App } from '@capacitor/app'
import * as Sentry from '@sentry/browser'
import { BrowserQRCodeReader } from '@zxing/browser'
import { languages, message } from './strings.js'
Sentry.init({
dsn: __SENTRY_DSN__, release: __SENTRY_RELEASE__, environment: __SENTRY_ENVIRONMENT__,
sendDefaultPii: false
})
const root = document.getElementById('app')
const state = {
lang: localStorage.getItem('ekomat.language') ?? 'ru',
token: localStorage.getItem('ekomat.access'),
view: 'home', machines: [], info: null, products: [], error: null,
pending: false, destination: 'home', quote: null, ticketOperation: null
}
if (!Object.hasOwn(languages, state.lang)) state.lang = 'ru'
const copy = (key) => message(state.lang, key)
const money = (number) => new Intl.NumberFormat(state.lang === 'kk' ? 'kk-KZ' : state.lang)
.format(number) + ' ₸'
const when = (time) => new Intl.DateTimeFormat(state.lang, { dateStyle: 'medium', timeStyle: 'short' }).format(time)
function uid() {
if (typeof crypto.randomUUID === 'function') return crypto.randomUUID()
return Array.from(crypto.getRandomValues(new Uint8Array(24)), (byte) => byte.toString(16).padStart(2, '0')).join('')
}
const requestKeys = new Map()
const mockEventIds = new Map()
let camera = null
function node(tag, attributes = {}, ...children) {
const element = document.createElement(tag)
for (const [key, value] of Object.entries(attributes)) {
if (key.startsWith('on')) element.addEventListener(key.slice(2), value)
else if (value !== false && value !== null && value !== undefined) element.setAttribute(key, value === true ? '' : value)
}
element.append(...children.flat(Infinity).filter((child) => child !== null && child !== undefined && child !== false))
return element
}
const text = (tag, key, attrs) => node(tag, attrs, copy(key))
const button = (key, action, style = 'primary', extra = {}) =>
text('button', key, { type: 'button', class: 'button ' + style, onclick: action, disabled: state.pending, ...extra })
const label = (key, field) => node('label', { class: 'field' }, copy(key), field)
const pill = (status) => text('span', status, { class: 'pill ' + status })
const section = (title, ...children) => node('section', { class: 'panel' }, text('h2', title), children)
async function api(path, payload) {
const headers = { Accept: 'application/json' }
if (state.token) headers.Authorization = 'Bearer ' + state.token
const options = { headers, signal: AbortSignal.timeout(10_000) }
const signature = path + JSON.stringify(payload)
if (payload !== undefined) {
options.method = 'POST'
options.body = JSON.stringify(payload)
headers['Content-Type'] = 'application/json'
if (!requestKeys.has(signature)) requestKeys.set(signature, uid())
headers['Idempotency-Key'] = requestKeys.get(signature)
}
let response
try {
response = await fetch(__API_ORIGIN__ + '/v1/' + path, options)
} catch {
throw new Error('noConnection')
}
const result = await response.json()
requestKeys.delete(signature)
if (!response.ok) throw new Error(result.error ?? 'stale')
return result
}
function setToken(token) {
state.token = token
requestKeys.clear()
mockEventIds.clear()
if (token) localStorage.setItem('ekomat.access', token)
else {
localStorage.removeItem('ekomat.access')
state.info = null
state.products = []
state.challenge = null
state.quote = null
state.focusOrder = null
state.ticketOperation = null
}
}
async function mockEvent(path, payload) {
const signature = path + JSON.stringify(payload)
if (!mockEventIds.has(signature)) mockEventIds.set(signature, uid())
try {
await api(path, { ...payload, eventId: mockEventIds.get(signature) })
mockEventIds.delete(signature)
} catch (error) {
if (error.message !== 'noConnection') mockEventIds.delete(signature)
throw error
}
}
async function refresh() {
state.machines = (await api('machines')).machines
state.info = state.token ? await api('overview') : null
if (state.view === 'shop' && state.info?.machineId) state.products = (await api('products')).products
}
async function act(action) {
if (state.pending) return
state.pending = true
state.error = null
render()
try {
await action()
} catch (error) {
state.error = error.message
if (state.error === 'signInRequired') {
setToken(null)
state.view = 'login'
}
} finally {
state.pending = false
render()
}
}
function go(view) {
return act(async () => {
if (!state.token && ['intake', 'shop', 'history', 'pair'].includes(view)) {
state.destination = view
state.view = 'login'
} else state.view = view
await refresh()
window.scrollTo({ top: 0, behavior: 'instant' })
})
}
function activeMachine() {
return state.machines.find((machine) => machine.id === state.info?.machineId)
}
function machineCard(machine) {
const [latitude, longitude] = machine.coordinates
return node('article', { class: 'machine' },
node('span', { class: 'machine-marker', 'aria-hidden': true }, '⌾'),
node('div', { class: 'machine-copy' },
node('h3', {}, machine.names[state.lang]), node('p', {}, machine.addresses[state.lang])),
pill(machine.status),
node('a', { href: 'https://www.openstreetmap.org/?mlat=' + latitude + '&mlon=' + longitude,
rel: 'noopener noreferrer', target: '_blank', class: 'route' }, copy('route'), ' ↗'))
}
function balanceCard() {
const amount = state.info?.wallet.available ?? 0
return node('aside', { class: 'balance-card' }, text('p', 'balance'),
node('strong', {}, state.info ? money(amount) : '—'),
state.info?.wallet.held > 0 && node('small', {}, copy('held'), ' · ', money(state.info.wallet.held)))
}
function actionCard(key, description, icon) {
return node('button', { class: 'action-card ' + key, type: 'button', disabled: state.pending, onclick: () => go(key) },
node('span', { class: 'action-icon', 'aria-hidden': true }, icon),
node('span', {}, node('strong', {}, copy(key)), text('small', description)),
node('span', { class: 'arrow', 'aria-hidden': true }, '↗'))
}
function home() {
const machine = activeMachine() ?? state.machines[0]
return [
node('section', { class: 'hero' },
node('div', {}, text('h1', 'welcome'), text('p', 'welcomeLead'),
!state.token && button('signIn', () => go('login'))),
balanceCard()),
node('section', { class: 'actions' }, actionCard('intake', 'intakeLead', '♻'), actionCard('shop', 'shopLead', '◉')),
machine && section(activeMachine() ? 'paired' : 'nearby', machineCard(machine),
button('machines', () => go('machines'), 'subtle')),
section('recent', records(3))
]
}
function locationList() {
return [text('h1', 'machines'), state.machines.map(machineCard),
button('pair', () => { state.destination = 'home'; go('pair') })]
}
function mockNumber() {
const stored = localStorage.getItem('ekomat.mockNumber')
if (stored) return stored
const random = crypto.getRandomValues(new Uint32Array(1))[0] % 1_000_000
const generated = '+77000' + String(random).padStart(6, '0')
localStorage.setItem('ekomat.mockNumber', generated)
return generated
}
function mockProfileKey() {
const stored = localStorage.getItem('ekomat.mockProfile')
if (stored) return stored
const key = uid() + uid()
localStorage.setItem('ekomat.mockProfile', key)
return key
}
function login() {
const phone = node('input', { type: 'tel', required: true, value: mockNumber() })
const pin = node('input', { inputmode: 'numeric', pattern: '[0-9]{6}', autocomplete: 'one-time-code', required: true })
const accepted = node('input', { type: 'checkbox', required: true })
const challenge = state.challenge
const submit = node('button', { type: 'submit', class: 'button primary', disabled: state.pending },
copy(challenge ? 'signIn' : 'getCode'))
return node('section', { class: 'panel narrow' }, text('h1', 'signIn'), text('p', 'signInLead'),
node('form', { onsubmit: (event) => {
event.preventDefault()
const input = challenge ? { challengeId: challenge.challengeId, otp: pin.value, accepted: accepted.checked }
: { phone: phone.value, mockProfileKey: mockProfileKey() }
act(async () => {
if (!challenge) state.challenge = await api('auth/otp/request', input)
else {
const { token } = await api('auth/otp/verify', input)
setToken(token)
state.challenge = null
state.view = state.destination
await refresh()
}
})
} }, challenge ? [
node('p', { class: 'demo-code' }, copy('demoCode'), ' ', node('strong', {}, challenge.mockOtp)),
label('otp', pin), node('label', { class: 'check' }, accepted, copy('consent')),
text('small', 'terms'), submit, button('changeNumber', () => { state.challenge = null; render() }, 'subtle')
] : [label('phone', phone), submit]))
}
async function connect(scanToken) {
await api('machines/pair', { scanToken })
state.view = state.destination === 'pair' ? 'home' : state.destination
await refresh()
}
function pairing() {
const input = node('input', { required: true, autocomplete: 'off' })
const video = node('video', { playsinline: true, hidden: true, muted: true })
async function scan() {
if (!navigator.mediaDevices) {
state.error = 'noCamera'
render()
return
}
try {
video.hidden = false
camera = await new BrowserQRCodeReader().decodeFromConstraints({ video: { facingMode: 'environment' } }, video,
(result, _error, controls) => {
if (!result || !video.isConnected) return
controls.stop()
act(() => connect(result.getText()))
})
if (!video.isConnected) camera.stop()
} catch {
state.error = 'noCamera'
render()
}
}
return node('section', { class: 'panel narrow' }, text('h1', 'pair'), text('p', 'pairLead'),
button('qr', scan, 'secondary'), video,
node('form', { onsubmit: (event) => {
event.preventDefault()
const value = input.value.trim()
act(() => connect(value))
} }, label('qrInput', input), node('button', { type: 'submit', class: 'button secondary', disabled: state.pending }, copy('connect'))),
button('mockConnect', () => act(() => connect('ekomat:demo:garden'))))
}
function requirePair(view) {
return node('section', { class: 'panel' }, text('p', 'chooseMachine'),
button('pair', () => { state.destination = view; go('pair') }))
}
function intake() {
const session = state.info?.intake.find(({ status }) => status === 'active')
const machine = activeMachine()
if (!session && !machine) return [text('h1', 'intake'), requirePair('intake')]
const tariffs = session?.tariffs ?? machine.tariffs
function record(material) {
return act(async () => {
await mockEvent('intake-sessions/' + session.id + '/mock-event', { material })
await refresh()
})
}
return [text('h1', 'intake'), text('p', 'intakeInstructions'),
node('div', { class: 'actions' }, ['pet', 'aluminium'].map((material) =>
node('article', { class: 'panel metric' }, text('h2', material),
node('strong', {}, money(tariffs[material])), session && node('span', {},
'× ', String(session.items.filter((item) => item.material === material).length))))),
session ? [
section('earned', node('strong', { class: 'value' }, money(session.items.reduce((sum, item) => sum + item.amount, 0))),
session.items.at(-1)?.material === 'rejected' && text('p', 'rejectedReason')),
section('mockControls', node('div', { class: 'button-row' },
['pet', 'aluminium', 'rejected'].map((material) => button(material, () => record(material), 'secondary')))),
button('closeIntake', () => record('close'))
] : button('startIntake', () => act(async () => { await api('intake-sessions', {}); await refresh() }))]
}
function orderCard(order) {
const route = 'orders/' + order.id
const confirmed = node('input', { type: 'checkbox', required: true })
function mock(outcome, actualMl) {
return act(async () => {
await mockEvent(route + '/mock-event', { commandId: order.commandId, outcome, actualMl })
await refresh()
})
}
return section(order.productId, pill(order.status),
node('p', {}, copy('volume'), ' · ', String(order.volumeMl), ' ', copy('ml')),
order.status === 'ready' && node('form', { onsubmit: (event) => {
event.preventDefault()
if (confirmed.checked) act(async () => { await api(route + '/dispense', { confirmedContainerReady: true }); await refresh() })
} }, text('p', 'safety'), node('label', { class: 'check' }, confirmed, copy('confirmContainer')),
node('button', { type: 'submit', class: 'button primary', disabled: state.pending }, copy('startDispense'))),
order.status === 'dispensing' && section('mockControls', node('div', { class: 'button-row' },
button('mockComplete', () => mock('measured', order.volumeMl), 'secondary'),
button('mockPartial', () => mock('measured', Math.floor(order.volumeMl / 2)), 'secondary'),
button('mockEmpty', () => mock('measured', 0), 'secondary'),
button('mockLost', () => mock('lost'), 'secondary'))),
typeof order.charged === 'number' && node('p', {}, copy('actual'), ' · ', String(order.actualMl), ' ', copy('ml'),
' / ', copy('charged'), ' · ', money(order.charged)),
['completed', 'partial', 'reconciliation', 'refunded'].includes(order.status) &&
button('reconcile', () => { state.ticketOperation = order.id; go('help') }, 'secondary'),
['completed', 'partial', 'refunded'].includes(order.status) && button('chooseAgain', () => {
state.focusOrder = null
state.quote = null
render()
}, 'subtle'))
}
function shop() {
if (!state.info?.machineId) return [text('h1', 'shop'), requirePair('shop')]
const orders = state.info.orders
const order = orders.find((entry) => ['ready', 'dispensing', 'reconciliation'].includes(entry.status)) ??
orders.find((entry) => entry.id === state.focusOrder)
if (order) return [text('h1', 'shop'), orderCard(order)]
if (state.quote) {
const quote = state.quote
const missing = quote.price - state.info.wallet.available
return [text('h1', 'shop'), section(quote.productId,
node('p', {}, String(quote.volumeMl), ' ', copy('ml')),
node('p', {}, copy('total'), ' · ', node('strong', {}, money(quote.price))),
node('p', {}, copy(missing > 0 ? 'missing' : 'remaining'), ' · ', money(Math.abs(missing))),
missing > 0 ? button('intake', () => go('intake')) : button('pay', () => act(async () => {
const { order } = await api('orders', { quoteId: quote.id })
state.focusOrder = order.id
state.quote = null
await refresh()
})),
button('chooseAgain', () => { state.quote = null; render() }, 'subtle'))]
}
const categories = state.products.filter((product) => product.volumes.length)
return [text('h1', 'shop'), categories.length ? categories.map((product) => {
const volume = node('select', {}, product.volumes.map((value) =>
node('option', { value }, String(value), ' ', copy('ml'))))
return section(product.id, node('p', {}, money(product.pricePerLitre), ' ', copy('litre')), text('p', 'safety'),
label('volume', volume), button('quote', () => {
const volumeMl = Number(volume.value)
act(async () => { state.quote = (await api('orders/quote', { productId: product.id, volumeMl })).quote })
}))
}) : text('p', 'noProducts')]
}
function records(limit) {
const ledger = state.info?.ledger.filter((entry) => !state.historyFilter || limit !== Infinity ||
entry.type === state.historyFilter).slice(0, limit)
if (!ledger?.length) return text('p', 'empty')
return node('ul', { class: 'ledger' }, ledger.map((entry) => {
const amount = entry.type === 'purchase' ? entry.held : entry.available
const machine = state.machines.find((item) => item.id === entry.machineId)
const order = state.info.orders.find((item) => item.id === entry.operationId)
return node('li', {}, node('div', {},
node('strong', {}, copy(entry.type), entry.productId || entry.material ? ' · ' + copy(entry.productId ?? entry.material) : ''),
node('small', {}, when(entry.at), machine ? ' · ' + machine.names[state.lang] : ''),
order && pill(order.status),
node('details', {}, text('summary', 'details'), node('code', {}, entry.operationId))),
node('span', { class: amount > 0 ? 'positive' : 'amount' }, amount > 0 ? '+' : '', money(amount)))
}))
}
function help() {
const info = state.info
const description = node('textarea', { required: true, minlength: 3, maxlength: 1000, rows: 3 })
const operations = [...info?.orders ?? [], ...info?.intake ?? []]
const choice = node('select', {}, node('option', { value: '' }, copy('help')),
operations.map((entry) => node('option', { value: entry.id, selected: entry.id === state.ticketOperation },
copy(entry.productId ?? 'intake'), ' · ', when(entry.createdAt ?? entry.updatedAt))))
return [text('h1', 'help'),
section('faq', text('p', 'intakeInstructions'), text('p', 'safety')),
info && node('form', { class: 'panel', onsubmit: (event) => {
event.preventDefault()
const payload = { message: description.value, operationId: choice.value || undefined }
act(async () => { await api('support/tickets', payload); state.ticketOperation = null; await refresh() })
} }, choice, label('message', description),
node('button', { class: 'button primary', type: 'submit', disabled: state.pending }, copy('submit'))),
info && section('tickets', info.tickets.length ? info.tickets.map((ticket) =>
node('article', { class: 'ticket' }, pill(ticket.status), node('p', {}, ticket.message),
node('details', {}, text('summary', 'details'), node('code', {}, ticket.id)))) : text('p', 'noTickets')),
section('consent', text('p', 'terms'),
info && button('logout', () => act(async () => {
await api('auth/logout', {})
setToken(null)
state.view = 'home'
await refresh()
}), 'secondary'))]
}
function history() {
const filter = node('select', { onchange: (event) => { state.historyFilter = event.target.value; render() } },
[['', 'all'], ['credit', 'credit'], ['hold', 'hold'], ['purchase', 'purchase'], ['release', 'release']]
.map(([value, key]) => text('option', key, { value, selected: value === (state.historyFilter ?? '') })))
return [text('h1', 'history'), balanceCard(), node('section', { class: 'panel' }, label('filter', filter), records(Infinity))]
}
const views = { home, login, machines: locationList, pair: pairing, intake, shop, help,
history }
const navItems = { home: '⌂', machines: '⌖', history: '◷', help: '?' }
function render() {
camera?.stop()
camera = null
document.documentElement.lang = state.lang
document.title = copy('brand')
root.replaceChildren(
node('header', { class: 'header' }, node('div', { class: 'header-inner' },
node('button', { class: 'brand', type: 'button', disabled: state.pending, onclick: () => go('home') },
node('span', { class: 'brand-mark', 'aria-hidden': true }, 'e'), copy('brand')),
node('div', { class: 'header-actions' }, text('span', 'demo', { class: 'demo' }),
node('select', { 'aria-label': copy('language'), onchange: (event) => {
state.lang = event.target.value
localStorage.setItem('ekomat.language', state.lang)
render()
} }, Object.entries(languages).map(([code, title]) =>
node('option', { value: code, selected: code === state.lang }, title)))))),
node('main', { class: 'content', 'aria-busy': state.pending ? 'true' : 'false' },
state.view === 'home' && text('p', 'demoInfo', { class: 'demo-info' }),
state.error && node('aside', { class: 'notice', role: 'alert' }, copy(state.error),
button('refresh', () => act(refresh), 'subtle')),
views[state.view]()),
node('nav', { class: 'bottom-nav', 'aria-label': copy('home') },
Object.entries(navItems).map(([key, icon]) =>
node('button', { type: 'button', onclick: () => go(key), disabled: state.pending, 'aria-current': state.view === key ? 'page' : null },
node('span', { 'aria-hidden': true }, icon), copy(key)))))
}
act(refresh)
window.addEventListener('online', () => act(refresh))
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') act(refresh)
})
if (Capacitor.isNativePlatform()) {
App.addListener('appStateChange', ({ isActive }) => { if (isActive) act(refresh) })
} else if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js').catch(() => {})