{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv\n",
    "\n",
    "def read_csv_to_dict(file_path, key_column):\n",
    "    with open(file_path, mode='r', encoding='utf-8') as csvfile:\n",
    "        reader = csv.DictReader(csvfile)\n",
    "        result_dict = {row[key_column]: row for row in reader}\n",
    "    return result_dict\n",
    "\n",
    "# Usage\n",
    "csv_file_path = '../BVR_patients_recalcuted_far_PD.csv'\n",
    "key_column_name = 'far PD sid zip file name'\n",
    "topology_csv_dict = read_csv_to_dict(csv_file_path, key_column_name)\n",
    "\n",
    "print(topology_csv_dict)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from api import BigApi\n",
    "BigApi.init(\".admin.env\")\n",
    "BigApi.adminLogin()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scanReqs = BigApi.adminGet(f\"/admin/fabricator/scan_requests\")\n",
    "bigOrderResult = BigApi.adminGet(f\"/admin/shop/orders\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "potentiallyBadOrders = {}\n",
    "\n",
    "# filter big order - remove Shipped or Cancelled\n",
    "bigOrders = [o for o in bigOrderResult[\"items\"] if o['state'] not in ['Shipped', 'Cancelled']]\n",
    "\n",
    "def extractIpd(message):\n",
    "    regex = r\"\\b(5[0-9]|6\\d|7[0-9])\\b\"\n",
    "    matches = re.findall(regex, message)\n",
    "    if len(matches) > 0:\n",
    "        return matches[0]\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "for key, row in topology_csv_dict.items():\n",
    "    topology_patient_id = row['patient_id']\n",
    "    for scanReq in scanReqs[\"items\"]:\n",
    "        if scanReq[\"topologyPatientId\"] == topology_patient_id:\n",
    "            for order in bigOrders:\n",
    "                if order[\"state\"] == \"Shipped\" or order[\"state\"] == \"Cancelled\":\n",
    "                    continue\n",
    "\n",
    "                if order[\"id\"] == scanReq[\"bigOrderId\"]:\n",
    "                    ipdOverrideExists = False\n",
    "                    ipdOverrideIndex = -1\n",
    "                    ipdOverrideValue = 0\n",
    "                    ipdTopologyValue = 0\n",
    "\n",
    "                    for i in range(len(order[\"history\"]))[::-1]:\n",
    "                        history = order[\"history\"][i]\n",
    "                        if history[\"message\"].startswith(\"Customer set IPD override\"):\n",
    "                            ipdOverrideValue = extractIpd(history[\"message\"])\n",
    "                            ipdOverrideExists = True\n",
    "                            ipdOverrideIndex = i\n",
    "                            break\n",
    "\n",
    "                    if ipdOverrideIndex > -1:\n",
    "                        indexes = range(ipdOverrideIndex + 1, len(order[\"history\"]))\n",
    "                        indexes = indexes[::-1]\n",
    "                        for i in indexes:\n",
    "                            history = order[\"history\"][i]\n",
    "                            if history[\"message\"].startswith(\"IPD updated to\"):\n",
    "                                ipdTopologyValue = extractIpd(history[\"message\"]);\n",
    "                                if ipdTopologyValue != ipdOverrideValue:\n",
    "                                    print(ipdOverrideValue, ipdTopologyValue)\n",
    "                                potentiallyBadOrders[order[\"id\"]] = ipdOverrideValue\n",
    "                                break\n",
    "\n",
    "for bigOrderId, ipd in potentiallyBadOrders.items():\n",
    "    print(f\"https://main-ocean-arda.bigscreencloud.com/shop/order/{bigOrderId} {ipd}\")\n",
    "\n",
    "print(len(potentiallyBadOrders.keys()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for bigOrderId, ipd in potentiallyBadOrders.items():\n",
    "    print(f\"https://main-ocean-arda.bigscreencloud.com/shop/order/{bigOrderId} {ipd}\")\n",
    "    data = BigApi.adminPut(f\"/admin/shop/order/{bigOrderId}\", {\n",
    "        \"action\": \"CustomerOverrideIPD\",\n",
    "        \"ipd\": ipd\n",
    "    })"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bigOrderId = \"\"\n",
    "data = BigApi.adminPut(f\"/admin/shop/order/{bigOrderId}\", {\n",
    "    \"action\": \"AdminSendIPDCorrectionEmail\"\n",
    "})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# filter big order - remove Shipped or Cancelled\n",
    "bigOrders = [o for o in bigOrderResult[\"items\"] if o['state'] not in ['Shipped', 'Cancelled']]\n",
    "\n",
    "rows = topology_csv_dict.values()\n",
    "\n",
    "# Skip 370\n",
    "rows = list(rows)\n",
    "rows = rows[370:]\n",
    "\n",
    "for row in rows:\n",
    "    topology_patient_id = row['patient_id']\n",
    "    for scanReq in scanReqs[\"items\"]:\n",
    "        if scanReq[\"topologyPatientId\"] == topology_patient_id:\n",
    "            for order in bigOrders:\n",
    "                if order[\"state\"] == \"Shipped\" or order[\"state\"] == \"Cancelled\":\n",
    "                    continue\n",
    "\n",
    "                if order[\"id\"] == scanReq[\"bigOrderId\"]:\n",
    "                    bigOrderId = order[\"id\"]\n",
    "                    try:\n",
    "                        data = BigApi.adminPut(f\"/admin/shop/order/{bigOrderId}\", { \"action\": \"AdminSendIPDCorrectionEmail\" })\n",
    "                    except:\n",
    "                        BigApi.adminLogin()\n",
    "                        data = BigApi.adminPut(f\"/admin/shop/order/{bigOrderId}\", { \"action\": \"AdminSendIPDCorrectionEmail\" })"
   ]
  }
 ],
 "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.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
