{
 "nbformat": 4,
 "nbformat_minor": 0,
 "metadata": {
  "colab": {
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Saguaro Street Coffee: a dashboard you can trust\n",
    "\n",
    "This notebook turns a messy export from a coffee shop's till into a one-page dashboard. Python does every calculation and draws every chart, so every number on the page can be traced back to the file. The AI's job was to write this code and the plain-words explanation, not to do the math in its head.\n",
    "\n",
    "**To run it:** click **Runtime > Run all**, or press the play button on each step in order. Step 1 asks for the file.\n",
    "\n",
    "Saguaro Street Coffee is a made-up shop. Every person and sale in the file is invented for this workshop."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1: Get the sales file"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "cellView": "form"
   },
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title Step 1: Get the sales file\n",
    "#@markdown Upload **sales_export.csv** when the button appears. If the file is already in the Files panel on the left, this step finds it and skips the upload. You can also paste a link to a .csv or .zip file below.\n",
    "import glob\n",
    "import os\n",
    "import shutil\n",
    "import urllib.request\n",
    "import zipfile\n",
    "from pathlib import Path\n",
    "\n",
    "DATA_URL = \"https://www.opzetintent.com/ai-exchange/saguaro-street-coffee-files.zip\"  #@param {type:\"string\"}\n",
    "\n",
    "SRC = None\n",
    "for p in [\"sales_export.csv\", \"/content/sales_export.csv\"] + sorted(glob.glob(\"**/sales_export.csv\", recursive=True)):\n",
    "    if os.path.exists(p):\n",
    "        SRC = Path(p)\n",
    "        break\n",
    "\n",
    "if SRC is None and DATA_URL.strip():\n",
    "    url = DATA_URL.strip()\n",
    "    name = \"download.zip\" if url.lower().split(\"?\")[0].endswith(\".zip\") else \"sales_export.csv\"\n",
    "    urllib.request.urlretrieve(url, name)\n",
    "    if name.endswith(\".zip\"):\n",
    "        with zipfile.ZipFile(name) as z:\n",
    "            member = next((m for m in z.namelist() if m.endswith(\"sales_export.csv\")), None)\n",
    "            if member is None:\n",
    "                raise SystemExit(\"That zip file has no sales_export.csv in it.\")\n",
    "            with z.open(member) as fin, open(\"sales_export.csv\", \"wb\") as fout:\n",
    "                shutil.copyfileobj(fin, fout)\n",
    "    SRC = Path(\"sales_export.csv\")\n",
    "\n",
    "if SRC is None:\n",
    "    try:\n",
    "        from google.colab import files\n",
    "        uploaded = files.upload()\n",
    "        csvs = [n for n in uploaded if n.lower().endswith(\".csv\")]\n",
    "        if not csvs:\n",
    "            raise SystemExit(\"No .csv file was uploaded. Run this step again and pick sales_export.csv.\")\n",
    "        SRC = Path(csvs[0])\n",
    "    except ImportError:\n",
    "        raise SystemExit(\"Put sales_export.csv in the same folder as this notebook, then run this step again.\")\n",
    "\n",
    "print(f\"Using {SRC} ({SRC.stat().st_size / 1e6:.1f} MB)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Look at the file as it came out of the till\n",
    "\n",
    "Two years of sales, one row per item on a receipt. Some rows are refunds, some are voided sales, some were saved twice, and staff typed some item names by hand."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "raw = pd.read_csv(SRC, dtype=str, keep_default_na=False)\n",
    "days = pd.to_datetime(raw[\"Date\"], format=\"%m/%d/%Y\")\n",
    "print(f\"{len(raw):,} rows from {raw['Transaction ID'].nunique():,} receipts, \"\n",
    "      f\"{days.min():%b} {days.min().day}, {days.min().year} to {days.max():%b} {days.max().day}, {days.max().year}\")\n",
    "print()\n",
    "print(\"Kinds of rows:\")\n",
    "print(raw[\"Event Type\"].value_counts().to_string())\n",
    "raw.drop(columns=[\"Customer Name\"]).head(10)   # names are not needed, so they are not shown"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3: Clean it\n",
    "\n",
    "The cleaning follows four rules, written into the code:\n",
    "\n",
    "1. A voided sale is never money.\n",
    "2. A refund is money going back out.\n",
    "3. Blank means unknown. The code never guesses.\n",
    "4. Two matching rows are two sales, unless something in the file proves one is a copy. Here it does: the till writes two of the same item as one line with a quantity of 2, so a line that matches another to the second, on the same receipt, is the same sale saved twice.\n",
    "\n",
    "Customer names are dropped. No number on the dashboard needs them.\n",
    "\n",
    "Click **Show code** on the next cell to see the rules as Python."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "cellView": "form"
   },
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title The cleaning rules, as code\n",
    "import html\n",
    "import math\n",
    "import re\n",
    "import sys\n",
    "import warnings\n",
    "from pathlib import Path\n",
    "\n",
    "import pandas as pd\n",
    "\n",
    "# Some pandas and NumPy versions print a harmless notice about date math.\n",
    "# Hide it so the output stays readable in a live demo.\n",
    "warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n",
    "\n",
    "HERE = Path(__file__).resolve().parent if \"__file__\" in globals() else Path.cwd()\n",
    "DEFAULT_IN = next((p for p in (HERE / \"sales_export.csv\", Path.cwd() / \"sales_export.csv\") if p.exists()),\n",
    "                  HERE / \"sales_export.csv\")\n",
    "DEFAULT_OUT = Path.cwd() / \"dashboard.html\"\n",
    "SHOP_NAME = \"Saguaro Street Coffee\"\n",
    "\n",
    "\n",
    "# ---------------------------------------------------------------------------\n",
    "# Product list. Staff type some names by hand, so many spellings point to one\n",
    "# product. Keys are lower case with spaces, dashes and other marks removed.\n",
    "# ---------------------------------------------------------------------------\n",
    "PRODUCTS = {\n",
    "    \"latte\": \"Latte\",\n",
    "    \"icedlatte\": \"Iced latte\",\n",
    "    \"lavenderoatlatte\": \"Lavender oat latte\",\n",
    "    \"cappuccino\": \"Cappuccino\",\n",
    "    \"mocha\": \"Mocha\",\n",
    "    \"americano\": \"Americano\",\n",
    "    \"drip\": \"Drip coffee\",\n",
    "    \"dripcoffee\": \"Drip coffee\",\n",
    "    \"coldbrew\": \"Cold brew\",\n",
    "    \"chailatte\": \"Chai latte\",\n",
    "    \"pricklypearlemonade\": \"Prickly pear lemonade\",\n",
    "    \"pricklypearlemonaid\": \"Prickly pear lemonade\",\n",
    "    \"blueberrymuffin\": \"Blueberry muffin\",\n",
    "    \"croissant\": \"Croissant\",\n",
    "    \"glutenfreescone\": \"Gluten-free scone\",\n",
    "    \"breakfastburrito\": \"Breakfast burrito\",\n",
    "    \"bfastburrito\": \"Breakfast burrito\",\n",
    "    \"avocadotoast\": \"Avocado toast\",\n",
    "}\n",
    "CATEGORIES = {\"Coffee\": \"Coffee\", \"Food\": \"Food\", \"Tea\": \"Tea\", \"Other Drinks\": \"Other drinks\"}\n",
    "COLUMNS = {\n",
    "    \"Date\": \"date\", \"Time\": \"time\", \"Transaction ID\": \"txn\", \"Category\": \"category_raw\",\n",
    "    \"Item\": \"item\", \"Qty\": \"qty\", \"Gross Sales\": \"gross\", \"Discount Name\": \"discount_name\",\n",
    "    \"Discounts\": \"discount\", \"Net Sales\": \"net\", \"Customer ID\": \"customer_id\",\n",
    "    \"Customer Name\": \"customer_name\", \"Employee\": \"employee\", \"Event Type\": \"line_type\",\n",
    "}\n",
    "COMPARE_WEEKS = 13  # the top tiles compare the last 13 weeks with the same weeks a year earlier\n",
    "\n",
    "\n",
    "def money_to_float(s):\n",
    "    return pd.to_numeric(s.str.strip().str.replace(r\"[\\$,]\", \"\", regex=True), errors=\"coerce\")\n",
    "\n",
    "\n",
    "def key(name):\n",
    "    return \"\".join(ch for ch in str(name).lower() if ch.isalnum())\n",
    "\n",
    "\n",
    "def stated_rate(name):\n",
    "    \"\"\"The discount a name promises: 'Happy Hour 20%' is 20%, a comp is 100%.\"\"\"\n",
    "    m = re.search(r\"(\\d+(?:\\.\\d+)?)\\s*%\", str(name))\n",
    "    if m:\n",
    "        return float(m.group(1)) / 100\n",
    "    return 1.0 if \"comp\" in str(name).lower() else None\n",
    "\n",
    "\n",
    "\n",
    "# ---------------------------------------------------------------------------\n",
    "# Load and clean\n",
    "# ---------------------------------------------------------------------------\n",
    "def load(path):\n",
    "    raw = pd.read_csv(path, dtype=str, keep_default_na=False)\n",
    "    d = raw.rename(columns=COLUMNS).copy()\n",
    "    for c in d.columns:\n",
    "        d[c] = d[c].str.strip()\n",
    "    # Customer names are not needed for any number on the dashboard.\n",
    "    d = d.drop(columns=[\"customer_name\"])\n",
    "    # The till writes two of the same item as one line with a quantity of 2.\n",
    "    # So a second line that matches the first to the second, on the same\n",
    "    # receipt, is the same sale saved twice. Remove the extra copy.\n",
    "    before = len(d)\n",
    "    d = d.drop_duplicates().reset_index(drop=True)\n",
    "    log = {\"rows_in\": len(raw), \"double_saved\": before - len(d)}\n",
    "    for c in [\"gross\", \"discount\", \"net\"]:\n",
    "        d[c] = money_to_float(d[c])\n",
    "    d[\"qty\"] = pd.to_numeric(d[\"qty\"], errors=\"coerce\")\n",
    "    d[\"day\"] = pd.to_datetime(d[\"date\"], format=\"%m/%d/%Y\", errors=\"coerce\")\n",
    "    d[\"hour\"] = pd.to_numeric(d[\"time\"].str[:2], errors=\"coerce\")\n",
    "    # Blank means unknown. Keep it as unknown, never guess.\n",
    "    d[\"customer_id\"] = d[\"customer_id\"].replace(\"\", pd.NA)\n",
    "    d[\"discount_name\"] = d[\"discount_name\"].replace(\"\", pd.NA)\n",
    "    d[\"product\"] = [PRODUCTS.get(key(s), s) for s in d[\"item\"]]\n",
    "    d[\"category\"] = d[\"category_raw\"].map(CATEGORIES).fillna(d[\"category_raw\"])\n",
    "    log[\"renamed\"] = int((d[\"item\"].map(key) != d[\"product\"].map(key)).sum())\n",
    "    log[\"rows_out\"] = len(d)\n",
    "    return raw, d, log"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "raw, d, log = load(SRC)\n",
    "\n",
    "spellings = (d.groupby(\"product\")[\"item\"].unique()\n",
    "               .map(lambda names: \", \".join(sorted(names)))\n",
    "               .rename(\"Typed in the till as\"))\n",
    "print(f\"{log['double_saved']:,} rows were the same sale saved twice. The extra copies are gone: \"\n",
    "      f\"{log['rows_in']:,} rows in, {log['rows_out']:,} kept.\")\n",
    "print(f\"{log['renamed']:,} rows had an item name typed a short or misspelled way. Each spelling now points to one product.\")\n",
    "print(f\"{(d['line_type'] == 'Void').sum():,} voided lines will not count as money.\")\n",
    "print(f\"{(d['line_type'] == 'Refund').sum():,} refund lines count as money going back out.\")\n",
    "print(f\"{d['customer_id'].isna().sum():,} rows have no customer number. They stay unknown, not guessed.\")\n",
    "spellings.to_frame()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4: Do the math\n",
    "\n",
    "The code compares the last 13 weeks with the same 13 weeks a year earlier, so the season is the same on both sides. It also finds the day prices went up and the day a new discount started, straight from the file."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "cellView": "form"
   },
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title The math, as code\n",
    "# ---------------------------------------------------------------------------\n",
    "# Math\n",
    "# ---------------------------------------------------------------------------\n",
    "def period_stats(money, start, end):\n",
    "    m = money[(money[\"day\"] >= start) & (money[\"day\"] < end)]\n",
    "    pay = m[m[\"line_type\"] == \"Payment\"]\n",
    "    ref = m[m[\"line_type\"] == \"Refund\"]\n",
    "    sales = m[\"net\"].sum()\n",
    "    count = pay[\"txn\"].nunique()\n",
    "    days = (end - start).days\n",
    "    return {\n",
    "        \"sales\": sales,\n",
    "        \"count\": count,\n",
    "        \"avg\": sales / count if count else 0.0,\n",
    "        \"refunds\": -ref[\"net\"].sum(),\n",
    "        \"refund_lines\": len(ref),\n",
    "        \"discounts\": -pay[\"discount\"].sum(),\n",
    "        \"days\": days,\n",
    "        \"weeks\": days / 7,\n",
    "    }\n",
    "\n",
    "\n",
    "def find_price_change(pay):\n",
    "    \"\"\"First day the regular price of the products went up.\"\"\"\n",
    "    p = pay.assign(unit=pay[\"gross\"] / pay[\"qty\"]).sort_values(\"day\")\n",
    "    first_price = p.groupby(\"product\")[\"unit\"].first()\n",
    "    rises = []\n",
    "    for prod, g in p.groupby(\"product\"):\n",
    "        up = g[g[\"unit\"] > first_price[prod] + 0.001]\n",
    "        if len(up):\n",
    "            rises.append(up[\"day\"].min())\n",
    "    if not rises:\n",
    "        return None, 0\n",
    "    day = pd.Series(rises).mode().iloc[0]\n",
    "    return day, sum(1 for r in rises if r == day)\n",
    "\n",
    "\n",
    "def compute(d):\n",
    "    data_start = d[\"day\"].min()\n",
    "    data_end = d[\"day\"].max()\n",
    "    week0 = data_start - pd.Timedelta(days=int(data_start.weekday()))\n",
    "    d[\"week\"] = ((d[\"day\"] - week0).dt.days // 7).astype(int)\n",
    "    d[\"week_start\"] = week0 + pd.to_timedelta(d[\"week\"] * 7, unit=\"D\")\n",
    "\n",
    "    money = d[d[\"line_type\"] != \"Void\"].copy()  # a voided sale is never money\n",
    "    pay = money[money[\"line_type\"] == \"Payment\"]\n",
    "    ref = money[money[\"line_type\"] == \"Refund\"]\n",
    "    total_sales = money[\"net\"].sum()\n",
    "    total_count = pay[\"txn\"].nunique()\n",
    "\n",
    "    # Weeks\n",
    "    weekly = pd.DataFrame({\n",
    "        \"sales\": money.groupby(\"week_start\")[\"net\"].sum(),\n",
    "        \"count\": pay.groupby(\"week_start\")[\"txn\"].nunique(),\n",
    "        \"refund_lines\": ref.groupby(\"week_start\").size(),\n",
    "        \"discounts\": -pay.groupby(\"week_start\")[\"discount\"].sum(),\n",
    "        \"days\": d.groupby(\"week_start\")[\"day\"].nunique(),\n",
    "    }).fillna(0).sort_index()\n",
    "    weekly[\"avg\"] = weekly[\"sales\"] / weekly[\"count\"]\n",
    "    full_weeks = weekly[weekly[\"days\"] == 7]\n",
    "\n",
    "    # Top tiles: the last 13 full weeks against the same 13 weeks a year\n",
    "    # earlier, so the season is the same on both sides.\n",
    "    last = full_weeks.index[-COMPARE_WEEKS:]\n",
    "    now_start, now_end = last[0], last[-1] + pd.Timedelta(days=7)\n",
    "    yr_start, yr_end = now_start - pd.Timedelta(days=364), now_end - pd.Timedelta(days=364)\n",
    "    now = period_stats(money, now_start, now_end)\n",
    "    year_ago = period_stats(money, yr_start, yr_end)\n",
    "\n",
    "    # Price change: from that day to the end, against the same days a year earlier\n",
    "    price_day, n_products_up = find_price_change(pay)\n",
    "    price = None\n",
    "    if price_day is not None:\n",
    "        a_start, a_end = price_day, data_end + pd.Timedelta(days=1)\n",
    "        b_start, b_end = a_start - pd.Timedelta(days=364), a_end - pd.Timedelta(days=364)\n",
    "        before_p = pay[(pay[\"day\"] >= price_day - pd.Timedelta(days=91)) & (pay[\"day\"] < price_day)]\n",
    "        after_p = pay[(pay[\"day\"] >= price_day) & (pay[\"day\"] < price_day + pd.Timedelta(days=91))]\n",
    "        old_u = (before_p[\"gross\"] / before_p[\"qty\"]).groupby(before_p[\"product\"]).median()\n",
    "        new_u = (after_p[\"gross\"] / after_p[\"qty\"]).groupby(after_p[\"product\"]).median()\n",
    "        units = before_p.groupby(\"product\")[\"qty\"].sum()\n",
    "        common = old_u.index.intersection(new_u.index)\n",
    "        price = {\n",
    "            \"day\": price_day,\n",
    "            \"products\": n_products_up,\n",
    "            \"rise\": (units[common] * new_u[common]).sum() / (units[common] * old_u[common]).sum() - 1,\n",
    "            \"after\": period_stats(money, a_start, a_end),\n",
    "            \"year_before\": period_stats(money, b_start, b_end),\n",
    "            \"a_start\": a_start, \"a_end\": a_end,\n",
    "        }\n",
    "\n",
    "    # Discounts: when each one ran, what it gave away, and which are new\n",
    "    disc = pay[pay[\"discount_name\"].notna()]\n",
    "    discounts = pd.DataFrame({\n",
    "        \"first\": disc.groupby(\"discount_name\")[\"day\"].min(),\n",
    "        \"last\": disc.groupby(\"discount_name\")[\"day\"].max(),\n",
    "        \"uses\": disc.groupby(\"discount_name\")[\"txn\"].nunique(),\n",
    "        \"given\": -disc.groupby(\"discount_name\")[\"discount\"].sum(),\n",
    "    }).sort_values(\"given\", ascending=False)\n",
    "    discounts[\"new\"] = discounts[\"first\"] > data_start + pd.Timedelta(days=28)\n",
    "\n",
    "    # The biggest new discount that is still running, and the hours it covers\n",
    "    promo = None\n",
    "    running = discounts[discounts[\"new\"] & (discounts[\"last\"] >= data_end - pd.Timedelta(days=14))]\n",
    "    if len(running):\n",
    "        name = running[\"given\"].idxmax()\n",
    "        rows = disc[disc[\"discount_name\"] == name]\n",
    "        hours = sorted(rows[\"hour\"].value_counts().loc[lambda s: s >= 0.05 * len(rows)].index)\n",
    "        p_start = discounts.loc[name, \"first\"]\n",
    "        span = min((p_start - data_start).days, (data_end - p_start).days + 1, 91)\n",
    "        b0, b1 = p_start - pd.Timedelta(days=span), p_start\n",
    "        a0, a1 = p_start, p_start + pd.Timedelta(days=span)\n",
    "\n",
    "        def visits_by_hour(start, end):\n",
    "            p = pay[(pay[\"day\"] >= start) & (pay[\"day\"] < end)]\n",
    "            return p.groupby(\"hour\")[\"txn\"].nunique() / (end - start).days\n",
    "\n",
    "        before_h = visits_by_hour(b0, b1)\n",
    "        after_h = visits_by_hour(a0, a1)\n",
    "        last_b = visits_by_hour(b0 - pd.Timedelta(days=364), b1 - pd.Timedelta(days=364))\n",
    "        last_a = visits_by_hour(a0 - pd.Timedelta(days=364), a1 - pd.Timedelta(days=364))\n",
    "        inside = before_h.index.isin(hours)\n",
    "\n",
    "        def sales_in_hours(start, end):\n",
    "            m = money[(money[\"day\"] >= start) & (money[\"day\"] < end) & money[\"hour\"].isin(hours)]\n",
    "            return m[\"net\"].sum() / (end - start).days\n",
    "\n",
    "        promo = {\n",
    "            \"name\": name,\n",
    "            \"start\": p_start,\n",
    "            \"hours\": hours,\n",
    "            \"given\": float(discounts.loc[name, \"given\"]),\n",
    "            \"uses\": int(discounts.loc[name, \"uses\"]),\n",
    "            \"days\": span,\n",
    "            \"b0\": b0, \"b1\": b1, \"a0\": a0, \"a1\": a1,\n",
    "            \"before_h\": before_h, \"after_h\": after_h,\n",
    "            \"in_before\": before_h[inside].sum(), \"in_after\": after_h.reindex(hours).fillna(0).sum(),\n",
    "            \"out_before\": before_h[~inside].sum(), \"out_after\": after_h[~after_h.index.isin(hours)].sum(),\n",
    "            \"in_sales_before\": sales_in_hours(b0, b1), \"in_sales_after\": sales_in_hours(a0, a1),\n",
    "            \"given_per_day\": -rows[(rows[\"day\"] >= a0) & (rows[\"day\"] < a1)][\"discount\"].sum() / span,\n",
    "            \"given_now\": -rows[(rows[\"day\"] >= now_start) & (rows[\"day\"] < now_end)][\"discount\"].sum(),\n",
    "            \"in_last_chg\": change(last_a.reindex(hours).fillna(0).sum(), last_b.reindex(hours).fillna(0).sum()),\n",
    "            \"out_last_chg\": change(last_a[~last_a.index.isin(hours)].sum(), last_b[~last_b.index.isin(hours)].sum()),\n",
    "        }\n",
    "\n",
    "    # Refunds: find the week where one item was refunded far more than usual\n",
    "    spike = None\n",
    "    rw = ref.groupby([\"week_start\", \"product\"]).size().unstack(fill_value=0).reindex(full_weeks.index, fill_value=0)\n",
    "    if len(rw):\n",
    "        typical = rw.median()\n",
    "        jump = rw - typical\n",
    "        week, prod = jump.stack().idxmax()\n",
    "        count = int(rw.loc[week, prod])\n",
    "        if count >= 5 and count >= 3 * max(typical[prod], 1):\n",
    "            others = rw[prod].drop(week)\n",
    "            sold = pay[(pay[\"week_start\"] == week) & (pay[\"product\"] == prod)][\"qty\"].sum()\n",
    "            sold_typical = pay[pay[\"product\"] == prod].groupby(\"week_start\")[\"qty\"].sum().median()\n",
    "            wref = ref[(ref[\"week_start\"] == week) & (ref[\"product\"] == prod)]\n",
    "            spike = {\n",
    "                \"week\": week,\n",
    "                \"product\": prod,\n",
    "                \"count\": count,\n",
    "                \"typical_week\": float(others.mean()),\n",
    "                \"max_other\": int(others.max()),\n",
    "                \"dollars\": float(-wref[\"net\"].sum()),\n",
    "                \"sold\": int(sold),\n",
    "                \"sold_typical\": float(sold_typical),\n",
    "                \"staff\": int(wref[\"employee\"].nunique()),\n",
    "                \"days\": int(wref[\"day\"].nunique()),\n",
    "            }\n",
    "    refund_weeks = rw.sum(axis=1)\n",
    "\n",
    "    # Items and categories over the whole file\n",
    "    by_item = money.groupby(\"product\")[\"net\"].sum().sort_values(ascending=False)\n",
    "    by_cat = money.groupby(\"category\")[\"net\"].sum().sort_values(ascending=False)\n",
    "\n",
    "    return {\n",
    "        \"d\": d, \"money\": money, \"weekly\": weekly, \"full_weeks\": full_weeks,\n",
    "        \"data_start\": data_start, \"data_end\": data_end,\n",
    "        \"total_sales\": total_sales, \"total_count\": total_count,\n",
    "        \"now\": now, \"year_ago\": year_ago,\n",
    "        \"now_start\": now_start, \"now_end\": now_end, \"yr_start\": yr_start, \"yr_end\": yr_end,\n",
    "        \"price\": price, \"discounts\": discounts, \"promo\": promo,\n",
    "        \"spike\": spike, \"refund_weeks\": refund_weeks, \"refund_by_item\": rw,\n",
    "        \"by_item\": by_item, \"by_cat\": by_cat,\n",
    "    }\n",
    "\n",
    "\n",
    "\n",
    "# ---------------------------------------------------------------------------\n",
    "# Formatting helpers\n",
    "# ---------------------------------------------------------------------------\n",
    "def usd(x, cents=False):\n",
    "    return f\"${x:,.2f}\" if cents else f\"${x:,.0f}\"\n",
    "\n",
    "\n",
    "def pct(x):\n",
    "    return f\"{abs(x) * 100:.0f}%\"\n",
    "\n",
    "\n",
    "def day_label(ts):\n",
    "    return f\"{ts.strftime('%b')} {ts.day}\"\n",
    "\n",
    "\n",
    "def day_label_year(ts):\n",
    "    return f\"{ts.strftime('%b')} {ts.day}, {ts.year}\"\n",
    "\n",
    "\n",
    "def change(a, b):\n",
    "    return (a - b) / b if b else 0.0\n",
    "\n",
    "\n",
    "def esc(s):\n",
    "    return html.escape(str(s), quote=True)\n",
    "\n",
    "\n",
    "def round_to(x, step):\n",
    "    return int(round(x / step) * step)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "R = compute(d)\n",
    "now, yr, price, P = R[\"now\"], R[\"year_ago\"], R[\"price\"], R[\"promo\"]\n",
    "\n",
    "if price:\n",
    "    print(f\"Prices went up on {day_label_year(price['day'])}, by about {pct(price['rise'])} on average.\")\n",
    "if P:\n",
    "    print(f\"{P['name']} started on {day_label_year(P['start'])}.\")\n",
    "print(f\"Comparing the last {now['weeks']:.0f} weeks ({day_label(R['now_start'])} to \"\n",
    "      f\"{day_label_year(R['now_end'] - pd.Timedelta(days=1))}) with the same weeks a year earlier.\")\n",
    "rows = [\n",
    "    (\"Sales\", usd(yr[\"sales\"]), usd(now[\"sales\"]), change(now[\"sales\"], yr[\"sales\"])),\n",
    "    (\"Number of sales\", f\"{yr['count']:,}\", f\"{now['count']:,}\", change(now[\"count\"], yr[\"count\"])),\n",
    "    (\"Average sale\", usd(yr[\"avg\"], True), usd(now[\"avg\"], True), change(now[\"avg\"], yr[\"avg\"])),\n",
    "    (\"Refunds\", usd(yr[\"refunds\"]), usd(now[\"refunds\"]), change(now[\"refunds\"], yr[\"refunds\"])),\n",
    "    (\"Discounts given\", usd(yr[\"discounts\"]), usd(now[\"discounts\"]), change(now[\"discounts\"], yr[\"discounts\"])),\n",
    "]\n",
    "pd.DataFrame([(n, x, y, f\"{'Up' if c > 0 else 'Down'} {pct(c)}\") for n, x, y, c in rows],\n",
    "             columns=[\"\", \"A year earlier\", \"Last 13 weeks\", \"Change\"]).set_index(\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 5: Check that the totals add up\n",
    "\n",
    "Before anything is shown, the code checks its own work: every row readable, every discount matches the rate in its name, every refund points back to a sale, the weeks add up to the total, and so on. If any check fails, the dashboard shows a stop page instead of numbers."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "cellView": "form"
   },
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title The checks, as code\n",
    "# ---------------------------------------------------------------------------\n",
    "# Checks: the totals must add up before anything is shown\n",
    "# ---------------------------------------------------------------------------\n",
    "def run_checks(d, R):\n",
    "    checks = []\n",
    "    money, weekly = R[\"money\"], R[\"weekly\"]\n",
    "\n",
    "    def add(ok, plain):\n",
    "        checks.append((bool(ok), plain))\n",
    "\n",
    "    add(d[\"day\"].notna().all(), \"Every row has a date the code can read.\")\n",
    "    add(d[[\"gross\", \"discount\", \"net\", \"qty\"]].notna().all().all(), \"Every row has amounts the code can read.\")\n",
    "    add(d[\"line_type\"].isin([\"Payment\", \"Refund\", \"Void\"]).all(), \"Every row is a payment, a refund or a voided sale.\")\n",
    "    add(((d[\"net\"].abs() - (d[\"gross\"].abs() - d[\"discount\"].abs())).abs() < 0.005).all(),\n",
    "        \"On every row, the line amount minus the discount equals the amount charged.\")\n",
    "    rate = d[\"discount_name\"].map(stated_rate)\n",
    "    named = d[d[\"discount_name\"].notna()]\n",
    "    add(rate[named.index].notna().all()\n",
    "        and ((named[\"discount\"].abs() - rate[named.index] * named[\"gross\"].abs()).abs() <= 0.011).all(),\n",
    "        \"Every discount matches the rate in its name, to the cent.\")\n",
    "    pay = d[d[\"line_type\"] == \"Payment\"]\n",
    "    ref = d[d[\"line_type\"] == \"Refund\"]\n",
    "    add((pay[\"net\"] >= 0).all() and (ref[\"net\"] <= 0).all(), \"Payments are money in and refunds are money out.\")\n",
    "    k = [\"txn\", \"product\"]\n",
    "    matched = ref.merge(pay[k].drop_duplicates(), on=k, how=\"left\", indicator=True)\n",
    "    add((matched[\"_merge\"] == \"both\").all(), \"Every refund points back to a sale of that item on the same receipt.\")\n",
    "    add(not money[\"line_type\"].eq(\"Void\").any(), \"No voided sale is counted as money.\")\n",
    "    add(abs(weekly[\"sales\"].sum() - R[\"total_sales\"]) < 0.01, \"The weeks add up to the total sales.\")\n",
    "    add(abs(R[\"by_cat\"].sum() - R[\"total_sales\"]) < 0.01, \"The categories add up to the total sales.\")\n",
    "    add(abs(R[\"by_item\"].sum() - R[\"total_sales\"]) < 0.01, \"The items add up to the total sales.\")\n",
    "    add(weekly[\"count\"].sum() == R[\"total_count\"], \"The weekly counts add up to the total number of sales.\")\n",
    "    return checks"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "checks = run_checks(d, R)\n",
    "for ok, text in checks:\n",
    "    print((\"PASS  \" if ok else \"FAIL  \") + text)\n",
    "passed = sum(ok for ok, _ in checks)\n",
    "print()\n",
    "print(f\"{passed} of {len(checks)} checks passed.\" + (\"\" if passed == len(checks) else\n",
    "      \" The dashboard will show a stop page instead of numbers.\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 6: Draw the charts\n",
    "\n",
    "Python draws each chart. The chart titles are written from the numbers, so a title like \"Weekly sales are down 6%\" only appears when the math says so."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "cellView": "form"
   },
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title Chart, wording and page code\n",
    "# ---------------------------------------------------------------------------\n",
    "# Charts (inline SVG)\n",
    "# ---------------------------------------------------------------------------\n",
    "W = 400  # every chart is drawn on a 400-wide canvas and scales to fit\n",
    "\n",
    "\n",
    "def nice_max(v):\n",
    "    if v <= 0:\n",
    "        return 1\n",
    "    mag = 10 ** math.floor(math.log10(v))\n",
    "    for m in (1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10):\n",
    "        if m * mag >= v:\n",
    "            return m * mag\n",
    "    return 10 * mag\n",
    "\n",
    "\n",
    "def short_money(v):\n",
    "    if v >= 1000:\n",
    "        k = v / 1000\n",
    "        return f\"${k:.0f}K\" if abs(k - round(k)) < 0.05 else f\"${k:.1f}K\"\n",
    "    return f\"${v:.0f}\"\n",
    "\n",
    "\n",
    "def bar_path(x, y, w, h, r=4):\n",
    "    \"\"\"Vertical bar, rounded top, square bottom.\"\"\"\n",
    "    if h <= 0:\n",
    "        return \"\"\n",
    "    r = min(r, w / 2, h)\n",
    "    return (f\"M{x:.1f},{y + h:.1f} V{y + r:.1f} Q{x:.1f},{y:.1f} {x + r:.1f},{y:.1f} \"\n",
    "            f\"H{x + w - r:.1f} Q{x + w:.1f},{y:.1f} {x + w:.1f},{y + r:.1f} V{y + h:.1f} Z\")\n",
    "\n",
    "\n",
    "def nice_ticks(lo, hi, n=4):\n",
    "    \"\"\"Axis lines at tidy steps (1, 2, 2.5 or 5 times a power of ten) that cover lo to hi.\"\"\"\n",
    "    span = (hi - lo) or abs(hi) or 1\n",
    "    mag = 10 ** math.floor(math.log10(span / n))\n",
    "    step = next(m * mag for m in (1, 2, 2.5, 5, 10) if span / (m * mag) <= n)\n",
    "    first, last = math.floor(lo / step + 1e-9), math.ceil(hi / step - 1e-9)\n",
    "    return [k * step for k in range(first, last + 1)]\n",
    "\n",
    "\n",
    "def hour_label(h):\n",
    "    h = int(h)\n",
    "    return f\"{h % 12 or 12} {'AM' if h < 12 else 'PM'}\"\n",
    "\n",
    "\n",
    "def week_x(day, first_week, left, pw, n):\n",
    "    \"\"\"Where a day falls along a line of weekly points.\"\"\"\n",
    "    return left + pw * ((day - first_week).days / 7) / (n - 1)\n",
    "\n",
    "\n",
    "def short_name(name):\n",
    "    \"\"\"'Happy Hour 20%' becomes 'Happy Hour'.\"\"\"\n",
    "    return re.sub(r\"\\s*\\d+(\\.\\d+)?\\s*%$\", \"\", str(name)).strip()\n",
    "\n",
    "\n",
    "def markers(R):\n",
    "    out = []\n",
    "    if R[\"price\"]:\n",
    "        out.append((R[\"price\"][\"day\"], \"Prices up\"))\n",
    "    if R[\"promo\"]:\n",
    "        out.append((R[\"promo\"][\"start\"], short_name(R[\"promo\"][\"name\"]) + \" starts\"))\n",
    "    return out\n",
    "\n",
    "\n",
    "def chart_weekly(R):\n",
    "    \"\"\"Sales each week over the whole file, with the price rise and the new discount marked.\"\"\"\n",
    "    wk = R[\"full_weeks\"][\"sales\"]\n",
    "    Wd, H = 800, 260\n",
    "    left, right, top, bottom = 52, 12, 34, 30\n",
    "    pw, ph = Wd - left - right, H - top - bottom\n",
    "    ticks = nice_ticks(wk.min(), wk.max())\n",
    "    lo, hi = ticks[0], ticks[-1]\n",
    "    n = len(wk)\n",
    "    first = wk.index[0]\n",
    "\n",
    "    def y(v):\n",
    "        return top + ph - ph * (v - lo) / (hi - lo)\n",
    "\n",
    "    out = [f'<svg viewBox=\"0 0 {Wd} {H}\" role=\"img\" aria-label=\"Weekly sales line chart\">']\n",
    "    for v in ticks:\n",
    "        out.append(f'<line class=\"grid\" x1=\"{left}\" x2=\"{Wd - right}\" y1=\"{y(v):.1f}\" y2=\"{y(v):.1f}\"/>')\n",
    "        out.append(f'<text class=\"tick\" x=\"{left - 6}\" y=\"{y(v) + 4:.1f}\" text-anchor=\"end\">{short_money(v)}</text>')\n",
    "    for day, label in markers(R):\n",
    "        x = week_x(day, first, left, pw, n)\n",
    "        out.append(f'<line class=\"marker\" x1=\"{x:.1f}\" x2=\"{x:.1f}\" y1=\"{top - 12}\" y2=\"{top + ph}\"/>')\n",
    "        out.append(f'<text class=\"note\" x=\"{x + 4:.1f}\" y=\"{top - 4}\">{esc(label)}</text>')\n",
    "    pts = [(left + pw * i / (n - 1), y(v)) for i, v in enumerate(wk.values)]\n",
    "    out.append(f'<path class=\"line1\" d=\"M{\" L\".join(f\"{a:.1f},{b:.1f}\" for a, b in pts)}\"/>')\n",
    "    for (px, py), (ws, v) in zip(pts, wk.items()):\n",
    "        out.append(f'<g><title>Week of {esc(day_label_year(ws))}: {esc(usd(v))}</title>'\n",
    "                   f'<circle class=\"hitdot\" cx=\"{px:.1f}\" cy=\"{py:.1f}\" r=\"5\"/></g>')\n",
    "    out.append(f'<circle class=\"dot1\" cx=\"{pts[-1][0]:.1f}\" cy=\"{pts[-1][1]:.1f}\" r=\"4\"/>')\n",
    "    for i, ws in enumerate(wk.index):\n",
    "        # label the first week of each quarter\n",
    "        if ws.month in (1, 4, 7, 10) and ws.day <= 7:\n",
    "            x = left + pw * i / (n - 1)\n",
    "            out.append(f'<text class=\"tick\" x=\"{x:.1f}\" y=\"{H - 8}\" text-anchor=\"middle\">{ws.strftime(\"%b %Y\")}</text>')\n",
    "    out.append(f'<line class=\"axis\" x1=\"{left}\" x2=\"{Wd - right}\" y1=\"{top + ph}\" y2=\"{top + ph}\"/>')\n",
    "    out.append(\"</svg>\")\n",
    "    return \"\".join(out)\n",
    "\n",
    "\n",
    "def mini_line(series, label_fmt, title, R, H=170):\n",
    "    left, right, top, bottom = 52, 10, 26, 24\n",
    "    width = W / 2 - 6\n",
    "    pw, ph = width - left - right, H - top - bottom\n",
    "    ticks = nice_ticks(series.min(), series.max(), 3)\n",
    "    lo, hi = ticks[0], ticks[-1]\n",
    "    n = len(series)\n",
    "    first = series.index[0]\n",
    "\n",
    "    def y(v):\n",
    "        return top + ph - ph * (v - lo) / (hi - lo)\n",
    "\n",
    "    out = [f'<svg viewBox=\"0 0 {width:.0f} {H}\" role=\"img\" aria-label=\"{esc(title)}\">',\n",
    "           f'<text class=\"label\" x=\"0\" y=\"12\">{esc(title)}</text>']\n",
    "    for v in ticks:\n",
    "        out.append(f'<line class=\"grid\" x1=\"{left}\" x2=\"{width - right}\" y1=\"{y(v):.1f}\" y2=\"{y(v):.1f}\"/>')\n",
    "        out.append(f'<text class=\"tick\" x=\"{left - 5}\" y=\"{y(v) + 4:.1f}\" text-anchor=\"end\">{label_fmt(v)}</text>')\n",
    "    for day, _ in markers(R):\n",
    "        x = week_x(day, first, left, pw, n)\n",
    "        out.append(f'<line class=\"marker\" x1=\"{x:.1f}\" x2=\"{x:.1f}\" y1=\"{top}\" y2=\"{top + ph}\"/>')\n",
    "    pts = [(left + pw * i / (n - 1), y(v)) for i, v in enumerate(series.values)]\n",
    "    out.append(f'<path class=\"line1\" d=\"M{\" L\".join(f\"{a:.1f},{b:.1f}\" for a, b in pts)}\"/>')\n",
    "    for (px, py), (ws, v) in zip(pts, series.items()):\n",
    "        out.append(f'<g><title>Week of {esc(day_label_year(ws))}: {esc(label_fmt(v, True))}</title>'\n",
    "                   f'<circle class=\"hitdot\" cx=\"{px:.1f}\" cy=\"{py:.1f}\" r=\"4\"/></g>')\n",
    "    out.append(f'<circle class=\"dot1\" cx=\"{pts[-1][0]:.1f}\" cy=\"{pts[-1][1]:.1f}\" r=\"3.5\"/>')\n",
    "    out.append(f'<text class=\"tick\" x=\"{left}\" y=\"{H - 6}\">{series.index[0].strftime(\"%b %Y\")}</text>')\n",
    "    out.append(f'<text class=\"tick\" x=\"{width - right}\" y=\"{H - 6}\" text-anchor=\"end\">{series.index[-1].strftime(\"%b %Y\")}</text>')\n",
    "    out.append(\"</svg>\")\n",
    "    return \"\".join(out)\n",
    "\n",
    "\n",
    "def chart_count_and_avg(R):\n",
    "    fw = R[\"full_weeks\"]\n",
    "    a = mini_line(fw[\"count\"], lambda v, full=False: f\"{v:,.0f}\", \"Sales a week\", R)\n",
    "    b = mini_line(fw[\"avg\"], lambda v, full=False: usd(v, True), \"Average sale\", R)\n",
    "    return f'<div class=\"pair\">{a}{b}</div>'\n",
    "\n",
    "\n",
    "def chart_hours(R):\n",
    "    \"\"\"Visits a day in each hour, before and after the new discount started.\"\"\"\n",
    "    P = R[\"promo\"]\n",
    "    hours = sorted(set(P[\"before_h\"].index) | set(P[\"after_h\"].index))\n",
    "    b = P[\"before_h\"].reindex(hours).fillna(0)\n",
    "    a = P[\"after_h\"].reindex(hours).fillna(0)\n",
    "    H = 250\n",
    "    left, right, top, bottom = 34, 8, 24, 30\n",
    "    pw, ph = W - left - right, H - top - bottom\n",
    "    ticks = nice_ticks(0, max(b.max(), a.max()))\n",
    "    vmax = ticks[-1]\n",
    "    slot = pw / len(hours)\n",
    "    bw = min(14, (slot - 8) / 2)\n",
    "    out = [f'<svg viewBox=\"0 0 {W} {H}\" role=\"img\" aria-label=\"Visits by hour of day, before and after\">']\n",
    "    for i, h in enumerate(hours):\n",
    "        if h in P[\"hours\"]:\n",
    "            x = left + i * slot\n",
    "            out.append(f'<rect class=\"band\" x=\"{x:.1f}\" y=\"{top}\" width=\"{slot:.1f}\" height=\"{ph}\"/>')\n",
    "    hh = [i for i, h in enumerate(hours) if h in P[\"hours\"]]\n",
    "    if hh:\n",
    "        x = left + (hh[0] + (hh[-1] + 1)) / 2 * slot\n",
    "        out.append(f'<text class=\"note\" x=\"{x:.1f}\" y=\"{top - 8}\" text-anchor=\"middle\">{esc(short_name(P[\"name\"]))}</text>')\n",
    "    for v in ticks:\n",
    "        yy = top + ph - ph * v / vmax\n",
    "        out.append(f'<line class=\"grid\" x1=\"{left}\" x2=\"{W - right}\" y1=\"{yy:.1f}\" y2=\"{yy:.1f}\"/>')\n",
    "        out.append(f'<text class=\"tick\" x=\"{left - 6}\" y=\"{yy + 4:.1f}\" text-anchor=\"end\">{v:.0f}</text>')\n",
    "    for i, h in enumerate(hours):\n",
    "        x0 = left + i * slot + (slot - 2 * bw - 2) / 2\n",
    "        for j, (cls, v, when) in enumerate(((\"sb\", b[h], \"Before\"), (\"s1\", a[h], \"After\"))):\n",
    "            hgt = ph * v / vmax\n",
    "            x = x0 + j * (bw + 2)\n",
    "            out.append(f'<g><title>{esc(hour_label(h))}, {when.lower()}: {v:.1f} visits a day</title>'\n",
    "                       f'<path class=\"{cls}\" d=\"{bar_path(x, top + ph - hgt, bw, hgt, 3)}\"/></g>')\n",
    "        out.append(f'<text class=\"tick\" x=\"{left + i * slot + slot / 2:.1f}\" y=\"{H - bottom + 16}\" '\n",
    "                   f'text-anchor=\"middle\">{esc(hour_label(h))}</text>')\n",
    "    out.append(f'<line class=\"axis\" x1=\"{left}\" x2=\"{W - right}\" y1=\"{top + ph}\" y2=\"{top + ph}\"/>')\n",
    "    out.append(\"</svg>\")\n",
    "    legend = (f'<div class=\"legend\"><span><i class=\"kb\"></i>{P[\"days\"] // 7} weeks before</span>'\n",
    "              f'<span><i class=\"k1\"></i>{P[\"days\"] // 7} weeks after</span></div>')\n",
    "    return legend + \"\".join(out)\n",
    "\n",
    "\n",
    "def chart_refunds(R, weeks=26):\n",
    "    \"\"\"Refunds each week for the last half year, with the problem item in orange.\"\"\"\n",
    "    rw = R[\"refund_by_item\"].tail(weeks)\n",
    "    S = R[\"spike\"]\n",
    "    spike_item = S[\"product\"] if S else None\n",
    "    hot = rw[spike_item] if spike_item else pd.Series(0, index=rw.index)\n",
    "    rest = rw.sum(axis=1) - hot\n",
    "    H = 250\n",
    "    left, right, top, bottom = 34, 8, 16, 30\n",
    "    pw, ph = W - left - right, H - top - bottom\n",
    "    ticks = nice_ticks(0, (rest + hot).max())\n",
    "    vmax = ticks[-1]\n",
    "    slot = pw / len(rw)\n",
    "    bw = min(12, slot - 3)\n",
    "    out = [f'<svg viewBox=\"0 0 {W} {H}\" role=\"img\" aria-label=\"Refunds each week\">']\n",
    "    for v in ticks:\n",
    "        yy = top + ph - ph * v / vmax\n",
    "        out.append(f'<line class=\"grid\" x1=\"{left}\" x2=\"{W - right}\" y1=\"{yy:.1f}\" y2=\"{yy:.1f}\"/>')\n",
    "        out.append(f'<text class=\"tick\" x=\"{left - 6}\" y=\"{yy + 4:.1f}\" text-anchor=\"end\">{v:.0f}</text>')\n",
    "    for i, ws in enumerate(rw.index):\n",
    "        x = left + i * slot + (slot - bw) / 2\n",
    "        h_rest = ph * rest[ws] / vmax\n",
    "        h_hot = ph * hot[ws] / vmax\n",
    "        y_rest = top + ph - h_rest\n",
    "        tip = f\"Week of {day_label_year(ws)}: {int(rest[ws] + hot[ws])} refunds\"\n",
    "        if spike_item:\n",
    "            tip += f\", {int(hot[ws])} of them {spike_item.lower()}\"\n",
    "        out.append(f'<g><title>{esc(tip)}</title>')\n",
    "        if h_hot > 0:\n",
    "            out.append(f'<path class=\"s1\" d=\"{bar_path(x, y_rest, bw, h_rest, 0)}\"/>')\n",
    "            out.append(f'<path class=\"s2\" d=\"{bar_path(x, y_rest - h_hot, bw, max(h_hot - 1.5, 0.5), 3)}\"/>')\n",
    "        else:\n",
    "            out.append(f'<path class=\"s1\" d=\"{bar_path(x, y_rest, bw, h_rest, 3)}\"/>')\n",
    "        out.append(f'<rect class=\"hit\" x=\"{left + i * slot:.1f}\" y=\"{top}\" width=\"{slot:.1f}\" height=\"{ph}\"/></g>')\n",
    "        if (len(rw) - 1 - i) % 6 == 0:\n",
    "            out.append(f'<text class=\"tick\" x=\"{x + bw / 2:.1f}\" y=\"{H - bottom + 16}\" text-anchor=\"middle\">{day_label(ws)}</text>')\n",
    "    out.append(f'<line class=\"axis\" x1=\"{left}\" x2=\"{W - right}\" y1=\"{top + ph}\" y2=\"{top + ph}\"/>')\n",
    "    out.append(\"</svg>\")\n",
    "    legend = '<div class=\"legend\"><span><i class=\"k1\"></i>Other items</span>'\n",
    "    if spike_item:\n",
    "        legend += f'<span><i class=\"k2\"></i>{esc(spike_item.capitalize())}</span>'\n",
    "    return legend + \"</div>\" + \"\".join(out)\n",
    "\n",
    "\n",
    "\n",
    "# ---------------------------------------------------------------------------\n",
    "# Words. Every number below comes from the math above.\n",
    "# ---------------------------------------------------------------------------\n",
    "def fewer_more(x, fewer=\"fewer\", more=\"more\"):\n",
    "    return f\"{pct(x)} {fewer if x < 0 else more}\"\n",
    "\n",
    "\n",
    "def up_down(x, band=0.01):\n",
    "    if abs(x) < band:\n",
    "        return \"about the same\"\n",
    "    return f\"{'up' if x > 0 else 'down'} {pct(x)}\"\n",
    "\n",
    "\n",
    "def titles(R):\n",
    "    now, yr = R[\"now\"], R[\"year_ago\"]\n",
    "    ch = change(now[\"sales\"], yr[\"sales\"])\n",
    "    t1 = (f\"Weekly sales are {up_down(ch)} from the same weeks last year\"\n",
    "          if abs(ch) >= 0.01 else \"Weekly sales match the same weeks last year\")\n",
    "\n",
    "    t2 = \"Sales a week and the average sale\"\n",
    "    if R[\"price\"]:\n",
    "        p = R[\"price\"]\n",
    "        cnt = change(p[\"after\"][\"count\"], p[\"year_before\"][\"count\"])\n",
    "        avg = change(p[\"after\"][\"avg\"], p[\"year_before\"][\"avg\"])\n",
    "        t2 = (f\"Since prices went up: {fewer_more(cnt)} sales than a year earlier, \"\n",
    "              f\"each one {fewer_more(avg, 'smaller', 'bigger')}\")\n",
    "\n",
    "    t3 = \"\"\n",
    "    if R[\"promo\"]:\n",
    "        P = R[\"promo\"]\n",
    "        when = \"afternoon\" if min(P[\"hours\"]) >= 12 else \"morning\" if max(P[\"hours\"]) < 12 else \"discount-hour\"\n",
    "        t3 = (f\"Since {short_name(P['name'])} started: {fewer_more(change(P['in_after'], P['in_before']))} {when} visits, \"\n",
    "              f\"{fewer_more(change(P['out_after'], P['out_before']))} the rest of the day\")\n",
    "\n",
    "    S = R[\"spike\"]\n",
    "    t4 = (f\"{S['product']} refunds jumped to {S['count']} in the week of {day_label(S['week'])}\"\n",
    "          if S else \"Refunds stayed in their usual range\")\n",
    "    return t1, t2, t3, t4\n",
    "\n",
    "\n",
    "def what_this_means(R):\n",
    "    now, yr, P, S, price = R[\"now\"], R[\"year_ago\"], R[\"promo\"], R[\"spike\"], R[\"price\"]\n",
    "\n",
    "    says = []\n",
    "    p1 = (f\"Over the last {now['weeks']:.0f} weeks the shop took in {usd(now['sales'])}, \"\n",
    "          f\"against {usd(yr['sales'])} in the same weeks last year. That is {up_down(change(now['sales'], yr['sales']))}. \"\n",
    "          f\"It made {now['count']:,} sales, {fewer_more(change(now['count'], yr['count']))} than a year earlier, \"\n",
    "          f\"and the average sale was {usd(now['avg'], True)}, {up_down(change(now['avg'], yr['avg']))}. \")\n",
    "    if now[\"count\"] < yr[\"count\"] and now[\"avg\"] > yr[\"avg\"]:\n",
    "        p1 += \"Fewer people are coming in, and the bigger average sale only covers part of the gap.\"\n",
    "    says.append(p1)\n",
    "\n",
    "    if price:\n",
    "        a, b = price[\"after\"], price[\"year_before\"]\n",
    "        says.append(\n",
    "            f\"Prices went up on {day_label_year(price['day'])}, by about {pct(price['rise'])} on average across \"\n",
    "            f\"{price['products']} items. Since then, sales are {up_down(change(a['sales'], b['sales']))} on the same days \"\n",
    "            f\"a year earlier, the number of sales is {up_down(change(a['count'], b['count']))}, \"\n",
    "            f\"and the average sale is {up_down(change(a['avg'], b['avg']))}. \"\n",
    "            f\"Possibly because some regulars now come in less often at the higher prices.\"\n",
    "        )\n",
    "\n",
    "    if P:\n",
    "        hrs = f\"{hour_label(P['hours'][0])} and {hour_label(P['hours'][-1])}\" if len(P[\"hours\"]) > 1 else hour_label(P[\"hours\"][0])\n",
    "        says.append(\n",
    "            f\"{short_name(P['name'])} started on {day_label_year(P['start'])}, with \"\n",
    "            f\"{pct(stated_rate(P['name'])) + ' off' if stated_rate(P['name']) else 'a discount on'} \"\n",
    "            f\"sales in the {hrs} hours. \"\n",
    "            f\"So far it has given {usd(P['given'])} off across {P['uses']:,} sales. \"\n",
    "            + (f\"In the last {now['weeks']:.0f} weeks it gave {usd(P['given_now'])} off, \"\n",
    "               \"which is most of the rise in discounts on the tiles. \"\n",
    "               if P[\"given_now\"] >= 0.5 * (now[\"discounts\"] - yr[\"discounts\"]) > 0 else \"\")\n",
    "            + f\"In the {P['days'] // 7} weeks after it started, visits in those hours went from \"\n",
    "            f\"{P['in_before']:.1f} to {P['in_after']:.1f} a day, while visits in the rest of the day went from \"\n",
    "            f\"{P['out_before']:.0f} to {P['out_after']:.0f}. \"\n",
    "            f\"In the same weeks last year, those hours were {up_down(P['in_last_chg'])} and the rest of the day \"\n",
    "            f\"{up_down(P['out_last_chg'])}. Possibly because some customers who used to come earlier now wait for the discount.\"\n",
    "        )\n",
    "\n",
    "    if S:\n",
    "        says.append(\n",
    "            f\"Refunds on the {S['product'].lower()} jumped in the week of {day_label_year(S['week'])}: \"\n",
    "            f\"{S['count']} refunds worth {usd(S['dollars'], True)}, where a normal week has \"\n",
    "            f\"{'none or one' if S['typical_week'] < 1 else 'about ' + str(round(S['typical_week']))} and no other week had more than {S['max_other']}. \"\n",
    "            f\"They came on {S['days']} different days from {S['staff']} different staff members, \"\n",
    "            f\"so it was not one bad shift. The shop still sold {S['sold']} that week, about the usual {S['sold_typical']:.0f}. \"\n",
    "            f\"Possibly because of a bad batch of an ingredient or a change in the recipe.\"\n",
    "        )\n",
    "\n",
    "    read = [\n",
    "        f\"The tiles at the top compare the last {now['weeks']:.0f} weeks \"\n",
    "        f\"({day_label(R['now_start'])} to {day_label_year(R['now_end'] - pd.Timedelta(days=1))}) with the same \"\n",
    "        f\"{yr['weeks']:.0f} weeks a year earlier, so the season is the same on both sides. \"\n",
    "        \"Green means the change is good for the shop and red means it is not. For refunds and discounts, down is good.\",\n",
    "        f\"The wide chart shows sales for each of the {len(R['full_weeks'])} weeks in the file. \"\n",
    "        \"The thin lines mark the price rise and the start of the new discount.\",\n",
    "        \"The two small charts split those sales into how many sales the shop made each week and how big each one was.\",\n",
    "    ]\n",
    "    if P:\n",
    "        read.append(\n",
    "            \"The hour chart shows the average number of visits a day in each hour of the day. \"\n",
    "            f\"Light bars are the {P['days'] // 7} weeks before {short_name(P['name'])} started and dark bars are the \"\n",
    "            f\"{P['days'] // 7} weeks after. The shaded hours are when the discount runs.\"\n",
    "        )\n",
    "    read.append(\"The refund chart counts refunds each week for the last 26 weeks\"\n",
    "                + (f\", with the {S['product'].lower()} in orange.\" if S else \".\"))\n",
    "\n",
    "    nxt = []\n",
    "    if S:\n",
    "        nxt.append(\n",
    "            f\"Ask the kitchen what changed with the {S['product'].lower()} in the week of {day_label(S['week'])}, \"\n",
    "            \"and check that week's ingredients and recipe. Refunds on a top seller can cost regulars as well as money.\"\n",
    "        )\n",
    "    if P:\n",
    "        nxt.append(\n",
    "            f\"Decide whether {short_name(P['name'])} pays for itself. Sales in those hours went from {usd(P['in_sales_before'])} \"\n",
    "            f\"to {usd(P['in_sales_after'])} a day, while the discount gives away about {usd(P['given_per_day'])} a day. \"\n",
    "            \"Watch whether morning visits keep falling while it runs.\"\n",
    "        )\n",
    "    return says, read, nxt\n",
    "\n",
    "\n",
    "\n",
    "# ---------------------------------------------------------------------------\n",
    "# Page\n",
    "# ---------------------------------------------------------------------------\n",
    "CSS = \"\"\"\n",
    ":root{\n",
    "  color-scheme: light;\n",
    "  --page:#f6f5f1; --card:#fcfcfb; --ink:#1b1b1a; --ink2:#52514e; --muted:#7a7873;\n",
    "  --grid:#e6e5df; --axis:#c3c2b7; --ring:rgba(11,11,11,0.08);\n",
    "  --s1:#2a78d6; --s2:#eb6834; --sb:#9ec5f4; --band:rgba(42,120,214,0.07);\n",
    "  --good:#006300; --bad:#b42b2b;\n",
    "}\n",
    "@media (prefers-color-scheme: dark){\n",
    "  :root:not([data-theme=\"light\"]){\n",
    "    color-scheme: dark;\n",
    "    --page:#0f0f0e; --card:#1a1a19; --ink:#f0efec; --ink2:#c3c2b7; --muted:#9a988f;\n",
    "    --grid:#2c2c2a; --axis:#45453f; --ring:rgba(255,255,255,0.10);\n",
    "    --s1:#3987e5; --s2:#d95926; --sb:#1c5cab; --band:rgba(57,135,229,0.10);\n",
    "    --good:#3fbf3f; --bad:#f07a7a;\n",
    "  }\n",
    "}\n",
    ":root[data-theme=\"dark\"]{\n",
    "  color-scheme: dark;\n",
    "  --page:#0f0f0e; --card:#1a1a19; --ink:#f0efec; --ink2:#c3c2b7; --muted:#9a988f;\n",
    "  --grid:#2c2c2a; --axis:#45453f; --ring:rgba(255,255,255,0.10);\n",
    "  --s1:#3987e5; --s2:#d95926; --sb:#1c5cab; --band:rgba(57,135,229,0.10);\n",
    "  --good:#3fbf3f; --bad:#f07a7a;\n",
    "}\n",
    "*{box-sizing:border-box}\n",
    "html{-webkit-text-size-adjust:100%}\n",
    "body{margin:0;background:var(--page);color:var(--ink);\n",
    "  font:16px/1.5 system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;overflow-x:hidden}\n",
    "main{max-width:1120px;margin:0 auto;padding:24px 16px 48px}\n",
    "header h1{margin:0;font-size:1.6rem;font-weight:650;letter-spacing:-0.01em}\n",
    "header p{margin:4px 0 0;color:var(--ink2);font-size:.95rem}\n",
    ".tag{display:inline-block;margin-left:6px;padding:1px 8px;border-radius:999px;border:1px solid var(--ring);\n",
    "  color:var(--muted);font-size:.8rem;vertical-align:middle}\n",
    ".period{margin:24px 0 10px;color:var(--ink2);font-size:.9rem}\n",
    ".tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px}\n",
    ".tile{background:var(--card);border:1px solid var(--ring);border-radius:12px;padding:14px 16px}\n",
    ".tile .lab{color:var(--ink2);font-size:.88rem}\n",
    ".tile .num{font-size:1.75rem;font-weight:650;margin:2px 0 4px;letter-spacing:-0.01em}\n",
    ".tile .chg{font-size:.85rem;font-weight:600}\n",
    ".tile .chg.good{color:var(--good)} .tile .chg.bad{color:var(--bad)} .tile .chg.flat{color:var(--ink2)}\n",
    ".tile .was{display:block;color:var(--muted);font-weight:400;font-size:.8rem}\n",
    ".charts{display:grid;grid-template-columns:1fr;gap:12px;margin-top:20px}\n",
    "@media (min-width:860px){.charts{grid-template-columns:1fr 1fr}}\n",
    ".card{background:var(--card);border:1px solid var(--ring);border-radius:12px;padding:16px;min-width:0}\n",
    ".card h2{margin:0 0 4px;font-size:1.02rem;font-weight:620;line-height:1.35}\n",
    ".card .sub{margin:0 0 10px;color:var(--ink2);font-size:.86rem}\n",
    ".card svg{display:block;width:100%;height:auto;max-width:560px;margin:0 auto;overflow:visible}\n",
    ".pair{display:grid;grid-template-columns:1fr 1fr;gap:12px}\n",
    ".pair svg{max-width:360px}\n",
    ".card.wide{grid-column:1/-1}\n",
    ".card.wide svg{max-width:900px}\n",
    ".legend{display:flex;flex-wrap:wrap;gap:4px 16px;margin:0 0 8px;color:var(--ink2);font-size:.84rem}\n",
    ".legend i{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:6px;vertical-align:-1px}\n",
    ".k1{background:var(--s1)} .k2{background:var(--s2)} .kb{background:var(--sb)}\n",
    "svg text{font-family:inherit}\n",
    ".tick{fill:var(--muted);font-size:12px}\n",
    ".note{fill:var(--ink2);font-size:12px}\n",
    ".label{fill:var(--ink2);font-size:13px;font-weight:600}\n",
    ".cat{fill:var(--ink);font-size:12.5px}\n",
    ".cat.rank-top{font-weight:650}\n",
    ".cat.rank-low{fill:var(--ink2)}\n",
    ".val{fill:var(--ink2);font-size:12px}\n",
    ".grid{stroke:var(--grid);stroke-width:1}\n",
    ".axis{stroke:var(--axis);stroke-width:1}\n",
    ".marker{stroke:var(--ink2);stroke-width:1;stroke-dasharray:none;opacity:.6}\n",
    ".band{fill:var(--band)}\n",
    ".s1{fill:var(--s1)} .s2{fill:var(--s2)} .sb{fill:var(--sb)}\n",
    ".line1{fill:none;stroke:var(--s1);stroke-width:2;stroke-linejoin:round;stroke-linecap:round}\n",
    ".dot1{fill:var(--s1);stroke:var(--card);stroke-width:2}\n",
    ".hit,.hitdot{fill:transparent}\n",
    "g:hover .s1,g:hover .s2,g:hover .sb{opacity:.82}\n",
    ".means{background:var(--card);border:1px solid var(--ring);border-radius:12px;padding:20px;margin-top:20px}\n",
    ".means h2{margin:0 0 6px;font-size:1.25rem}\n",
    ".means h3{margin:18px 0 6px;font-size:1rem;color:var(--ink2);font-weight:620}\n",
    ".means p{margin:0 0 10px;max-width:72ch}\n",
    ".means ol{margin:0;padding-left:1.3em;max-width:72ch} .means li{margin-bottom:8px}\n",
    ".stop{background:var(--card);border:1px solid var(--ring);border-radius:12px;padding:20px;margin-top:20px}\n",
    "@media (max-width:480px){\n",
    "  header h1{font-size:1.35rem}\n",
    "  .tile{padding:12px}\n",
    "  .tile .num{font-size:1.45rem}\n",
    "  .tiles{grid-template-columns:1fr 1fr}\n",
    "  .pair{grid-template-columns:1fr}\n",
    "  .card{padding:14px 12px}\n",
    "  .means{padding:16px 14px}\n",
    "}\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "def tile(label, now, was, chg, up_is_good, fmt, extra=\"\"):\n",
    "    if abs(chg) < 0.005:\n",
    "        cls, arrow = \"flat\", \"■\"\n",
    "        word = \"No change\"\n",
    "    else:\n",
    "        good = (chg > 0) == up_is_good\n",
    "        cls = \"good\" if good else \"bad\"\n",
    "        arrow = \"▲\" if chg > 0 else \"▼\"\n",
    "        word = f\"{'Up' if chg > 0 else 'Down'} {pct(chg)}\"\n",
    "    return (f'<div class=\"tile\"><div class=\"lab\">{esc(label)}</div>'\n",
    "            f'<div class=\"num\">{esc(fmt(now))}</div>'\n",
    "            f'<div class=\"chg {cls}\">{arrow} {esc(word)}<span class=\"was\">was {esc(fmt(was))}{esc(extra)}</span></div></div>')\n",
    "\n",
    "\n",
    "def page(R, checks):\n",
    "    start, end = R[\"data_start\"], R[\"data_end\"]\n",
    "    head = (f'<header><h1>{esc(SHOP_NAME)} sales</h1>'\n",
    "            f'<p>{esc(day_label_year(start))} to {esc(day_label_year(end))}<span class=\"tag\">Sample files</span></p></header>')\n",
    "    failed = [c for ok, c in checks if not ok]\n",
    "    if failed:\n",
    "        items = \"\".join(f\"<li>{esc(c)}</li>\" for c in failed)\n",
    "        body = (f'<section class=\"stop\"><h2>The numbers did not add up</h2>'\n",
    "                f'<p>Before showing anything, the code checks that its totals match. These checks did not pass:</p>'\n",
    "                f'<ol>{items}</ol><p>No numbers are shown, so nothing here can mislead you. '\n",
    "                f'Send the file again or ask for help finding the rows that do not match.</p></section>')\n",
    "        return doc(head + body)\n",
    "\n",
    "    now, yr = R[\"now\"], R[\"year_ago\"]\n",
    "    period = (f'<p class=\"period\">The last {now[\"weeks\"]:.0f} weeks '\n",
    "              f'({esc(day_label(R[\"now_start\"]))} to {esc(day_label_year(R[\"now_end\"] - pd.Timedelta(days=1)))}), '\n",
    "              f'compared with the same weeks a year earlier</p>')\n",
    "    tiles = \"\".join([\n",
    "        tile(\"Sales\", now[\"sales\"], yr[\"sales\"], change(now[\"sales\"], yr[\"sales\"]), True, usd),\n",
    "        tile(\"Number of sales\", now[\"count\"], yr[\"count\"], change(now[\"count\"], yr[\"count\"]), True, lambda v: f\"{v:,.0f}\"),\n",
    "        tile(\"Average sale\", now[\"avg\"], yr[\"avg\"], change(now[\"avg\"], yr[\"avg\"]), True, lambda v: usd(v, True)),\n",
    "        tile(\"Refunds\", now[\"refunds\"], yr[\"refunds\"], change(now[\"refunds\"], yr[\"refunds\"]), False, usd),\n",
    "        tile(\"Discounts given\", now[\"discounts\"], yr[\"discounts\"], change(now[\"discounts\"], yr[\"discounts\"]), False, usd),\n",
    "    ])\n",
    "    t1, t2, t3, t4 = titles(R)\n",
    "    cards = [\n",
    "        f'<article class=\"card wide\"><h2>{esc(t1)}</h2><p class=\"sub\">Sales each week, after refunds</p>{chart_weekly(R)}</article>',\n",
    "        f'<article class=\"card\"><h2>{esc(t2)}</h2><p class=\"sub\">Each week. The thin lines mark the price rise and the new discount.</p>{chart_count_and_avg(R)}</article>',\n",
    "    ]\n",
    "    if R[\"promo\"]:\n",
    "        cards.append(f'<article class=\"card\"><h2>{esc(t3)}</h2><p class=\"sub\">Average visits a day in each hour</p>{chart_hours(R)}</article>')\n",
    "    cards.append(f'<article class=\"card\"><h2>{esc(t4)}</h2><p class=\"sub\">Refunds each week, last 26 weeks</p>{chart_refunds(R)}</article>')\n",
    "    charts = '<section class=\"charts\">' + \"\".join(cards) + '</section>'\n",
    "    says, read, nxt = what_this_means(R)\n",
    "    means = ('<section class=\"means\"><h2>What this means</h2>'\n",
    "             '<h3>What the numbers say</h3>' + \"\".join(f\"<p>{esc(p)}</p>\" for p in says) +\n",
    "             '<h3>How to read the charts</h3>' + \"\".join(f\"<p>{esc(p)}</p>\" for p in read) +\n",
    "             '<h3>Worth doing next</h3><ol>' + \"\".join(f\"<li>{esc(p)}</li>\" for p in nxt) + '</ol></section>')\n",
    "    return doc(head + period + f'<section class=\"tiles\">{tiles}</section>' + charts + means)\n",
    "\n",
    "\n",
    "def doc(inner):\n",
    "    return (\"<!doctype html>\\n<html lang=\\\"en\\\"><head><meta charset=\\\"utf-8\\\">\"\n",
    "            \"<meta name=\\\"viewport\\\" content=\\\"width=device-width, initial-scale=1\\\">\"\n",
    "            f\"<title>{esc(SHOP_NAME)} Sales</title><style>{CSS}</style></head>\"\n",
    "            f\"<body><main>{inner}</main></body></html>\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "from IPython.display import HTML, display\n",
    "\n",
    "t1, t2, t3, t4 = titles(R)\n",
    "cards = [(\"card wide\", t1, chart_weekly(R)), (\"card\", t2, chart_count_and_avg(R))]\n",
    "if R[\"promo\"]:\n",
    "    cards.append((\"card\", t3, chart_hours(R)))\n",
    "cards.append((\"card\", t4, chart_refunds(R)))\n",
    "display(HTML(f\"<style>{CSS}</style><main><section class='charts'>\"\n",
    "             + \"\".join(f\"<article class='{c}'><h2>{esc(t)}</h2>{svg}</article>\" for c, t, svg in cards)\n",
    "             + \"</section></main>\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 7: Build the dashboard\n",
    "\n",
    "This puts the numbers, the charts and the \"What this means\" section on one page, saves it as **dashboard.html** and downloads it. Open that file in any browser."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "from IPython.display import HTML, display\n",
    "\n",
    "out = Path(\"dashboard.html\")\n",
    "out.write_text(page(R, checks), encoding=\"utf-8\")\n",
    "print(f\"Saved {out.resolve()}\")\n",
    "display(HTML(out.read_text(encoding=\"utf-8\")))\n",
    "\n",
    "try:\n",
    "    from google.colab import files\n",
    "    files.download(str(out))\n",
    "except ImportError:\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Next: your own numbers\n",
    "\n",
    "This code is written for this file's columns. For your own data, use the workshop prompts: they have the AI write a script like this one for your files, with the same rules and checks."
   ]
  }
 ]
}
