{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9a248cb7",
   "metadata": {},
   "source": [
    "# Proyecto final (solución de referencia): la bandeja de soporte de PyShop en una tabla\n",
    "\n",
    "**Problema.** 600 tickets escritos a mano, con pedidos, fechas, teléfonos y montos en formatos mezclados. El\n",
    "equipo de soporte necesita una tabla limpia, una versión anonimizada y un reporte con cifras.\n",
    "\n",
    "**Plan.**\n",
    "\n",
    "1. Patrones compilados con pruebas positivas y negativas.\n",
    "2. Funciones de normalización (pedido, fecha, monto, teléfono, tema).\n",
    "3. DataFrame limpio con nueve columnas.\n",
    "4. Anonimización verificada.\n",
    "5. Calidad de datos.\n",
    "6. Reporte por tema, mes, monto, método y palabras.\n",
    "7. Extra: el log del servidor."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c4aa790",
   "metadata": {},
   "source": [
    "## 1. Datos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9f212de8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:38.297486Z",
     "iopub.status.busy": "2026-10-07T17:27:38.297218Z",
     "iopub.status.idle": "2026-10-07T17:27:38.580334Z",
     "shell.execute_reply": "2026-10-07T17:27:38.579829Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Python 3.13.14 | pandas 3.0.3\n",
      "600 tickets | 2000 líneas de log | 97,737 caracteres\n",
      "Ticket T-0001\n",
      "De: Valeria Ortiz <valeria.ortiz@ejemplo.org>\n",
      "Hola, la factura del pedido PS-42098 tiene un error. Pagué $4696 con efectivo el 24 de febrero de 2026. Por favor favor respondan pronto.\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "import sys\n",
    "from collections import Counter\n",
    "\n",
    "import pandas as pd\n",
    "\n",
    "print(\"Python\", sys.version.split()[0], \"| pandas\", pd.__version__)\n",
    "\n",
    "# Generadores del curso (iguales en todos los notebooks): bandeja de soporte y log de PyShop\n",
    "import random\n",
    "\n",
    "NOMBRES = [\"Ana López\", \"Luis Pérez\", \"María Gómez\", \"Carlos Ruiz\", \"Sofía Díaz\", \"Jorge Torres\",\n",
    "           \"Lucía Romero\", \"Pedro Castro\", \"Elena Vargas\", \"Diego Morales\", \"Valeria Ortiz\", \"Andrés Silva\"]\n",
    "DOMINIOS = [\"correo.com\", \"mail.net\", \"ejemplo.org\", \"pyshop.mx\"]\n",
    "MESES = [\"enero\", \"febrero\", \"marzo\", \"abril\", \"mayo\", \"junio\", \"julio\", \"agosto\", \"septiembre\",\n",
    "         \"octubre\", \"noviembre\", \"diciembre\"]\n",
    "TEMAS = {\n",
    "    \"envio\": [\"mi pedido {p} no ha llegado\", \"el envío del pedido {p} viene con retraso\",\n",
    "              \"la guía del pedido {p} no se actualiza\"],\n",
    "    \"devolucion\": [\"quiero devolver el pedido {p}\", \"solicito el reembolso del pedido {p}\",\n",
    "                   \"necesito cambiar el producto del pedido {p}\"],\n",
    "    \"pago\": [\"me cobraron dos veces el pedido {p}\", \"el pago del pedido {p} fue rechazado\",\n",
    "             \"no veo reflejado el pago del pedido {p}\"],\n",
    "    \"danado\": [\"el pedido {p} llegó dañado\", \"el producto del pedido {p} llegó roto\",\n",
    "               \"al pedido {p} le faltan piezas\"],\n",
    "    \"factura\": [\"necesito la factura del pedido {p}\", \"la factura del pedido {p} tiene un error\",\n",
    "                \"no me llegó la factura del pedido {p}\"],\n",
    "}\n",
    "PAGOS = [\"tarjeta\", \"transferencia\", \"efectivo\", \"PayPal\"]\n",
    "\n",
    "\n",
    "def _usuario(nombre):\n",
    "    n, a = nombre.lower().split()\n",
    "    tabla = str.maketrans(\"áéíóú\", \"aeiou\")\n",
    "    return f\"{n}.{a}\".translate(tabla)\n",
    "\n",
    "\n",
    "def generar_tickets(n=600, semilla=42):\n",
    "    \"\"\"Lista de n tickets de soporte (str) con formatos mezclados a propósito.\"\"\"\n",
    "    rng = random.Random(semilla)\n",
    "    tickets = []\n",
    "    for i in range(1, n + 1):\n",
    "        nombre = rng.choice(NOMBRES)\n",
    "        correo = f\"{_usuario(nombre)}{rng.choice(['', str(rng.randint(1, 99))])}@{rng.choice(DOMINIOS)}\"\n",
    "        num = rng.randint(10000, 99999)\n",
    "        pedido = rng.choices([f\"PS-{num}\", f\"ps-{num}\", f\"PS {num}\"], weights=[80, 12, 8])[0]\n",
    "        dia, mes = rng.randint(1, 28), rng.randint(1, 10)\n",
    "        fecha = rng.choice([f\"2026-{mes:02d}-{dia:02d}\", f\"{dia:02d}/{mes:02d}/2026\",\n",
    "                            f\"{dia} de {MESES[mes - 1]} de 2026\"])\n",
    "        tel = \"\".join(str(rng.randint(0, 9)) for _ in range(8))\n",
    "        lada = rng.choice([\"55\", \"33\", \"81\"])\n",
    "        telefono = rng.choice([f\"{lada} {tel[:4]} {tel[4:]}\", f\"({lada}) {tel[:4]}-{tel[4:]}\",\n",
    "                               f\"+52 {lada} {tel[:4]} {tel[4:]}\", f\"{lada}{tel}\"])\n",
    "        pesos, centavos = rng.randint(99, 4999), rng.choice([0, 0, 50, 90, 99])\n",
    "        monto = rng.choice([f\"${pesos:,}.{centavos:02d}\", f\"{pesos}.{centavos:02d} MXN\", f\"${pesos}\"])\n",
    "        tema = rng.choice(list(TEMAS))\n",
    "        frase = rng.choice(TEMAS[tema]).format(p=pedido)\n",
    "        partes = [f\"Hola, {frase}.\"]\n",
    "        if rng.random() < 0.8:\n",
    "            partes.append(f\"Pagué {monto} con {rng.choice(PAGOS)} el {fecha}.\")\n",
    "        if rng.random() < 0.6:\n",
    "            partes.append(f\"Mi teléfono es {telefono}.\")\n",
    "        if rng.random() < 0.05:  # errata con palabra repetida (para retrorreferencias)\n",
    "            partes.append(\"Por favor favor respondan pronto.\")\n",
    "        texto = f\"Ticket T-{i:04d}\\nDe: {nombre} <{correo}>\\n\" + \" \".join(partes)\n",
    "        tickets.append(texto)\n",
    "    return tickets\n",
    "\n",
    "\n",
    "RUTAS = [\"/\", \"/productos\", \"/productos/{id}\", \"/carrito\", \"/api/pedidos/{id}\", \"/api/pagos\",\n",
    "         \"/login\", \"/buscar?q=audifonos\"]\n",
    "\n",
    "\n",
    "def generar_log(n=2000, semilla=7):\n",
    "    \"\"\"Lista de n líneas de log de acceso (formato tipo Common Log + tiempo de respuesta).\"\"\"\n",
    "    rng = random.Random(semilla)\n",
    "    ips = [f\"10.0.{rng.randint(0, 3)}.{rng.randint(2, 254)}\" for _ in range(40)]\n",
    "    lineas = []\n",
    "    seg = 8 * 3600\n",
    "    for _ in range(n):\n",
    "        seg += rng.randint(1, 20)\n",
    "        h, m, s = seg // 3600 % 24, seg // 60 % 60, seg % 60\n",
    "        ruta = rng.choice(RUTAS).format(id=rng.randint(1, 500))\n",
    "        metodo = \"POST\" if ruta in (\"/api/pagos\", \"/login\", \"/carrito\") and rng.random() < 0.7 else \"GET\"\n",
    "        estado = rng.choices([200, 201, 301, 404, 500], weights=[78, 6, 4, 9, 3])[0]\n",
    "        if metodo == \"GET\" and estado == 201:\n",
    "            estado = 200\n",
    "        bytes_ = 0 if estado in (301, 404) else rng.randint(200, 25000)\n",
    "        tiempo = round(rng.uniform(0.005, 0.3) if estado != 500 else rng.uniform(0.5, 2.5), 3)\n",
    "        lineas.append(f'{rng.choice(ips)} - - [07/Oct/2026:{h:02d}:{m:02d}:{s:02d} -0600] '\n",
    "                      f'\"{metodo} {ruta} HTTP/1.1\" {estado} {bytes_} {tiempo}')\n",
    "    return lineas\n",
    "\n",
    "tickets = generar_tickets()\n",
    "log = generar_log()\n",
    "bandeja = \"\\n\\n\".join(tickets)\n",
    "print(len(tickets), \"tickets |\", len(log), \"líneas de log |\", f\"{len(bandeja):,} caracteres\")\n",
    "print(tickets[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de7ca1c3",
   "metadata": {},
   "source": [
    "## 2. Patrones y pruebas\n",
    "\n",
    "Cada patrón se define una vez, con nombre, y se prueba con un caso que debe coincidir y otro que no."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7cbfdacd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:38.581450Z",
     "iopub.status.busy": "2026-10-07T17:27:38.581290Z",
     "iopub.status.idle": "2026-10-07T17:27:38.586583Z",
     "shell.execute_reply": "2026-10-07T17:27:38.585923Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "pruebas de patrones: correctas\n"
     ]
    }
   ],
   "source": [
    "P_TICKET = re.compile(r\"^Ticket (T-\\d{4})$\", re.MULTILINE)\n",
    "P_DE = re.compile(r\"^De: (?P<cliente>.+) <(?P<usuario>[\\w.+-]+)@(?P<dominio>[\\w-]+(?:\\.[\\w-]+)+)>$\", re.MULTILINE)\n",
    "P_PEDIDO = re.compile(r\"(?i)\\bps[- ]?(\\d{5})\\b\")\n",
    "P_PEDIDO_OFICIAL = re.compile(r\"\\bPS-\\d{5}\\b\")\n",
    "P_MONTO = re.compile(r\"Pagué (\\$?[\\d,]+(?:\\.\\d{2})?(?: MXN)?)\")\n",
    "P_METODO = re.compile(r\"con (tarjeta|transferencia|efectivo|PayPal)\")\n",
    "P_FECHA = re.compile(r\"\\d{4}-\\d{2}-\\d{2}|\\d{2}/\\d{2}/\\d{4}|\\d{1,2} de [a-z]+ de \\d{4}\")\n",
    "P_TEL = re.compile(r\"(?:\\+52 )?\\(?(\\d{2})\\)?[ -]?(\\d{4})[ -]?(\\d{4})\")\n",
    "P_CORREO = re.compile(r\"[\\w.+-]+@([\\w-]+(?:\\.[\\w-]+)+)\")\n",
    "TEMAS = {\n",
    "    \"envio\": r\"no ha llegado|retraso|guía\",\n",
    "    \"devolucion\": r\"devolver|reembolso|cambiar\",\n",
    "    \"pago\": r\"cobraron|rechazado|reflejado\",\n",
    "    \"danado\": r\"dañado|roto|faltan\",\n",
    "    \"factura\": r\"factura\",\n",
    "}\n",
    "\n",
    "assert P_PEDIDO.search(\"pedido ps-20458\")[1] == \"20458\" and not P_PEDIDO.search(\"PS-482\")\n",
    "assert P_PEDIDO_OFICIAL.search(\"PS-42098\") and not P_PEDIDO_OFICIAL.search(\"PS 42098\")\n",
    "assert P_MONTO.search(\"Pagué $1,269.50 con\")[1] == \"$1,269.50\" and not P_MONTO.search(\"Pago $10\")\n",
    "assert P_METODO.search(\"con PayPal el\")[1] == \"PayPal\" and not P_METODO.search(\"con cheque\")\n",
    "assert P_FECHA.search(\"el 24 de febrero de 2026\") and not P_FECHA.search(\"el 2026/02/24\")\n",
    "assert P_TEL.search(\"(55) 3010-3105\").groups() == (\"55\", \"3010\", \"3105\") and not P_TEL.search(\"PS-42098\")\n",
    "assert P_CORREO.search(\"ana@correo.com\")[1] == \"correo.com\" and not P_CORREO.search(\"ana@correo\")\n",
    "print(\"pruebas de patrones: correctas\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7bc1ec5",
   "metadata": {},
   "source": [
    "## 3. Funciones de normalización"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "cc1bde8b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:38.587923Z",
     "iopub.status.busy": "2026-10-07T17:27:38.587817Z",
     "iopub.status.idle": "2026-10-07T17:27:38.592725Z",
     "shell.execute_reply": "2026-10-07T17:27:38.592263Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'ticket': 'T-0002', 'cliente': 'María Gómez', 'dominio': 'ejemplo.org', 'pedido': 'PS-46421', 'fecha': '2026-06-25', 'monto': 4491.0, 'metodo': 'efectivo', 'tema': 'envio', 'telefono': '8116155940'}\n"
     ]
    }
   ],
   "source": [
    "def fecha_iso(f):\n",
    "    if re.fullmatch(r\"\\d{4}-\\d{2}-\\d{2}\", f):\n",
    "        return f\n",
    "    if m := re.fullmatch(r\"(\\d{2})/(\\d{2})/(\\d{4})\", f):\n",
    "        return f\"{m[3]}-{m[2]}-{m[1]}\"\n",
    "    if (m := re.fullmatch(r\"(\\d{1,2}) de (\\w+) de (\\d{4})\", f)) and m[2] in MESES:\n",
    "        return f\"{m[3]}-{MESES.index(m[2]) + 1:02d}-{int(m[1]):02d}\"\n",
    "    return None\n",
    "\n",
    "\n",
    "def a_float(monto):\n",
    "    return float(re.sub(r\"[$,]|\\s*MXN\", \"\", monto))\n",
    "\n",
    "\n",
    "def tema_de(texto):\n",
    "    return next((k for k, p in TEMAS.items() if re.search(p, texto, re.IGNORECASE)), None)\n",
    "\n",
    "\n",
    "def fila(t):\n",
    "    de = P_DE.search(t)\n",
    "    ped, mon, met = P_PEDIDO.search(t), P_MONTO.search(t), P_METODO.search(t)\n",
    "    fec, tel = P_FECHA.search(t), P_TEL.search(t)\n",
    "    return {\n",
    "        \"ticket\": P_TICKET.search(t)[1],\n",
    "        \"cliente\": de[\"cliente\"],\n",
    "        \"dominio\": de[\"dominio\"],\n",
    "        \"pedido\": f\"PS-{ped[1]}\" if ped else None,\n",
    "        \"fecha\": fecha_iso(fec.group()) if fec else None,\n",
    "        \"monto\": a_float(mon[1]) if mon else None,\n",
    "        \"metodo\": met[1] if met else None,\n",
    "        \"tema\": tema_de(t),\n",
    "        \"telefono\": \"\".join(tel.groups()) if tel else None,\n",
    "    }\n",
    "\n",
    "\n",
    "assert fecha_iso(\"24 de febrero de 2026\") == \"2026-02-24\" and fecha_iso(\"28/02/2026\") == \"2026-02-28\"\n",
    "assert a_float(\"4491.00 MXN\") == 4491.0\n",
    "print(fila(tickets[1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea5bfa5b",
   "metadata": {},
   "source": [
    "## 4. Tabla limpia"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c92c9532",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:38.593607Z",
     "iopub.status.busy": "2026-10-07T17:27:38.593513Z",
     "iopub.status.idle": "2026-10-07T17:27:38.623237Z",
     "shell.execute_reply": "2026-10-07T17:27:38.622769Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(600, 9)\n",
      "{'ticket': 600, 'cliente': 600, 'dominio': 600, 'pedido': 600, 'fecha': 488, 'monto': 488, 'metodo': 488, 'tema': 600, 'telefono': 369}\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>ticket</th>\n",
       "      <th>cliente</th>\n",
       "      <th>dominio</th>\n",
       "      <th>pedido</th>\n",
       "      <th>fecha</th>\n",
       "      <th>monto</th>\n",
       "      <th>metodo</th>\n",
       "      <th>tema</th>\n",
       "      <th>telefono</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>T-0001</td>\n",
       "      <td>Valeria Ortiz</td>\n",
       "      <td>ejemplo.org</td>\n",
       "      <td>PS-42098</td>\n",
       "      <td>2026-02-24</td>\n",
       "      <td>4696.0</td>\n",
       "      <td>efectivo</td>\n",
       "      <td>factura</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>T-0002</td>\n",
       "      <td>María Gómez</td>\n",
       "      <td>ejemplo.org</td>\n",
       "      <td>PS-46421</td>\n",
       "      <td>2026-06-25</td>\n",
       "      <td>4491.0</td>\n",
       "      <td>efectivo</td>\n",
       "      <td>envio</td>\n",
       "      <td>8116155940</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>T-0003</td>\n",
       "      <td>Ana López</td>\n",
       "      <td>ejemplo.org</td>\n",
       "      <td>PS-20458</td>\n",
       "      <td>2026-02-28</td>\n",
       "      <td>1500.0</td>\n",
       "      <td>efectivo</td>\n",
       "      <td>devolucion</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>T-0004</td>\n",
       "      <td>Elena Vargas</td>\n",
       "      <td>correo.com</td>\n",
       "      <td>PS-40021</td>\n",
       "      <td>2026-06-26</td>\n",
       "      <td>1269.5</td>\n",
       "      <td>efectivo</td>\n",
       "      <td>devolucion</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>T-0005</td>\n",
       "      <td>Diego Morales</td>\n",
       "      <td>mail.net</td>\n",
       "      <td>PS-28131</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>envio</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   ticket        cliente      dominio    pedido       fecha   monto    metodo  \\\n",
       "0  T-0001  Valeria Ortiz  ejemplo.org  PS-42098  2026-02-24  4696.0  efectivo   \n",
       "1  T-0002    María Gómez  ejemplo.org  PS-46421  2026-06-25  4491.0  efectivo   \n",
       "2  T-0003      Ana López  ejemplo.org  PS-20458  2026-02-28  1500.0  efectivo   \n",
       "3  T-0004   Elena Vargas   correo.com  PS-40021  2026-06-26  1269.5  efectivo   \n",
       "4  T-0005  Diego Morales     mail.net  PS-28131         NaN     NaN       NaN   \n",
       "\n",
       "         tema    telefono  \n",
       "0     factura         NaN  \n",
       "1       envio  8116155940  \n",
       "2  devolucion         NaN  \n",
       "3  devolucion         NaN  \n",
       "4       envio         NaN  "
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.DataFrame([fila(t) for t in tickets])\n",
    "print(df.shape)\n",
    "print(df.notna().sum().to_dict())\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e969ab1c",
   "metadata": {},
   "source": [
    "## 5. Versión anonimizada\n",
    "\n",
    "Los correos conservan el dominio, que es útil para el análisis; los teléfonos se ocultan por completo. La\n",
    "verificación busca cualquier correo con usuario visible o teléfono restante."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "dfb0f4fb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:38.624123Z",
     "iopub.status.busy": "2026-10-07T17:27:38.624040Z",
     "iopub.status.idle": "2026-10-07T17:27:38.680378Z",
     "shell.execute_reply": "2026-10-07T17:27:38.679391Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ticket T-0002\n",
      "De: María Gómez <***@ejemplo.org>\n",
      "Hola, la guía del pedido PS-46421 no se actualiza. Pagué 4491.00 MXN con efectivo el 2026-06-25. Mi teléfono es ** **** ****.\n",
      "quedan 0 correos y 0 teléfonos\n",
      "CSV escritos: 600 y 600 filas\n"
     ]
    }
   ],
   "source": [
    "def anonimiza(t):\n",
    "    return P_TEL.sub(\"** **** ****\", P_CORREO.sub(r\"***@\\1\", t))\n",
    "\n",
    "anon = [anonimiza(t) for t in tickets]\n",
    "quedan_correos = sum(bool(re.search(r\"[\\w.+-]+(?<!\\*)@\", a)) for a in anon)\n",
    "quedan_tels = sum(bool(P_TEL.search(a)) for a in anon)\n",
    "print(anon[1])\n",
    "print(\"quedan\", quedan_correos, \"correos y\", quedan_tels, \"teléfonos\")\n",
    "assert quedan_correos == 0 and quedan_tels == 0\n",
    "\n",
    "df_anon = df.drop(columns=[\"telefono\"]).assign(texto=anon)\n",
    "# Los CSV se escriben en una carpeta temporal para no ensuciar la carpeta del notebook;\n",
    "# en tu entrega, usa una ruta propia.\n",
    "import tempfile\n",
    "from pathlib import Path\n",
    "\n",
    "carpeta = Path(tempfile.mkdtemp())\n",
    "df.to_csv(carpeta / \"tickets_limpios.csv\", index=False)\n",
    "df_anon.to_csv(carpeta / \"tickets_anonimizados.csv\", index=False)\n",
    "print(\"CSV escritos:\", len(df), \"y\", len(df_anon), \"filas\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae55d889",
   "metadata": {},
   "source": [
    "## 6. Calidad de datos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "65a3ec8a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:38.682551Z",
     "iopub.status.busy": "2026-10-07T17:27:38.682427Z",
     "iopub.status.idle": "2026-10-07T17:27:38.690040Z",
     "shell.execute_reply": "2026-10-07T17:27:38.689681Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "pedidos normalizados: 600 | distintos: 597 | repetidos: 3\n",
      "tickets con pedido fuera del formato oficial: 131\n",
      "fechas: 488 | montos: 488 | teléfonos: 369 | sin tema: 0\n",
      "     ticket    pedido       cliente\n",
      "163  T-0164  PS-15747  Jorge Torres\n",
      "292  T-0293  PS-15747    Sofía Díaz\n",
      "233  T-0234  PS-28623    Luis Pérez\n",
      "563  T-0564  PS-28623  Pedro Castro\n",
      "18   T-0019  PS-96356   Carlos Ruiz\n",
      "334  T-0335  PS-96356   María Gómez\n"
     ]
    }
   ],
   "source": [
    "incorrectos = sum(not P_PEDIDO_OFICIAL.search(t) for t in tickets)\n",
    "print(\"pedidos normalizados:\", df[\"pedido\"].notna().sum(), \"| distintos:\", df[\"pedido\"].nunique(),\n",
    "      \"| repetidos:\", int(df[\"pedido\"].duplicated().sum()))\n",
    "print(\"tickets con pedido fuera del formato oficial:\", incorrectos)\n",
    "print(\"fechas:\", df[\"fecha\"].notna().sum(), \"| montos:\", df[\"monto\"].notna().sum(),\n",
    "      \"| teléfonos:\", df[\"telefono\"].notna().sum(), \"| sin tema:\", df[\"tema\"].isna().sum())\n",
    "print(df.loc[df[\"pedido\"].duplicated(keep=False), [\"ticket\", \"pedido\", \"cliente\"]].sort_values(\"pedido\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cca4236",
   "metadata": {},
   "source": [
    "## 7. Reporte: temas y meses"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d13aba7b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:38.690872Z",
     "iopub.status.busy": "2026-10-07T17:27:38.690789Z",
     "iopub.status.idle": "2026-10-07T17:27:38.709610Z",
     "shell.execute_reply": "2026-10-07T17:27:38.709169Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tema\n",
      "devolucion    131\n",
      "danado        129\n",
      "envio         126\n",
      "factura       117\n",
      "pago           97 \n",
      "\n",
      "mes\n",
      "2026-01    44\n",
      "2026-02    55\n",
      "2026-03    51\n",
      "2026-04    43\n",
      "2026-05    39\n",
      "2026-06    51\n",
      "2026-07    58\n",
      "2026-08    53\n",
      "2026-09    51\n",
      "2026-10    43 \n",
      "\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>tema</th>\n",
       "      <th>danado</th>\n",
       "      <th>devolucion</th>\n",
       "      <th>envio</th>\n",
       "      <th>factura</th>\n",
       "      <th>pago</th>\n",
       "      <th>All</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mes</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2026-01</th>\n",
       "      <td>10</td>\n",
       "      <td>9</td>\n",
       "      <td>10</td>\n",
       "      <td>9</td>\n",
       "      <td>6</td>\n",
       "      <td>44</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-02</th>\n",
       "      <td>8</td>\n",
       "      <td>13</td>\n",
       "      <td>12</td>\n",
       "      <td>13</td>\n",
       "      <td>9</td>\n",
       "      <td>55</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-03</th>\n",
       "      <td>10</td>\n",
       "      <td>10</td>\n",
       "      <td>9</td>\n",
       "      <td>12</td>\n",
       "      <td>10</td>\n",
       "      <td>51</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-04</th>\n",
       "      <td>12</td>\n",
       "      <td>9</td>\n",
       "      <td>7</td>\n",
       "      <td>10</td>\n",
       "      <td>5</td>\n",
       "      <td>43</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-05</th>\n",
       "      <td>7</td>\n",
       "      <td>9</td>\n",
       "      <td>10</td>\n",
       "      <td>9</td>\n",
       "      <td>4</td>\n",
       "      <td>39</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-06</th>\n",
       "      <td>9</td>\n",
       "      <td>14</td>\n",
       "      <td>12</td>\n",
       "      <td>9</td>\n",
       "      <td>7</td>\n",
       "      <td>51</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-07</th>\n",
       "      <td>14</td>\n",
       "      <td>14</td>\n",
       "      <td>11</td>\n",
       "      <td>10</td>\n",
       "      <td>9</td>\n",
       "      <td>58</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-08</th>\n",
       "      <td>12</td>\n",
       "      <td>11</td>\n",
       "      <td>10</td>\n",
       "      <td>11</td>\n",
       "      <td>9</td>\n",
       "      <td>53</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-09</th>\n",
       "      <td>13</td>\n",
       "      <td>9</td>\n",
       "      <td>13</td>\n",
       "      <td>6</td>\n",
       "      <td>10</td>\n",
       "      <td>51</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2026-10</th>\n",
       "      <td>12</td>\n",
       "      <td>9</td>\n",
       "      <td>9</td>\n",
       "      <td>7</td>\n",
       "      <td>6</td>\n",
       "      <td>43</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>All</th>\n",
       "      <td>107</td>\n",
       "      <td>107</td>\n",
       "      <td>103</td>\n",
       "      <td>96</td>\n",
       "      <td>75</td>\n",
       "      <td>488</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "tema     danado  devolucion  envio  factura  pago  All\n",
       "mes                                                   \n",
       "2026-01      10           9     10        9     6   44\n",
       "2026-02       8          13     12       13     9   55\n",
       "2026-03      10          10      9       12    10   51\n",
       "2026-04      12           9      7       10     5   43\n",
       "2026-05       7           9     10        9     4   39\n",
       "2026-06       9          14     12        9     7   51\n",
       "2026-07      14          14     11       10     9   58\n",
       "2026-08      12          11     10       11     9   53\n",
       "2026-09      13           9     13        6    10   51\n",
       "2026-10      12           9      9        7     6   43\n",
       "All         107         107    103       96    75  488"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(df[\"tema\"].value_counts().to_string(), \"\\n\")\n",
    "df[\"mes\"] = df[\"fecha\"].str[:7]\n",
    "print(df[\"mes\"].value_counts().sort_index().to_string(), \"\\n\")\n",
    "pd.crosstab(df[\"mes\"], df[\"tema\"], margins=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66fe7d47",
   "metadata": {},
   "source": [
    "## 8. Montos y métodos de pago"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "24973e0f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:38.710955Z",
     "iopub.status.busy": "2026-10-07T17:27:38.710843Z",
     "iopub.status.idle": "2026-10-07T17:27:38.715599Z",
     "shell.execute_reply": "2026-10-07T17:27:38.715308Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "montos: 488 | suma 1,211,689.39 | media 2,482.97 | máximo 4,984.50\n",
      "tema\n",
      "danado        266843.12\n",
      "envio         262079.44\n",
      "factura       259447.61\n",
      "devolucion    255815.33\n",
      "pago          167503.89 \n",
      "\n",
      "metodo\n",
      "efectivo         151\n",
      "tarjeta          118\n",
      "PayPal           115\n",
      "transferencia    104 \n",
      "\n",
      "dominio\n",
      "correo.com     167\n",
      "ejemplo.org    156\n",
      "mail.net       139\n",
      "pyshop.mx      138\n"
     ]
    }
   ],
   "source": [
    "m = df[\"monto\"]\n",
    "print(f\"montos: {m.notna().sum()} | suma {m.sum():,.2f} | media {m.mean():,.2f} | máximo {m.max():,.2f}\")\n",
    "print(df.groupby(\"tema\")[\"monto\"].sum().round(2).sort_values(ascending=False).to_string(), \"\\n\")\n",
    "print(df[\"metodo\"].value_counts().to_string(), \"\\n\")\n",
    "print(df[\"dominio\"].value_counts().to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a5337b0",
   "metadata": {},
   "source": [
    "## 9. Palabras más frecuentes del cuerpo (4 letras o más)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d8655ccd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:38.716685Z",
     "iopub.status.busy": "2026-10-07T17:27:38.716590Z",
     "iopub.status.idle": "2026-10-07T17:27:38.722153Z",
     "shell.execute_reply": "2026-10-07T17:27:38.721699Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('hola', 600), ('pedido', 600), ('pagué', 488), ('teléfono', 369), ('efectivo', 151), ('tarjeta', 118), ('factura', 117), ('paypal', 115), ('llegó', 113), ('transferencia', 104)]\n"
     ]
    }
   ],
   "source": [
    "cuerpos = [t.split(\"\\n\", 2)[2] for t in tickets]\n",
    "palabras = Counter(w.lower() for c in cuerpos for w in re.findall(r\"\\b[^\\W\\d_]{4,}\\b\", c))\n",
    "print(palabras.most_common(10))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e725f57",
   "metadata": {},
   "source": [
    "## 10. Extra: el log del servidor\n",
    "\n",
    "Un patrón con grupos con nombre extrae todos los campos. Los identificadores de `/api/pedidos/{id}` van de 1 a\n",
    "500, mientras que los pedidos de la bandeja tienen cinco dígitos: no se pueden cruzar directamente."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "3c91f094",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:38.723243Z",
     "iopub.status.busy": "2026-10-07T17:27:38.723107Z",
     "iopub.status.idle": "2026-10-07T17:27:38.734237Z",
     "shell.execute_reply": "2026-10-07T17:27:38.733845Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2000 de 2000 líneas con match\n",
      "{'200': 1623, '201': 34, '301': 93, '404': 192, '500': 58}\n",
      "más de 1 s: 45\n",
      "peticiones a /api/pedidos/{id}: 232 | ids de 3 a 499\n"
     ]
    }
   ],
   "source": [
    "P_LOG = re.compile(r'(?P<ip>\\d+\\.\\d+\\.\\d+\\.\\d+) - - \\[(?P<fecha>[^\\]]+)\\] \"(?P<metodo>[A-Z]+) (?P<ruta>\\S+) '\n",
    "                   r'HTTP/[\\d.]+\" (?P<estado>\\d{3}) (?P<bytes>\\d+) (?P<tiempo>[\\d.]+)')\n",
    "dl = pd.DataFrame([P_LOG.match(l).groupdict() for l in log])\n",
    "dl[\"tiempo\"] = dl[\"tiempo\"].astype(float)\n",
    "print(len(dl), \"de\", len(log), \"líneas con match\")\n",
    "print(dl[\"estado\"].value_counts().sort_index().to_dict())\n",
    "print(\"más de 1 s:\", int((dl[\"tiempo\"] > 1).sum()))\n",
    "dl[\"ruta_n\"] = dl[\"ruta\"].str.replace(r\"/\\d+(?=/|$)\", \"/{id}\", regex=True)\n",
    "ids = dl.loc[dl[\"ruta_n\"] == \"/api/pedidos/{id}\", \"ruta\"].str.extract(r\"(\\d+)$\", expand=False).astype(int)\n",
    "print(\"peticiones a /api/pedidos/{id}:\", len(ids), \"| ids de\", ids.min(), \"a\", ids.max())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80568f7a",
   "metadata": {},
   "source": [
    "## 11. Conclusiones\n",
    "\n",
    "- **Temas.** Devolución (131) y producto dañado (129) encabezan la bandeja; pago es el tema con menos tickets (97)\n",
    "  y también el de menor monto en juego (167,503.89 MXN).\n",
    "- **Dinero en juego.** 488 tickets mencionan un pago, por 1,211,689.39 MXN en total; dañado concentra\n",
    "  266,843.12.\n",
    "- **Meses.** Julio es el mes con más tickets fechados (58) y mayo el de menos (39).\n",
    "- **Calidad de captura.** 131 de 600 tickets escriben el pedido fuera del formato oficial y hay tres formatos\n",
    "  de fecha y cuatro de teléfono. Un formulario con campos validados por `fullmatch` (pedido `PS-\\d{5}`,\n",
    "  teléfono de 10 dígitos, fecha ISO) eliminaría casi toda la limpieza.\n",
    "- **Privacidad.** La versión anonimizada conserva los dominios para el análisis y no deja correos ni\n",
    "  teléfonos visibles."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
