docs
Tutorial: peddemo

Código Completo

Todos os arquivos do robô do peddemo em Python (Playwright) e Node (puppeteer-core), prontos para copiar e rodar.

Os arquivos completos do tutorial, na ordem em que aparecem na árvore. Copie para uma pasta, crie o .env a partir do .env.example, instale as dependências e rode. O passo a passo para rodar está em Rodando.

Configuração

requirements.txt
hobots>=4.3,<5
playwright>=1.40
python-dotenv>=1.0
.env.example
# Client Secret do agente (Central → Configurações → agente → credenciais)
HOBOTS_CLIENT_SECRET=
# Nome desta instância na Central. Sem ela, o SDK usa o nome do computador.
HOBOTS_INSTANCE_ID=
# development | testing | staging | production (padrão: production)
HOBOTS_ENVIRONMENT=development

PEDDEMO_BASE_URL=http://localhost:3000
PEDDEMO_EMAIL=
PEDDEMO_PASSWORD=

# true = Chrome sem janela; false = você vê o robô trabalhando
HEADLESS=false
package.json
{
  "name": "peddemo-criar-pedidos",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "tsx index.ts"
  },
  "dependencies": {
    "chrome-paths": "^1.0.1",
    "dotenv": "^16.5.0",
    "hobots": "^4.3.0",
    "puppeteer-core": "^24.35.0"
  },
  "devDependencies": {
    "@types/node": "^20.12.11",
    "tsx": "^4.21.0",
    "typescript": "^5.7.3"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "noEmit": true,
    "types": ["node"]
  },
  "include": ["index.ts", "src"]
}
.env.example
# Client Secret do agente (Central → Configurações → agente → credenciais)
HOBOTS_CLIENT_SECRET=
# Nome desta instância na Central. Sem ela, o SDK usa o nome do computador.
HOBOTS_INSTANCE_ID=
# development | testing | staging | production (padrão: production)
HOBOTS_ENVIRONMENT=development

PEDDEMO_BASE_URL=http://localhost:3000
PEDDEMO_EMAIL=
PEDDEMO_PASSWORD=

# true = Chrome sem janela; false = você vê o robô trabalhando
HEADLESS=false

Entrada

bot.py
"""Agente peddemo-criar-pedidos: cria pedidos aleatórios no peddemo a cada trabalho."""

import signal
import threading

from dotenv import load_dotenv

import hobots
from peddemo.handler import criar_pedidos

# Suba a cada versão publicada: a Central mostra em que release cada erro aconteceu
RELEASE = "peddemo-criar-pedidos@0.1.0"

# Antes do register: o SDK lê HOBOTS_CLIENT_SECRET, HOBOTS_INSTANCE_ID e HOBOTS_ENVIRONMENT do ambiente
load_dotenv()

# Ctrl-C (SIGINT) e SIGTERM só avisam a thread principal, que encerra o SDK com calma
parar = threading.Event()
signal.signal(signal.SIGINT, lambda *_: parar.set())
signal.signal(signal.SIGTERM, lambda *_: parar.set())

hobots.register(
    criar_pedidos,
    release=RELEASE,
    machine_metrics=True,
    # Colunas da aba "itens" na Central: chaves do payload de cada pedido (peddemo/items.py)
    items={
        "columns": [
            {"key": "indice", "label": "Nº"},
            {"key": "cliente", "label": "Cliente"},
            {"key": "tipo", "label": "Tipo"},
            {"key": "forma_pagamento", "label": "Pagamento"},
            {"key": "itens_resumo", "label": "Itens"},
            {"key": "quantidade_itens", "label": "Qtd. itens"},
        ]
    },
)

print("peddemo-criar-pedidos aguardando trabalhos (Ctrl-C para sair)...")

while not parar.wait(1):  # o timeout mantém o Ctrl-C responsivo também no Windows
    pass

hobots.close(15_000)  # espera o trabalho em andamento, para o heartbeat e envia o que falta
peddemo/__init__.py
"""Robô do peddemo: login, criação de pedidos e o que vai para a Central."""
index.ts
import 'dotenv/config'; // antes de tudo: o SDK lê HOBOTS_* do ambiente no register
import hobots from 'hobots';

import { criarPedidos, type BotParams } from './src/handler';

// Suba a cada versão publicada: a Central mostra em que release cada erro aconteceu
const RELEASE = 'peddemo-criar-pedidos@0.1.0';

hobots.register<BotParams>(criarPedidos, {
  release: RELEASE,
  machineMetrics: true,
  // Colunas da aba "itens" na Central: chaves do payload de cada pedido (src/items.ts)
  items: {
    columns: [
      { key: 'indice', label: 'Nº' },
      { key: 'cliente', label: 'Cliente' },
      { key: 'tipo', label: 'Tipo' },
      { key: 'forma_pagamento', label: 'Pagamento' },
      { key: 'itens_resumo', label: 'Itens' },
      { key: 'quantidade_itens', label: 'Qtd. itens' },
    ],
  },
});

console.log('peddemo-criar-pedidos aguardando trabalhos (Ctrl-C para sair)...');

// Ctrl-C (SIGINT) e SIGTERM: espera o trabalho em andamento, para o heartbeat e envia o que falta
const shutdown = (): void => {
  void hobots.close(15_000).then(() => process.exit(0));
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

Handler

peddemo/handler.py
"""O trabalho do agente: entra no peddemo e cria `quantidade_pedidos` pedidos."""

from __future__ import annotations

import os
from typing import Any, Dict

from playwright.sync_api import Page

import hobots

from .browser import launch_browser, screenshot
from .errors import AuthError, OrderError
from .items import pedido_item_id, pedido_payload
from .login import login
from .orders import create_random_order


def criar_pedidos(params: Dict[str, Any], ctx: hobots.RunContext) -> None:
    quantidade = _quantidade(params)
    base_url = os.environ.get("PEDDEMO_BASE_URL", "http://localhost:3000").rstrip("/")
    email = os.environ.get("PEDDEMO_EMAIL", "")
    password = os.environ.get("PEDDEMO_PASSWORD", "")
    headless = os.environ.get("HEADLESS") == "true"
    if not email or not password:
        raise RuntimeError("PEDDEMO_EMAIL e PEDDEMO_PASSWORD precisam estar configurados no .env.")

    ctx.log.info(f"Criando {quantidade} pedido(s) em {base_url}...")
    criados = 0
    with launch_browser(headless) as page:
        _login(ctx, page, base_url, email, password)

        # barra de progresso na Central: percentual e tempo restante estimado
        ctx.progress.total(quantidade)

        for index in range(1, quantidade + 1):
            ctx.raise_if_canceled()  # cancelado na Central? para antes de começar outro pedido
            if _criar_pedido(ctx, page, base_url, index, quantidade):
                criados += 1

    ctx.log.success(f"Concluído: {criados} de {quantidade} pedido(s) criado(s).")


def _quantidade(params: Dict[str, Any]) -> int:
    """O parâmetro é entrada de usuário: vazio, zero ou texto caem em 5."""
    try:
        value = int(params.get("quantidade_pedidos") or 0)
    except (TypeError, ValueError):
        value = 0
    return max(1, value or 5)


def _login(ctx: hobots.RunContext, page: Page, base_url: str, email: str, password: str) -> None:
    def entrar(etapa: hobots.Step) -> None:
        try:
            login(page, base_url, email, password)
        except Exception as error:
            # o print vai junto da etapa: a tela no momento exato da falha
            etapa.image(screenshot(page, "tela no momento da falha de login"))
            if isinstance(error, AuthError):
                ctx.log.error(f"Falha de autenticação: {error}")
            raise  # a etapa fica em erro; sem login não há pedido

    # falhou? o SDK tenta de novo uma vez, 5 s depois (padrão de retries)
    ctx.step(f"Login {email}", entrar)
    ctx.log.info("Login realizado com sucesso.")


def _criar_pedido(ctx: hobots.RunContext, page: Page, base_url: str, index: int, total: int) -> bool:
    item_id = pedido_item_id(index)

    def pedido(etapa: hobots.Step) -> bool:
        try:
            order = create_random_order(page, base_url, index)
        except (hobots.RunCanceled, hobots.TaskTimeout):
            raise  # o trabalho está parando: não é falha deste pedido
        except OrderError as error:
            # regra de negócio: o robô funcionou, o processo é que não pode atender
            reason = str(error)
            ctx.log.warn(f"Pedido {index}/{total}: {reason}")
            etapa.warning(reason)
            ctx.items.occurrence(reason, {"indice": index}, id=item_id)
            return False
        except Exception as error:
            # falha técnica: print na etapa e no item, e uma issue para quem mantém o robô
            reason = str(error) or type(error).__name__
            ctx.log.error(f"Pedido {index}/{total} falhou: {reason}")
            image = screenshot(page, reason)
            etapa.image(image)
            ctx.items.failed(reason, {"indice": index}, id=item_id, image=image)
            hobots.capture_exception(error, {"tags": {"indice": str(index)}})
            raise  # a etapa fica em erro, com o tipo e a mensagem
        ctx.items.succeeded(pedido_payload(order), id=item_id)
        ctx.log.info(f"Pedido {index}/{total} criado com sucesso.")
        return True

    try:
        # retries=0: criar um pedido não pode ser repetido às cegas — o site pode já ter aceitado
        return ctx.step(f"Pedido {index}/{total}", pedido, retries=0)
    except (hobots.RunCanceled, hobots.TaskTimeout):
        raise
    except Exception:
        return False  # falha técnica, já registrada na etapa, no item e na issue: próximo pedido
    finally:
            # avança mesmo na falha: a barra mostra pedidos processados, não bem-sucedidos
            ctx.progress.advance()
src/handler.ts
import hobots, { type RunContext } from 'hobots';
import type { Page } from 'puppeteer-core';

import { launchBrowser, screenshot } from './browser';
import { AuthError, OrderError } from './errors';
import { pedidoItemId, pedidoPayload } from './items';
import { login } from './login';
import { createRandomOrder } from './orders';

export type BotParams = { quantidade_pedidos?: number };

export async function criarPedidos(params: BotParams, ctx: RunContext): Promise<void> {
  // o parâmetro é entrada de usuário: vazio, zero ou texto caem em 5
  const quantidade = Math.max(1, Math.floor(Number(params.quantidade_pedidos)) || 5);
  const baseUrl = (process.env.PEDDEMO_BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '');
  const email = process.env.PEDDEMO_EMAIL ?? '';
  const password = process.env.PEDDEMO_PASSWORD ?? '';
  const headless = process.env.HEADLESS === 'true';
  if (!email || !password) {
    throw new Error('PEDDEMO_EMAIL e PEDDEMO_PASSWORD precisam estar configurados no .env.');
  }

  ctx.log.info(`Criando ${quantidade} pedido(s) em ${baseUrl}...`);
  let criados = 0;
  const { page, close } = await launchBrowser(headless);
  try {
    await loginStep(ctx, page, baseUrl, email, password);

    // barra de progresso na Central: percentual e tempo restante estimado
    ctx.progress.total(quantidade);

    for (let index = 1; index <= quantidade; index++) {
      ctx.throwIfCanceled(); // cancelado na Central? para antes de começar outro pedido
      if (await criarPedido(ctx, page, baseUrl, index, quantidade)) criados++;
    }
  } finally {
    await close();
  }

  ctx.log.success(`Concluído: ${criados} de ${quantidade} pedido(s) criado(s).`);
}

async function loginStep(ctx: RunContext, page: Page, baseUrl: string, email: string, password: string): Promise<void> {
  // falhou? o SDK tenta de novo uma vez, 5 s depois (padrão de retries)
  await ctx.step(`Login ${email}`, async (etapa) => {
    try {
      await login(page, baseUrl, email, password);
    } catch (error) {
      // o print vai junto da etapa: a tela no momento exato da falha
      etapa.image(await screenshot(page, 'tela no momento da falha de login'));
      if (error instanceof AuthError) ctx.log.error(`Falha de autenticação: ${error.message}`);
      throw error; // a etapa fica em erro; sem login não há pedido
    }
  });
  ctx.log.info('Login realizado com sucesso.');
}

/** Cancelamento ou timeout do trabalho: não é falha do pedido, só sobe. */
function isStop(error: unknown): boolean {
  return error instanceof Error && (error.name === 'RunCanceled' || error.name === 'TaskTimeout');
}

async function criarPedido(ctx: RunContext, page: Page, baseUrl: string, index: number, total: number): Promise<boolean> {
  const id = pedidoItemId(index);
  try {
    // retries: 0 — criar um pedido não pode ser repetido às cegas: o site pode já ter aceitado
    return await ctx.step(`Pedido ${index}/${total}`, async (etapa) => {
      try {
        const order = await createRandomOrder(page, baseUrl, index);
        ctx.items.succeeded(pedidoPayload(order), { id });
        ctx.log.info(`Pedido ${index}/${total} criado com sucesso.`);
        return true;
      } catch (error) {
        if (isStop(error)) throw error; // o trabalho está parando: não é falha deste pedido
        const reason = error instanceof Error ? error.message : String(error);
        if (error instanceof OrderError) {
          // regra de negócio: o robô funcionou, o processo é que não pode atender
          ctx.log.warn(`Pedido ${index}/${total}: ${reason}`);
          etapa.warning(reason);
          ctx.items.occurrence(reason, { indice: index }, { id });
          return false;
        }
        // falha técnica: print na etapa e no item, e uma issue para quem mantém o robô
        ctx.log.error(`Pedido ${index}/${total} falhou: ${reason}`);
        const image = await screenshot(page, reason);
        etapa.image(image);
        ctx.items.failed(reason, { indice: index }, { id, image });
        hobots.captureException(error, { tags: { indice: String(index) } });
        throw error; // a etapa fica em erro, com o tipo e a mensagem
      }
    }, { retries: 0 });
  } catch (error) {
    if (isStop(error)) throw error;
    return false; // falha técnica, já registrada na etapa, no item e na issue: próximo pedido
  } finally {
    // avança mesmo na falha: a barra mostra pedidos processados, não bem-sucedidos
    ctx.progress.advance();
  }
}
peddemo/browser.py
from contextlib import contextmanager
from typing import Iterator, Optional

from playwright.sync_api import Page, sync_playwright

import hobots


@contextmanager
def launch_browser(headless: bool) -> Iterator[Page]:
    """Abre o Google Chrome da máquina e fecha ao sair do `with`, mesmo com erro."""
    with sync_playwright() as p:
        browser = p.chromium.launch(channel="chrome", headless=headless, args=["--start-maximized"])
        try:
            yield browser.new_page(no_viewport=True)
        finally:
            browser.close()


def screenshot(page: Page, caption: str) -> Optional[hobots.ImageAttachment]:
    """Print da tela pronto para ir num item, etapa ou log. Nunca levanta: se o navegador
    travou, o desfecho do pedido não pode depender dele."""
    try:
        return hobots.image(page.screenshot(timeout=5_000), caption=caption)
    except Exception:
        return None
src/browser.ts
import puppeteer, { type Page } from 'puppeteer-core';
import chromePaths from 'chrome-paths';
import hobots, { type ImageAttachment } from 'hobots';

/** Abre o Google Chrome da máquina. Chame `close()` num finally. */
export async function launchBrowser(headless: boolean): Promise<{ page: Page; close: () => Promise<void> }> {
  const executablePath = chromePaths.chrome === 'google-chrome' ? '/usr/bin/google-chrome' : chromePaths.chrome;
  const browser = await puppeteer.launch({ headless, executablePath, defaultViewport: null, args: ['--start-maximized'] });

  const [page] = await browser.pages();
  if (!page) throw new Error('Não foi possível abrir uma aba no navegador.');

  return { page, close: () => browser.close() };
}

/**
 * Print da tela pronto para ir num item, etapa ou log. Nunca lança: se o navegador
 * travou, o desfecho do pedido não pode depender dele.
 */
export async function screenshot(page: Page, caption: string): Promise<ImageAttachment | undefined> {
  try {
    const png = await Promise.race([
      page.screenshot({ type: 'png' }),
      new Promise<never>((_, reject) => setTimeout(() => reject(new Error('screenshot demorou')), 5_000)),
    ]);
    return hobots.image(png, { caption });
  } catch {
    return undefined;
  }
}
src/types/chrome-paths.d.ts
declare module 'chrome-paths' {
  const chromePaths: { chrome: string; chromium: string; canary: string };
  export default chromePaths;
}

Login

peddemo/login.py
from playwright.sync_api import Page

from .errors import AuthError

FORM_ERROR = "form p.text-red-600"


def login(page: Page, base_url: str, email: str, password: str) -> None:
    page.goto(f"{base_url}/signin", wait_until="networkidle")
    page.locator("#email").fill(email)
    page.locator("#password").fill(password)
    page.locator('button[type="submit"]').click()

    # o que vier primeiro: o painel (entrou) ou a mensagem vermelha do formulário (recusou)
    page.wait_for_function(
        "sel => location.pathname === '/dashboard' || document.querySelector(sel) !== null",
        arg=FORM_ERROR,
        timeout=15_000,
    )
    error = page.locator(FORM_ERROR)
    if error.count() > 0:
        raise AuthError(error.first.inner_text().strip() or "Falha ao autenticar.")
src/login.ts
import type { Page } from 'puppeteer-core';

import { AuthError } from './errors';

const FORM_ERROR = 'form p.text-red-600';

export async function login(page: Page, baseUrl: string, email: string, password: string): Promise<void> {
  await page.goto(`${baseUrl}/signin`, { waitUntil: 'networkidle2' });
  await page.waitForSelector('#email', { timeout: 15_000 });
  await page.type('#email', email, { delay: 20 });
  await page.type('#password', password, { delay: 20 });
  await page.click('button[type="submit"]');

  // o que vier primeiro: o painel (entrou) ou a mensagem vermelha do formulário (recusou)
  await page.waitForFunction(
    (sel: string) => location.pathname === '/dashboard' || document.querySelector(sel) !== null,
    { timeout: 15_000 },
    FORM_ERROR
  );
  const error = await page.$(FORM_ERROR);
  if (error) {
    const message = await error.evaluate(el => el.textContent?.trim() ?? '');
    throw new AuthError(message || 'Falha ao autenticar.');
  }
}

Pedidos

peddemo/orders.py
"""Fluxo de tela de /pedidos: abre o modal, sorteia os dados e cria um pedido."""

from __future__ import annotations

import random
import re
from dataclasses import dataclass
from typing import Dict, List

from playwright.sync_api import Locator, Page

import hobots

from .errors import OrderError

FORM_ERROR = "form p.text-red-600"

# Produtos que não existem no cardápio: simulam um cliente pedindo o que a pizzaria não tem
UNLISTED_PRODUCT_NAMES = ["Pizza Frango com Catupiry", "Pizza Vegetariana", "Fanta 2L", "Brownie", "Mousse de Maracujá"]
UNLISTED_PRODUCT_CHANCE = 0.2  # ~1 em cada 5 pedidos


@dataclass
class OrderItem:
    product_name: str
    quantity: int


@dataclass
class Order:
    index: int
    customer: str
    type: str
    payment_method: str
    items: List[OrderItem]


# ── tela ──────────────────────────────────────────────────────────────────────


def goto_pedidos(page: Page, base_url: str) -> None:
    page.goto(f"{base_url}/pedidos", wait_until="networkidle")
    page.locator("table").wait_for(timeout=15_000)


def count_orders(page: Page) -> int:
    return page.locator("tbody tr").count()


def open_new_order_modal(page: Page) -> None:
    page.get_by_role("button", name="+ Novo pedido", exact=True).click()
    page.locator("form").wait_for(timeout=10_000)


def _select_by_label(page: Page, label: str) -> Locator:
    # os <label> do modal não têm `for`, então get_by_label não acha o campo:
    # pegamos o <select> ao lado do rótulo pelo texto exato
    select = page.locator(f"xpath=//form//label[normalize-space()='{label}']/following-sibling::select")
    select.wait_for(timeout=10_000)
    return select


def select_random_option(page: Page, label: str) -> Dict[str, str]:
    """Sorteia e seleciona uma opção não vazia do select com esse rótulo."""
    select = _select_by_label(page, label)
    options = select.locator("option").evaluate_all(
        "els => els.filter(o => o.value).map(o => ({ value: o.value, label: o.textContent.trim() }))"
    )
    if not options:
        raise RuntimeError(f'Nenhuma opção disponível para o campo "{label}".')
    chosen = random.choice(options)
    select.select_option(value=chosen["value"])
    return chosen


def list_available_products(page: Page) -> List[str]:
    """Nomes dos produtos ativos do cardápio, como aparecem no modal."""
    names = page.locator("div.max-h-72 p.font-medium").all_inner_texts()
    return [name.strip() for name in names if name.strip()]


def set_product_quantity(page: Page, product_name: str, quantity: int) -> None:
    row = page.locator("div.max-h-72 div.justify-between").filter(
        has=page.locator("p.font-medium", has_text=re.compile(f"^{re.escape(product_name)}$"))
    )
    increment = row.get_by_role("button", name="+", exact=True)
    for _ in range(quantity):
        increment.click()
        hobots.sleep(120)  # dá tempo do contador re-renderizar antes do próximo clique


def submit_order(page: Page) -> None:
    page.get_by_role("button", name="Criar pedido", exact=True).click()
    # o que vier primeiro: o modal fechou (aceito) ou a mensagem vermelha (recusado)
    page.wait_for_function(
        "sel => document.querySelector('form') === null || document.querySelector(sel) !== null",
        arg=FORM_ERROR,
        timeout=10_000,
    )
    error = page.locator(FORM_ERROR)
    if error.count() > 0:
        raise OrderError(error.first.inner_text().strip() or "Falha ao criar o pedido.")


# ── regra do pedido ───────────────────────────────────────────────────────────


def pick_order_items(available: List[str]) -> List[OrderItem]:
    """De vez em quando monta o pedido com um produto que não existe no cardápio."""
    if random.random() < UNLISTED_PRODUCT_CHANCE:
        return [OrderItem(random.choice(UNLISTED_PRODUCT_NAMES), random.randint(1, 3))]
    if not available:
        raise OrderError("Nenhum item ativo no cardápio disponível para montar o pedido.")
    count = min(len(available), random.randint(1, 3))
    return [OrderItem(name, random.randint(1, 3)) for name in random.sample(available, count)]


def assert_products_exist(items: List[OrderItem], available: List[str]) -> None:
    """Produto fora do cardápio é ocorrência de negócio, não erro de tela."""
    for item in items:
        if item.product_name not in available:
            raise OrderError(f'Produto "{item.product_name}" não encontrado no cardápio do site.')


def _attempt(page: Page, base_url: str, index: int) -> Order:
    goto_pedidos(page, base_url)
    before = count_orders(page)

    open_new_order_modal(page)
    customer = select_random_option(page, "Cliente")
    order_type = select_random_option(page, "Tipo")
    payment = select_random_option(page, "Forma de pagamento")

    available = list_available_products(page)
    items = pick_order_items(available)
    assert_products_exist(items, available)  # OrderError se o produto não está no cardápio

    for item in items:
        set_product_quantity(page, item.product_name, item.quantity)

    resumo = ", ".join(f"{i.product_name} x{i.quantity}" for i in items)
    hobots.log.info(f'Pedido {index}: cliente="{customer["label"]}", tipo={order_type["value"]}, '
                    f'pagamento={payment["value"]}, itens=[{resumo}]')

    submit_order(page)  # OrderError se o site recusar
    if count_orders(page) <= before:
        raise RuntimeError("O pedido não apareceu na listagem após o envio.")

    return Order(index, customer["label"], order_type["value"], payment["value"], items)


def create_random_order(page: Page, base_url: str, index: int) -> Order:
    def attempt(number: int) -> Order:
        if number > 1:
            hobots.log.debug(f"Pedido {index}: tentativa {number} depois de um erro de tela")
        return _attempt(page, base_url, index)

    return hobots.retry(
        attempt,
        retries=1,  # 1 tentativa extra
        delay=1_000,  # ms
        # OrderError é regra de negócio: tentar de novo dá o mesmo resultado
        should_retry=lambda error: not isinstance(error, OrderError),
    )
src/orders.ts
import type { ElementHandle, Page } from 'puppeteer-core';
import hobots from 'hobots';

import { OrderError } from './errors';

const FORM_ERROR = 'form p.text-red-600';

// Produtos que não existem no cardápio: simulam um cliente pedindo o que a pizzaria não tem
const UNLISTED_PRODUCT_NAMES = ['Pizza Frango com Catupiry', 'Pizza Vegetariana', 'Fanta 2L', 'Brownie', 'Mousse de Maracujá'];
const UNLISTED_PRODUCT_CHANCE = 0.2; // ~1 em cada 5 pedidos

export type OrderItem = { productName: string; quantity: number };

export type OrderResult = {
  index: number;
  customer: string;
  type: string;
  paymentMethod: string;
  items: OrderItem[];
};

type SelectedOption = { value: string; label: string };

// ── tela ──────────────────────────────────────────────────────────────────────

async function gotoPedidos(page: Page, baseUrl: string): Promise<void> {
  await page.goto(`${baseUrl}/pedidos`, { waitUntil: 'networkidle2' });
  await page.waitForSelector('table', { timeout: 15_000 });
}

async function countOrders(page: Page): Promise<number> {
  return page.$$eval('tbody tr', rows => rows.length);
}

async function findButtonByText(page: Page, text: string): Promise<ElementHandle<Element>> {
  const handle = await page.evaluateHandle(
    label => Array.from(document.querySelectorAll('button')).find(btn => btn.textContent?.trim() === label) ?? null,
    text
  );
  const element = handle.asElement() as ElementHandle<Element> | null;
  if (!element) throw new Error(`Botão "${text}" não encontrado.`);
  return element;
}

async function openNewOrderModal(page: Page): Promise<void> {
  const button = await findButtonByText(page, '+ Novo pedido');
  await button.click();
  await page.waitForSelector('form', { timeout: 10_000 });
}

/** Os <label> do modal não têm `for`: acha o select ao lado do rótulo pelo texto exato. */
async function selectByLabel(page: Page, label: string): Promise<ElementHandle<HTMLSelectElement>> {
  const handle = await page.evaluateHandle(text => {
    const el = Array.from(document.querySelectorAll('form label')).find(l => l.textContent?.trim() === text);
    return el?.parentElement?.querySelector('select') ?? null;
  }, label);
  const element = handle.asElement() as ElementHandle<HTMLSelectElement> | null;
  if (!element) throw new Error(`Campo "${label}" não encontrado no formulário.`);
  return element;
}

/** Sorteia e seleciona uma opção não vazia do select com esse rótulo. */
async function selectRandomOption(page: Page, label: string): Promise<SelectedOption> {
  const select = await selectByLabel(page, label);
  const options = await select.evaluate(el =>
    Array.from(el.options)
      .filter(option => option.value)
      .map(option => ({ value: option.value, label: option.textContent?.trim() ?? '' }))
  );
  if (options.length === 0) throw new Error(`Nenhuma opção disponível para o campo "${label}".`);

  const chosen = options[Math.floor(Math.random() * options.length)]!;
  await select.select(chosen.value);
  return chosen;
}

/** Nomes dos produtos ativos do cardápio, como aparecem no modal. */
async function listAvailableProducts(page: Page): Promise<string[]> {
  return page.$$eval('div.max-h-72 p.font-medium', ps => ps.map(p => p.textContent?.trim() ?? '').filter(Boolean));
}

async function setProductQuantity(page: Page, productName: string, quantity: number): Promise<void> {
  const handle = await page.evaluateHandle(name => {
    const nameEl = Array.from(document.querySelectorAll('div.max-h-72 p.font-medium')).find(p => p.textContent?.trim() === name);
    const row = nameEl?.parentElement?.parentElement;
    return row ? (Array.from(row.querySelectorAll('button')).find(b => b.textContent?.trim() === '+') ?? null) : null;
  }, productName);
  const increment = handle.asElement() as ElementHandle<Element> | null;
  if (!increment) throw new Error(`Botão de aumentar quantidade não encontrado para "${productName}".`);

  for (let i = 0; i < quantity; i++) {
    await increment.click();
    await hobots.sleep(120); // dá tempo do contador re-renderizar antes do próximo clique
  }
}

async function submitOrder(page: Page): Promise<void> {
  const button = await findButtonByText(page, 'Criar pedido');
  await button.click();

  // o que vier primeiro: o modal fechou (aceito) ou a mensagem vermelha (recusado)
  await page.waitForFunction(
    (sel: string) => document.querySelector('form') === null || document.querySelector(sel) !== null,
    { timeout: 10_000 },
    FORM_ERROR
  );
  const error = await page.$(FORM_ERROR);
  if (error) {
    const message = await error.evaluate(el => el.textContent?.trim() ?? '');
    throw new OrderError(message || 'Falha ao criar o pedido.');
  }
}

// ── regra do pedido ───────────────────────────────────────────────────────────

const randomInt = (min: number, max: number): number => Math.floor(Math.random() * (max - min + 1)) + min;

/** De vez em quando monta o pedido com um produto que não existe no cardápio. */
function pickOrderItems(available: string[]): OrderItem[] {
  if (Math.random() < UNLISTED_PRODUCT_CHANCE) {
    const productName = UNLISTED_PRODUCT_NAMES[Math.floor(Math.random() * UNLISTED_PRODUCT_NAMES.length)]!;
    return [{ productName, quantity: randomInt(1, 3) }];
  }
  if (available.length === 0) {
    throw new OrderError('Nenhum item ativo no cardápio disponível para montar o pedido.');
  }
  const shuffled = [...available].sort(() => Math.random() - 0.5);
  const count = Math.min(available.length, randomInt(1, 3));
  return shuffled.slice(0, count).map(productName => ({ productName, quantity: randomInt(1, 3) }));
}

/** Produto fora do cardápio é ocorrência de negócio, não erro de tela. */
function assertProductsExist(items: OrderItem[], available: string[]): void {
  const missing = items.find(item => !available.includes(item.productName));
  if (missing) {
    throw new OrderError(`Produto "${missing.productName}" não encontrado no cardápio do site.`);
  }
}

async function attempt(page: Page, baseUrl: string, index: number): Promise<OrderResult> {
  await gotoPedidos(page, baseUrl);
  const before = await countOrders(page);

  await openNewOrderModal(page);
  const customer = await selectRandomOption(page, 'Cliente');
  const type = await selectRandomOption(page, 'Tipo');
  const paymentMethod = await selectRandomOption(page, 'Forma de pagamento');

  const available = await listAvailableProducts(page);
  const items = pickOrderItems(available);
  assertProductsExist(items, available); // OrderError se o produto não está no cardápio

  for (const item of items) {
    await setProductQuantity(page, item.productName, item.quantity);
  }

  const resumo = items.map(i => `${i.productName} x${i.quantity}`).join(', ');
  hobots.log.info(`Pedido ${index}: cliente="${customer.label}", tipo=${type.value}, pagamento=${paymentMethod.value}, itens=[${resumo}]`);

  await submitOrder(page); // OrderError se o site recusar
  if ((await countOrders(page)) <= before) {
    throw new Error('O pedido não apareceu na listagem após o envio.');
  }

  return { index, customer: customer.label, type: type.value, paymentMethod: paymentMethod.value, items };
}

export async function createRandomOrder(page: Page, baseUrl: string, index: number): Promise<OrderResult> {
  return hobots.retry(
    async attemptNumber => {
      if (attemptNumber > 1) hobots.log.debug(`Pedido ${index}: tentativa ${attemptNumber} depois de um erro de tela`);
      return attempt(page, baseUrl, index);
    },
    {
      retries: 1, // 1 tentativa extra
      delayMs: 1_000,
      // OrderError é regra de negócio: tentar de novo dá o mesmo resultado
      shouldRetry: error => !(error instanceof OrderError),
    }
  );
}

Itens e erros

peddemo/items.py
from typing import Any, Dict

from .orders import Order


def pedido_item_id(index: int) -> str:
    """Identidade do item no trabalho: a posição do pedido no lote."""
    return f"pedido-{index}"


def pedido_payload(order: Order) -> Dict[str, Any]:
    return {
        "indice": order.index,
        "cliente": order.customer,
        "tipo": order.type,
        "forma_pagamento": order.payment_method,
        # resumo em texto porque a coluna exibe valor simples; a lista completa vai em "itens"
        "itens_resumo": ", ".join(f"{i.product_name} x{i.quantity}" for i in order.items),
        "quantidade_itens": sum(i.quantity for i in order.items),
        "itens": [{"produto": i.product_name, "quantidade": i.quantity} for i in order.items],
    }
peddemo/errors.py
class AuthError(Exception):
    """O site recusou o login (senha errada, usuário bloqueado...)."""


class OrderError(Exception):
    """O pedido não pode ser criado por regra de negócio. Vira ocorrência, não falha."""
src/items.ts
import type { OrderResult } from './orders';

/** Identidade do item no trabalho: a posição do pedido no lote. */
export function pedidoItemId(index: number): string {
  return `pedido-${index}`;
}

export function pedidoPayload(order: OrderResult): Record<string, unknown> {
  return {
    indice: order.index,
    cliente: order.customer,
    tipo: order.type,
    forma_pagamento: order.paymentMethod,
    // resumo em texto porque a coluna exibe valor simples; a lista completa vai em `itens`
    itens_resumo: order.items.map(i => `${i.productName} x${i.quantity}`).join(', '),
    quantidade_itens: order.items.reduce((total, i) => total + i.quantity, 0),
    itens: order.items.map(i => ({ produto: i.productName, quantidade: i.quantity })),
  };
}
src/errors.ts
/** O site recusou o login (senha errada, usuário bloqueado...). */
export class AuthError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'AuthError';
  }
}

/** O pedido não pode ser criado por regra de negócio. Vira ocorrência, não falha. */
export class OrderError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'OrderError';
  }
}