Skip to content

Examples ​

The demo is a small back office of a shop, in ten tools. Each one is a single PHP file. The pictures on this page are taken from the running demo, and the sources are the files of the repository as they are.

The list of tools of the demo, "Shop back office": ten cards, each with the name of a tool and a line that says what it does.

The demo is not part of the Composer package. Run it from a copy of the repository:

bash
git clone https://github.com/RunIO-dev/runio-script-ui.git
cd runio-script-ui
composer install
php bin/script-ui serve examples/tools

Then open http://localhost:8765. The demo keeps its data in examples/var/, and the audit log has a button that brings the sample data back.

Change something ​

Refund orders ​

Find the orders of a customer, tick the ones to refund, and say yes. It shows a table that returns the ticked rows, and a button that asks before it acts. The second tutorial walks through it.

The refund tool with two ticked orders and the question "Refund 2 orders?" with the buttons "Yes" and "Cancel".

The source: examples/tools/refund.php
php
<?php
// Refund orders
// Find a customer's orders, tick the ones to refund, confirm.

require_once __DIR__ . '/_shop.php';

use function Runio\ScriptUi\{title, text, select, table, button, success, info, rerun};

$shop = Shop::open();

title('Refund orders');

$email = text('Customer email', placeholder: 'ava@example.com', help: 'Try ava@example.com or omar@example.com.');
$status = select('Status', ['paid', 'shipped']);

if ($email === '') {
    info('Type a customer email to see their orders.');

    return;
}

$orders = $shop->orders(email: $email, status: $status);

$picked = table(
    $orders,
    selectable: true,
    columns: ['id' => 'Order', 'created_at' => 'Placed on', 'items' => 'Items', 'total' => 'Total'],
    empty: 'No ' . $status . ' orders for ' . $email . '.',
);

$count = count($picked) === 1 ? '1 order' : count($picked) . ' orders';

if ($picked && button('Refund selected', style: 'danger', confirm: 'Refund ' . $count . '?')) {
    foreach ($picked as $order) {
        $shop->refund($order['id']);
    }

    success('Refunded ' . $count . '.');
    rerun();
}

Give a coupon ​

A form that checks what was typed, and says under each field what is wrong with it. Some checks run while the user fills the form in, and the rest when the button is pressed.

The coupon tool after a press on "Give coupon": red notes under the fields "Customer email" and "Reason" say what is missing.

The source: examples/tools/coupon.php
php
<?php
// Give a coupon
// A form that checks what was typed, and says under each field what is wrong with it.

require_once __DIR__ . '/_shop.php';

use function Runio\ScriptUi\{title, heading, text, number, date_input, textarea, button, field_error, valid, success, table};

$shop = Shop::open();

title('Give a coupon');

$email = text('Customer email', placeholder: 'ava@example.com', help: 'Try ava@example.com or omar@example.com.');
$percent = number('Discount in percent', default: 10, min: 1, max: 50, step: 1);
$until = date_input('Valid until', default: date('Y-m-d', strtotime('+30 days')), min: date('Y-m-d'));
$reason = textarea('Reason', rows: 2, help: 'It goes to the log. More than 20 percent needs one.');

$customer = $shop->customer($email);
$coupons = $customer === null ? [] : $shop->coupons($customer['email']);

// Checked on every run: the note comes when the user leaves the field, and it
// stays until the field is right. An empty field is left alone here, or a new
// page would start full of red. The answer tells whoever may open this tool
// who is a customer. That is fine in a back office, and nowhere else.
if ($email !== '' && $customer === null) {
    field_error('Customer email', 'No customer has this email.');
}

if (button('Give coupon', style: 'primary')) {
    // Checked when the button is pressed: what is missing, and what only counts now.
    if ($email === '') {
        field_error('Customer email', 'Enter the email of a customer.');
    }
    if ($percent === null) {
        field_error('Discount in percent', 'Enter a discount from 1 to 50.');
    }
    if ($until === null) {
        field_error('Valid until', 'Choose the last day of the coupon.');
    }
    if ($percent > 20 && mb_strlen($reason) < 10) {
        field_error('Reason', 'More than 20 percent needs a reason. Write a sentence.');
    }
    // The form still holds what was typed after the coupon was given. A second
    // press, or a double click, must not give a second one. Two requests at the
    // very same moment would both pass this check: where it matters, let the
    // database refuse the second one, with a unique key.
    foreach ($coupons as $coupon) {
        if ($coupon['until'] >= date('Y-m-d')) {
            field_error('Customer email', $customer['name'] . ' has a coupon already: ' . $coupon['code'] . ', valid until ' . $coupon['until'] . '.');

            break;
        }
    }

    // field_error() does not stop the script. Nothing is done until all of it is right.
    if (valid()) {
        $code = $shop->addCoupon($customer['email'], $percent, $until);
        $coupons = $shop->coupons($customer['email']);
        success($customer['name'] . ' got ' . $percent . ' % off with the code ' . $code . ', until ' . $until . '.');
    }
}

if ($customer !== null) {
    heading('Coupons of ' . $customer['name']);
    table(
        $coupons,
        columns: ['code' => 'Code', 'percent' => 'Percent', 'until' => 'Valid until', 'given' => 'Given on'],
        empty: 'No coupon yet.',
    );
}

Ship orders ​

All paid orders, ten on a page, with a search over all of them. A tick stays when the page of the table is turned, so one press can ship orders from several pages.

The tool "Ship orders": a search box, a table of paid orders with a tick box in every row, and the pages of the table under it.

The source: examples/tools/ship.php
php
<?php
// Ship orders
// Search the paid orders or go through them page by page, tick the ones that left the warehouse, confirm.

require_once __DIR__ . '/_shop.php';

use function Runio\ScriptUi\{title, table, button, success, info, rerun};

$shop = Shop::open();

title('Ship orders');

$orders = $shop->orders(status: 'paid');

if ($orders === []) {
    info('No paid order is waiting.');

    return;
}

// All paid orders go in. The table shows ten at a time and searches all of them.
// A tick stays when the page changes. A ticked row that the search hides is not
// in $picked, and it is ticked again when the search shows it.
$picked = table(
    $orders,
    selectable: true,
    columns: ['id' => 'Order', 'created_at' => 'Placed on', 'customer' => 'Customer', 'items' => 'Items', 'total' => 'Total'],
    pageSize: 10,
    search: true,
);

$count = count($picked) === 1 ? '1 order' : count($picked) . ' orders';

if ($picked && button('Mark as shipped', style: 'primary', confirm: 'Mark ' . $count . ' as shipped?')) {
    foreach ($picked as $order) {
        $shop->ship($order['id']);
    }

    success('Marked ' . $count . ' as shipped.');
    rerun();
}

Look something up ​

Customers ​

Filters in three columns, tick boxes for the countries, and a table. Tick one customer and the page shows their orders and their record in two tabs, a link that opens the refund tool with the email filled in, and a download of what the filters left.

The customer list, searched for "omar": one customer is ticked, and under the table stand a download button, a link to the refund tool, and two tabs with the orders and the record of that customer.

The source: examples/tools/customers.php
php
<?php
// Customers
// Filter the customer list and look at one customer in detail.

require_once __DIR__ . '/_shop.php';

use function Runio\ScriptUi\{title, heading, columns, tabs, text, multiselect, number, checkbox, date_input, table, download, json, link, note};

$shop = Shop::open();
$customers = $shop->customers();

title('Customers');

$search = $minSpent = $joinedAfter = null;

columns(
    function () use (&$search): void {
        $search = text('Search', placeholder: 'Name or email');
    },
    function () use (&$minSpent): void {
        $minSpent = number('Spent at least', default: 0, min: 0, step: 50);
    },
    function () use (&$joinedAfter): void {
        $joinedAfter = date_input('Joined after');
    },
);

$countries = array_column($customers, 'country');
sort($countries);
$from = multiselect('Country', $countries, horizontal: true, help: 'Tick none to see every country.');
$refundsOnly = checkbox('Only customers with a refund');

$found = array_values(array_filter($customers, static fn (array $customer): bool
    => ($search === '' || stripos($customer['name'] . ' ' . $customer['email'], $search) !== false)
    && ($from === [] || in_array($customer['country'], $from, true))
    && $customer['spent'] >= ($minSpent ?? 0)
    && ($joinedAfter === null || $customer['joined'] > $joinedAfter)
    && (!$refundsOnly || $customer['refunds'] > 0)));

$picked = table(
    $found,
    selectable: true,
    columns: ['name' => 'Name', 'email' => 'Email', 'country' => 'Country', 'joined' => 'Joined', 'orders' => 'Orders', 'refunds' => 'Refunds', 'spent' => 'Spent'],
    rowKey: 'email',   // a customer has no id column; the email tells them apart
    empty: 'No customer matches these filters.',
);

// The file holds what the filters above leave, with every column.
if ($found !== []) {
    download('Download as CSV', $found, 'customers.csv');
}

if (count($picked) === 1) {
    $customer = $picked[0];

    $orders = $shop->orders(email: $customer['email']);

    heading($customer['name']);
    link('Refund an order of this customer', '/refund?customer-email=' . rawurlencode($customer['email']));

    // Two views of one customer, one of them in sight. Both run on every run:
    // changing the tab asks nothing of the server.
    tabs([
        'Orders (' . count($orders) . ')' => fn () => table(
            $orders,
            columns: ['id' => 'Order', 'created_at' => 'Placed on', 'items' => 'Items', 'status' => 'Status', 'total' => 'Total'],
            key: 'orders',
            pageSize: 10,
        ),
        'Record' => fn () => json($customer),
    ]);
} elseif (count($picked) > 1) {
    note('Tick a single customer to see the details.');
}

Order archive ​

A table over 100,000 orders that holds one page at a time. It asks a function for the rows of the page it shows. The fourth tutorial shows the same with a database.

The order archive, searched for "haddad": a search box and a table of orders with tick boxes and headers that sort.

The source: examples/tools/archive.php
php
<?php
// Order archive
// 100,000 orders, read one page at a time.

require_once __DIR__ . '/_archive.php';

use function Runio\ScriptUi\{title, note, table, button, success, warning};

title('Order archive');
note('This table holds one page. Each time it is turned, searched or sorted, it asks for the rows of the page it shows, and for nothing else.');

$picked = table(
    Archive::page(...),      // gets a TableQuery: the search, the order, a limit and an offset
    selectable: true,
    columns: ['id' => 'Order', 'customer' => 'Customer', 'placed' => 'Placed on', 'status' => 'Status', 'total' => 'Total'],
    search: true,
    sortable: ['id', 'customer', 'placed', 'total'],
    count: Archive::count(...),   // gets the search, says how many orders it leaves
);

if (button('Print labels')) {
    if ($picked === []) {
        warning('Tick the orders that need a label first.');
    } else {
        success('Labels are on their way for ' . implode(', ', array_column($picked, 'id')) . '.');
    }
}

Bring data in and out ​

Import orders ​

Upload a CSV file, look at what it holds, and only then add the orders to the shop. The file waits on the server while the user looks at it, and nothing is saved before the button is pressed.

The import tool after an upload: the file "orders.csv" with a link "Remove", a table with the two orders the file holds, and a button "Import 2 orders".

The source: examples/tools/import.php
php
<?php
// Import orders
// Upload a CSV file with new orders, look at what it holds, then add them to the shop.

require_once __DIR__ . '/_shop.php';

use function Runio\ScriptUi\{title, file_input, table, button, download, success, warning, error, rerun};

$shop = Shop::open();

title('Import orders');

$file = file_input(
    'Orders as CSV',
    types: ['csv'],
    maxSize: 1024 * 1024,
    help: 'One order per line. The first line names the columns: email, items, total.',
);

if ($file === null) {
    // Something to try the tool with.
    download('Download an example file', Shop::exampleOrders(), 'orders-example.csv');

    return;
}

// The file waits on the server while you look at it. Nothing is in the shop yet.
// rows() reads what a spreadsheet saved: the first line names the columns, every cell is text.
[$orders, $problems] = $shop->checkOrders($file->rows());

if ($problems !== []) {
    $more = count($problems) - 5;
    warning(implode("\n", array_slice($problems, 0, 5)) . ($more > 0 ? "\nAnd " . $more . ' more.' : ''));
}

if ($orders === []) {
    error('No order could be read from ' . $file->name . '.');

    return;
}

table($orders, columns: ['customer' => 'Customer', 'email' => 'Email', 'items' => 'Items', 'total' => 'Total'], pageSize: 10);

$count = count($orders) === 1 ? '1 order' : count($orders) . ' orders';

if (button('Import ' . $count, style: 'primary', confirm: 'Add ' . $count . ' to the shop?')) {
    $shop->addOrders($orders);

    // The tool is done with the file. Without this line it would wait on the server for a day.
    $file->forget();

    success('Added ' . $count . ' from ' . $file->name . '.');
    rerun();
}

Export orders ​

A task that takes half a minute: start it, watch how far it is, stop it, fetch the file. The page looks at the task every two seconds. A tick before the start lets the task fail half way, and the page then shows an error in place of the bar. The fifth tutorial walks through it.

The export while it runs: a bar that is about a third full, the words "900 of 2,400 orders" beside it, and a button "Stop the export".

The source: examples/tools/export.php
php
<?php
// Export orders
// A task that takes long: start it, watch how far it is, stop it, fetch the file. Or see it fail.

require_once __DIR__ . '/_export.php';

use function Runio\ScriptUi\{title, note, progress, refresh, button, checkbox, download, success, warning, error, rerun};

title('Export orders');

$export = Export::read();   // the export belongs to the shop: whoever opens this page sees the same one

if ($export->state === 'waiting' || $export->state === 'running') {
    // The work goes on somewhere else. This page looks at it every two seconds, for as long as it is open.
    refresh(2);

    if ($export->state === 'waiting') {
        // No value: nobody knows yet how far it is.
        progress('Waiting for a worker');
    } else {
        progress('Exporting orders', $export->done, Export::ORDERS, text: number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders');
    }

    if (button('Stop the export', confirm: 'Stop the export where it is?')) {
        Export::stop();
        rerun();
    }

    return;
}

if ($export->state === 'finished') {
    success(number_format($export->done) . ' orders are exported.');
    download('Download orders.csv', Export::orders(...), 'orders.csv');
} elseif ($export->state === 'stopped') {
    warning('The export was stopped at ' . number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders.');
} elseif ($export->state === 'failed') {
    // A short message of your own. What the worker threw is in its log: it names paths and queries.
    error('The export failed at ' . number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders. There is no file to download.');
} else {
    note('An export of all orders takes about half a minute. In a real shop a worker would write it. Here the clock stands in for the worker.');
}

// Only the demo asks this. Its clock cannot fail, and a real worker needs no help with that.
$fails = checkbox('Let the worker give up half way', help: 'To see what a failed export looks like.');

if (button($export->state === 'none' ? 'Start the export' : 'Start a new export', style: 'primary')) {
    // Hands the work over and comes back at once. No message: the bar on the next page says that it started.
    Export::start($fails);
    rerun();
}

Watch something ​

Sales dashboard ​

Four numbers with their change, two charts and the latest orders. The page runs again every 30 seconds while somebody looks at it, and it waits while they are in the middle of something.

The sales dashboard: a choice of the period, four numbers (revenue, orders, average order and refunds) with their change, a bar chart of the revenue per day and a line chart of orders and refunds.

The source: examples/tools/dashboard.php
php
<?php
// Sales dashboard
// Revenue, orders and refunds for the last days.

require_once __DIR__ . '/_shop.php';

use function Runio\ScriptUi\{title, heading, note, radio, columns, expander, metric, chart, table, refresh};

$shop = Shop::open();

title('Sales dashboard');

// The numbers change when somebody refunds an order in another window. The page keeps up
// by itself, and leaves the user alone while they are in the middle of something.
refresh(30);

// Three options: all of them in view, and one click instead of two.
$days = radio('Period', [7 => 'Last 7 days', 14 => 'Last 14 days', 30 => 'Last 30 days'], default: 14, horizontal: true);

$now = $shop->daily($days);
$before = array_slice($shop->daily($days * 2), 0, $days);

$sum = static fn (array $rows, string $column): float => (float) array_sum(array_column($rows, $column));
$change = static function (float $now, float $before): ?string {
    if ($before == 0.0) {
        return null;
    }

    return sprintf('%+.1f%%', ($now - $before) / $before * 100);
};

$revenue = $sum($now, 'revenue');
$orders = $sum($now, 'orders');
$refunds = $sum($now, 'refunds');

columns(
    fn () => metric('Revenue', '$' . number_format($revenue), $change($revenue, $sum($before, 'revenue'))),
    fn () => metric('Orders', number_format($orders), $change($orders, $sum($before, 'orders'))),
    fn () => metric('Average order', '$' . number_format($orders > 0 ? $revenue / $orders : 0, 2)),
    fn () => metric('Refunds', number_format($refunds), $change($refunds, $sum($before, 'refunds')), inverse: true),
);

// What is not needed every time stays one click away.
expander('How these numbers are counted', function () use ($days): void {
    note('Revenue and orders leave out the orders that were refunded. A refund counts on the day its order was placed.');
    note('The change under a number compares the last ' . $days . ' days with the ' . $days . ' days before them.');
});

chart($now, x: 'day', y: 'revenue', title: 'Revenue per day (USD)');
chart($now, x: 'day', y: ['orders' => 'Orders', 'refunds' => 'Refunds'], type: 'line', title: 'Orders and refunds per day');

heading('Latest orders');
table(
    $shop->orders(days: $days),
    columns: ['id' => 'Order', 'created_at' => 'Placed on', 'customer' => 'Customer', 'items' => 'Items', 'status' => 'Status', 'total' => 'Total'],
    pageSize: 10,
);

Audit log ​

Every pressed button and every download of the demo: who it was, in which tool, with which inputs, and whether a question was answered with yes. The tool only reads the lines that the log: setting of the demo writes.

The audit log: a table with the time, the user, the tool, the button, whether it was confirmed, and the inputs of three presses.

The source: examples/tools/audit.php
php
<?php
// Audit log
// Every button press and every download, who it was and with which inputs.

require_once __DIR__ . '/_shop.php';

use function Runio\ScriptUi\{title, note, table, button, success, rerun};

title('Audit log');
note('The "log" setting in _config.php is called for every button a user presses and for every file a user downloads. This demo writes one line per action to examples/var/audit.log.');

$file = __DIR__ . '/../var/audit.log';
$entries = [];

foreach (is_file($file) ? array_reverse(file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []) : [] as $line) {
    $entry = json_decode($line, true);
    if (is_array($entry)) {
        $entries[] = [
            'time' => date('Y-m-d H:i:s', (int) strtotime((string) $entry['time'])),
            'user' => $entry['user'] ?? 'local',
            'tool' => $entry['tool'],
            'action' => $entry['action'],
            'confirmed' => $entry['confirmed'],
            'file' => $entry['download']['file'] ?? null,
            'inputs' => $entry['inputs'],
            // What the page said is wrong with its inputs in that run. A press that found something wrong did not do its work.
            'found_wrong' => implode(' ', array_merge([], ...array_values(array_filter((array) ($entry['field_errors'] ?? []), is_array(...))))),
        ];
    }
}

table($entries, search: true, empty: 'Nothing logged yet. Refund an order, then come back.');

if (button('Reset the demo data', confirm: 'Bring back the sample orders and empty this log?')) {
    Shop::open()->reset();
    if (is_file($file)) {
        unlink($file);
    }

    success('The demo data is fresh again.');
    rerun();
}

In another language ​

An Arabic page ​

A tool with an Arabic title is Arabic throughout. The page runs from right to left, and the texts that the library writes itself, such as "Reset" and the search box of the table, are Arabic too. German is built in as well, and any other language can be passed in.

An Arabic tool: the title, the labels and the headers of the table are Arabic, and the page runs from right to left.

The source: examples/tools/orders-ar.php
php
<?php
// البحث في الطلبات
// صفحة بالعربية: العنوان العربي يجعل اتجاه الصفحة من اليمين إلى اليسار، ونصوص المكتبة نفسها بالعربية.

require_once __DIR__ . '/_shop.php';

use function Runio\ScriptUi\{title, columns, text, select, metric, table, download};

$shop = Shop::open();

title('البحث في الطلبات');

$email = $status = null;

columns(
    function () use (&$email): void {
        $email = text('البريد الإلكتروني للعميل', placeholder: 'omar@example.com');
    },
    function () use (&$status): void {
        $status = select('حالة الطلب', ['' => 'كل الحالات', 'paid' => 'مدفوع', 'shipped' => 'تم الشحن', 'refunded' => 'مُسترجَع']);
    },
);

$orders = $shop->orders(email: $email === '' ? null : $email, status: $status === '' ? null : $status);

columns(
    fn () => metric('عدد الطلبات', number_format(count($orders))),
    fn () => metric('الإجمالي', '$' . number_format(array_sum(array_column($orders, 'total')), 2)),
);

table(
    $orders,
    columns: ['id' => 'رقم الطلب', 'created_at' => 'التاريخ', 'customer' => 'العميل', 'items' => 'المنتجات', 'total' => 'المبلغ'],
    pageSize: 20,
    search: true,
    empty: 'لا توجد طلبات مطابقة.',
);

// اسم الملف بالعربية، والدالة لا تُستدعى إلا عند طلب الملف.
if ($orders !== []) {
    download('تنزيل CSV', fn () => $orders, 'الطلبات.csv', key: 'download');
}

Released under the MIT License.