{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prerequisites:\n",
    "#!pip install requests\n",
    "#!pip install python-dotenv"
   ]
  },
  {
   "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": [
    "from enum import Enum\n",
    "\n",
    "r = requests.get(f\"{adminApiUrl}/admin/shop/schemas\", headers=getAdminHeaders())\n",
    "assert r.status_code == 200, f\"status code should be 200 (actual: {r.status_code})\"\n",
    "\n",
    "schemas = r.json()\n",
    "print(schemas)\n",
    "BigOrderAction = Enum(\"BigOrderAction\", dict([(v, k) for k, v in schemas[\"BigOrderAction\"].items()]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# To see sample orders list\n",
    "import requests\n",
    "\n",
    "r = requests.get(f\"{adminApiUrl}/admin/shop/shopify_orders?limit=5&search=%23BS01247923\", headers=getAdminHeaders())\n",
    "assert r.status_code == 200, f\"status code should be 200 (actual: {r.status_code})\"\n",
    "\n",
    "r.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compile lens insert data for US orders shipping in Q3 2023 → csv variable\n",
    "\n",
    "import requests\n",
    "from datetime import date\n",
    "\n",
    "def orderExcludesTags(orderDict, tagsArr):\n",
    "  for tag in tagsArr:\n",
    "    if(tag in orderDict['shopifyOrder']['tags']):\n",
    "      return False\n",
    "  return True\n",
    "\n",
    "def isPartOfQ3(orderDict):\n",
    "  cutoffDate = \"2023-07-22T00:00:00-08:00\"\n",
    "  return orderDict['shopifyOrder']['created_at'] < cutoffDate\n",
    "\n",
    "# function that accepts a list of properties formatted {name: 'name', value: 'value'} and accepts a name and returns the value\n",
    "def getPropVal(props, name):\n",
    "  for prop in props:\n",
    "    if(prop['name'] == name):\n",
    "      return prop['value']\n",
    "  return ''\n",
    "\n",
    "def parseRx(rx):\n",
    "  rx = rx.split(' | ')\n",
    "  if(len(rx) < 3):\n",
    "    return 'Sph 0.00, Cyl 0.00, Axis 000'\n",
    "  sph = float(rx[0])\n",
    "  cyl = float(rx[1])\n",
    "  if(sph > 3.0 or cyl > 3.0 or (sph + cyl >= 3.0)):\n",
    "    return 'SKIP'\n",
    "  rx[0] = 'Sph ' + rx[0]\n",
    "  rx[1] = 'Cyl ' + rx[1]\n",
    "  rx[2] = 'Axis ' + rx[2].replace('x', '').zfill(3)\n",
    "  return ', '.join(rx)\n",
    "\n",
    "excludedTags = ['prescription-ordered', 'team-bigscreen', 'competitor']\n",
    "csv = [['ID', 'Date', 'Name', 'Vision Rx - OD', 'Vision Rx - OS', 'Email', 'Shopify Order URL', 'Beyond Order ID']]\n",
    "beyondOrdersByEmail = [] #item format {email: '', orderName: ''}\n",
    "ordersProcessed = 0\n",
    "skipCount = 0\n",
    "inDateRange = True\n",
    "cursor = ''\n",
    "debugOut = ''\n",
    "\n",
    "print(f\"START: Compiling array of Q3 prescription lens orders\")\n",
    "\n",
    "while True:\n",
    "  r = requests.get(f\"{adminApiUrl}/admin/shop/shopify_orders\" + ('' if cursor == '' else '?cursor=' + cursor), headers=getAdminHeaders())\n",
    "  assert r.status_code == 200, f\"status code should be 200 (actual: {r.status_code})\"\n",
    "  orders = r.json()['orders']\n",
    "\n",
    "  for order in orders:\n",
    "    # debugOut = order #debug\n",
    "    # break #debug\n",
    "    inDateRange = isPartOfQ3(order)\n",
    "    if not inDateRange:\n",
    "      break\n",
    "    ordersProcessed += 1\n",
    "    if(order['shopifyOrder']['billing_address']['country'] == 'United States' and orderExcludesTags(order, excludedTags)):\n",
    "      items = order['shopifyOrder']['line_items']\n",
    "      for item in items:\n",
    "        if(item['name'] == 'Bigscreen Beyond - Measure Me'):\n",
    "          beyondOrdersByEmail.append({'email': order['shopifyOrder']['email'], 'orderName': order['shopifyOrder']['name']})\n",
    "        elif(item['name'] == 'Prescription Lenses'):\n",
    "          email = order['shopifyOrder']['email']\n",
    "          odRight = getPropVal(item['properties'], 'OD Right')\n",
    "          osLeft = getPropVal(item['properties'], 'OS Left')\n",
    "          if(odRight == ''):\n",
    "            odRight = getPropVal(item['properties'], 'OD (Right Eye)')\n",
    "          if(osLeft == ''):\n",
    "            osLeft = getPropVal(item['properties'], 'OS (Left Eye)')\n",
    "          odRight = parseRx(odRight)\n",
    "          osLeft = parseRx(osLeft)\n",
    "          if('Prescription Change requested' in order['shopifyOrder']['tags']):\n",
    "            odRight = 'CHECK SHOPIFY NOTES'\n",
    "            osLeft = 'CHECK SHOPIFY NOTES'\n",
    "          if(odRight == 'SKIP' or osLeft == 'SKIP'):\n",
    "            skipCount += 1\n",
    "          csv.append([order['shopifyOrder']['name'], order['shopifyOrder']['created_at'], order['shopifyOrder']['billing_address']['name'], odRight, osLeft, email, f\"https://admin.shopify.com/store/bigscreenvr/orders/{order['shopifyOrder']['id']}\"])\n",
    "\n",
    "  # break if no more nextCursor\n",
    "  if('nextCursor' not in r.json() or not inDateRange):\n",
    "    print(f\"### Finished iterating through {ordersProcessed} total orders ###\")\n",
    "    print(f\"There are {len(beyondOrdersByEmail)} Beyond orders\")\n",
    "    print(f\"CSV contains a grand total of {len(csv)} prescription lens orders\")\n",
    "    print(f\"{skipCount} orders have been marked as SKIP due to high prescription\")\n",
    "    break\n",
    "  else:\n",
    "    cursor = r.json()['nextCursor']\n",
    "    if(ordersProcessed % 200 == 0):\n",
    "      print(f\"{ordersProcessed} total orders...\")\n",
    "\n",
    "# for row in csv:\n",
    "#   email = row[4]\n",
    "#   orderName = getBeyondOrderName(beyondOrdersByEmail, email)\n",
    "#   row.append(orderName)\n",
    "\n",
    "# debugOut #debug\n",
    "# csv #debug\n",
    "# r.json() #debug"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Append Beyond Order Name to every csv row\n",
    "\n",
    "def getBeyondOrderName(ordersByEmail, email):\n",
    "  for order in ordersByEmail:\n",
    "    if(order['email'] == email):\n",
    "      return order['orderName']\n",
    "  return ''\n",
    "\n",
    "for row in csv:\n",
    "  moddedRow = row.copy()\n",
    "  email = moddedRow[5]\n",
    "  if('Email' not in email):\n",
    "    orderName = getBeyondOrderName(beyondOrdersByEmail, email)\n",
    "    moddedRow.append(orderName)\n",
    "  print('\"' + '\",\"'.join(moddedRow), end='\"/n')\n",
    "\n",
    "# debugOut #debug\n",
    "# moddedCsv #debug\n",
    "# beyondOrdersByEmail #debug\n",
    "# r.json() #debug"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "bob_df = pd.read_csv(\"C:/Users/decid/Documents/Bigscreen/DVT-2_VIDs_CSV_Final.csv\", header=None, names=['A'])\n",
    "fred_df = pd.read_csv(\"C:/Users/decid/Documents/Bigscreen/DVT-2_VIDs_CSV.csv\", header=None, names=['A', 'B'])\n",
    "\n",
    "# Merging the two DataFrames on column 'A'\n",
    "merged_df = bob_df.merge(fred_df, on='A', how='left')\n",
    "\n",
    "# Saving the merged DataFrame to a new CSV file\n",
    "merged_df.to_csv('merged.csv', index=False)\n",
    "\n",
    "print(\"Data merged and saved to 'merged.csv'\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load lens insert order CSV\n",
    "import pandas as pd\n",
    "\n",
    "van_df = pd.read_csv(\"C:/Users/decid/Documents/Bigscreen/20230918_lens_insert_order_batch_2.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Check csv for cancelled orders\n",
    "import requests\n",
    "\n",
    "ordersChecked = 0\n",
    "\n",
    "for orderName in van_df['ID']:\n",
    "  # print(f\"[DEBUG] Search url: {adminApiUrl}/admin/shop/shopify_orders?limit=5&search=%23{orderName[1:]}\") #debug\n",
    "  r = requests.get(f\"{adminApiUrl}/admin/shop/shopify_orders?limit=5&search=%23{orderName[1:]}\", headers=getAdminHeaders())\n",
    "  assert r.status_code == 200, f\"status code should be 200 (actual: {r.status_code})\"\n",
    "\n",
    "  order = r.json()['orders'][0]['shopifyOrder']\n",
    "  ordersChecked += 1\n",
    "\n",
    "  # print(order['cancel_reason']) #debug\n",
    "  if order['cancel_reason'] != None:\n",
    "    print(f\"Order {order['name']} is cancelled\")\n",
    "  else:\n",
    "    continue\n",
    "    # print(f\"Order {order['name']} is not cancelled\")\n",
    "\n",
    "print(f\"Cancellation checks complete. {ordersChecked} orders processed.\")"
   ]
  }
 ],
 "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"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
