{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Pakistan E-commerce — Data pipeline, commercial KPIs and customer analysis\n",
    "\n",
    "**Business objective.** Build an auditable Python-to-PostgreSQL pipeline for the public Pakistan e-commerce dataset, validate the import, profile commercial performance and create Tableau-ready extracts.\n",
    "\n",
    "**Security.** Credentials are read from environment variables. No password or private connection string is stored in this notebook."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Setup and configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "pd.set_option(\"display.max_columns\", 100)\n",
    "pd.set_option(\"display.float_format\", lambda x: f\"{x:,.2f}\")\n",
    "sns.set_theme(style=\"whitegrid\", palette=\"deep\")\n",
    "RANDOM_STATE = 42\n",
    "\n",
    "import os\n",
    "from sqlalchemy import create_engine,text\n",
    "from sqlalchemy.engine import URL\n",
    "\n",
    "DATA_PATH=Path(\"data/Pakistan Largest Ecommerce Dataset.xlsx\")\n",
    "EXPORT_DIR=Path(\"outputs/pakistan_ecommerce\")\n",
    "EXPORT_DIR.mkdir(parents=True,exist_ok=True)\n",
    "\n",
    "DB_CONFIG={\n",
    "    \"drivername\":\"postgresql+psycopg2\",\n",
    "    \"username\":os.getenv(\"PGUSER\",\"postgres\"),\n",
    "    \"password\":os.getenv(\"PGPASSWORD\"),\n",
    "    \"host\":os.getenv(\"PGHOST\",\"localhost\"),\n",
    "    \"port\":int(os.getenv(\"PGPORT\",\"5432\")),\n",
    "    \"database\":os.getenv(\"PGDATABASE\",\"pakistan_ecommerce\")}\n",
    "\n",
    "if not DATA_PATH.exists(): raise FileNotFoundError(DATA_PATH)\n",
    "raw=pd.read_excel(DATA_PATH)\n",
    "print(f\"Source: {raw.shape[0]:,} rows × {raw.shape[1]} columns\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Source audit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def normalise_name(name):\n",
    "    return (str(name).strip().lower().replace(\" \",\"_\").replace(\"-\",\"_\").replace(\"/\",\"_\").replace(\"(\",\"\").replace(\")\",\"\").replace(\".\",\"\"))\n",
    "\n",
    "raw.columns=[normalise_name(c) for c in raw.columns]\n",
    "quality=pd.DataFrame({\"dtype\":raw.dtypes.astype(str),\"missing_n\":raw.isna().sum(),\"missing_pct\":raw.isna().mean()*100,\"unique_n\":raw.nunique(dropna=False)}).sort_values(\"missing_pct\",ascending=False)\n",
    "display(quality.head(25))\n",
    "print(\"Full duplicate rows:\",raw.duplicated().sum())\n",
    "display(raw.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Cleaning and business rules"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rename_map={\"category_name_1\":\"category\",\"payment_method\":\"payment_method\",\"qty_ordered\":\"quantity\",\"discount_amount\":\"discount_amount\"}\n",
    "orders=raw.rename(columns=rename_map).copy()\n",
    "required=[\"item_id\",\"status\",\"created_at\",\"sku\",\"price\",\"quantity\",\"grand_total\",\"increment_id\",\"category\",\"payment_method\",\"discount_amount\",\"customer_id\"]\n",
    "missing=set(required)-set(orders.columns)\n",
    "if missing: raise ValueError(f\"Missing expected columns: {sorted(missing)}\")\n",
    "\n",
    "text_cols=[\"status\",\"sku\",\"category\",\"payment_method\",\"increment_id\"]\n",
    "for col in text_cols:\n",
    "    orders[col]=(orders[col].astype(\"string\").str.replace(r\"[\\r\\n\\t]+\",\" \",regex=True).str.replace('\"','',regex=False).str.strip())\n",
    "\n",
    "for col in [\"price\",\"quantity\",\"grand_total\",\"discount_amount\"]:\n",
    "    orders[col]=pd.to_numeric(orders[col],errors=\"coerce\")\n",
    "orders[\"created_at\"]=pd.to_datetime(orders[\"created_at\"],errors=\"coerce\")\n",
    "orders[\"category\"]=orders[\"category\"].fillna(\"Unknown\")\n",
    "orders[\"payment_method\"]=orders[\"payment_method\"].fillna(\"Unknown\")\n",
    "orders[\"status_group\"]=np.select([\n",
    "    orders[\"status\"].str.lower().isin([\"complete\",\"closed\",\"received\",\"paid\"]),\n",
    "    orders[\"status\"].str.lower().str.contains(\"cancel\",na=False),\n",
    "    orders[\"status\"].str.lower().str.contains(\"refund\",na=False)],\n",
    "    [\"Completed\",\"Cancelled\",\"Refunded\"],default=\"Other\")\n",
    "orders[\"order_month\"]=orders[\"created_at\"].dt.to_period(\"M\").dt.to_timestamp()\n",
    "orders[\"line_value\"]=orders[\"price\"].fillna(0)*orders[\"quantity\"].fillna(0)\n",
    "orders[\"discount_rate\"]=orders[\"discount_amount\"].div(orders[\"grand_total\"].replace(0,np.nan))\n",
    "orders=orders.drop_duplicates(subset=\"item_id\",keep=\"last\")\n",
    "display(orders.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Post-cleaning validation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "validation=pd.Series({\n",
    "    \"Rows after deduplication\":len(orders),\"Unique item IDs\":orders[\"item_id\"].nunique(),\n",
    "    \"Missing order IDs\":orders[\"increment_id\"].isna().sum(),\"Missing customer IDs\":orders[\"customer_id\"].isna().sum(),\n",
    "    \"Invalid dates\":orders[\"created_at\"].isna().sum(),\"Negative prices\":orders[\"price\"].lt(0).sum(),\n",
    "    \"Non-positive quantities\":orders[\"quantity\"].le(0).sum(),\"Zero grand totals\":orders[\"grand_total\"].eq(0).sum()})\n",
    "display(validation.to_frame(\"count\"))\n",
    "assert orders[\"item_id\"].is_unique\n",
    "assert orders[\"created_at\"].notna().mean()>.95\n",
    "\n",
    "# Keep anomalies for review instead of silently deleting them\n",
    "anomalies=orders[orders[\"price\"].lt(0)|orders[\"quantity\"].le(0)|orders[\"created_at\"].isna()]\n",
    "anomalies.to_csv(EXPORT_DIR/\"data_quality_anomalies.csv\",index=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Executive KPIs and trends"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "valid=orders[orders[\"created_at\"].notna()].copy()\n",
    "kpis=pd.Series({\"Order lines\":len(valid),\"Orders\":valid[\"increment_id\"].nunique(),\"Customers\":valid[\"customer_id\"].nunique(),\"Products\":valid[\"sku\"].nunique(),\"Categories\":valid[\"category\"].nunique(),\"Gross revenue\":valid[\"grand_total\"].sum(),\"Average order value\":valid.groupby(\"increment_id\")[\"grand_total\"].first().mean(),\"Completion rate (%)\":100*valid[\"status_group\"].eq(\"Completed\").mean(),\"Cancellation rate (%)\":100*valid[\"status_group\"].eq(\"Cancelled\").mean()})\n",
    "display(kpis.to_frame(\"value\"))\n",
    "\n",
    "monthly=(valid.groupby(\"order_month\",as_index=False).agg(order_lines=(\"item_id\",\"count\"),orders=(\"increment_id\",\"nunique\"),customers=(\"customer_id\",\"nunique\"),revenue=(\"grand_total\",\"sum\"),discounts=(\"discount_amount\",\"sum\")))\n",
    "monthly[\"aov\"]=monthly[\"revenue\"].div(monthly[\"orders\"])\n",
    "monthly[\"revenue_mom_pct\"]=monthly[\"revenue\"].pct_change()*100\n",
    "monthly[\"revenue_3m_avg\"]=monthly[\"revenue\"].rolling(3,min_periods=1).mean()\n",
    "display(monthly.tail(12))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,axes=plt.subplots(1,2,figsize=(16,5))\n",
    "axes[0].plot(monthly[\"order_month\"],monthly[\"revenue\"],marker=\"o\",label=\"Revenue\")\n",
    "axes[0].plot(monthly[\"order_month\"],monthly[\"revenue_3m_avg\"],linewidth=3,label=\"3-month average\")\n",
    "axes[0].legend(); axes[0].set_title(\"Monthly gross revenue\")\n",
    "status_perf=(valid.groupby(\"status_group\",as_index=False).agg(lines=(\"item_id\",\"count\"),orders=(\"increment_id\",\"nunique\"),revenue=(\"grand_total\",\"sum\")))\n",
    "sns.barplot(data=status_perf,x=\"status_group\",y=\"orders\",ax=axes[1],color=\"#2563eb\")\n",
    "axes[1].set_title(\"Orders by status group\"); plt.tight_layout();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Category, product and payment analysis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "category_perf=(valid.groupby(\"category\",as_index=False).agg(orders=(\"increment_id\",\"nunique\"),customers=(\"customer_id\",\"nunique\"),units=(\"quantity\",\"sum\"),revenue=(\"grand_total\",\"sum\"),discounts=(\"discount_amount\",\"sum\")))\n",
    "category_perf[\"revenue_share_pct\"]=100*category_perf[\"revenue\"]/category_perf[\"revenue\"].sum()\n",
    "category_perf=category_perf.sort_values(\"revenue\",ascending=False)\n",
    "\n",
    "product_perf=(valid.groupby([\"sku\",\"category\"],as_index=False).agg(orders=(\"increment_id\",\"nunique\"),customers=(\"customer_id\",\"nunique\"),units=(\"quantity\",\"sum\"),revenue=(\"grand_total\",\"sum\"),avg_price=(\"price\",\"mean\"))).sort_values(\"revenue\",ascending=False)\n",
    "payment_perf=(valid.groupby(\"payment_method\",as_index=False).agg(orders=(\"increment_id\",\"nunique\"),customers=(\"customer_id\",\"nunique\"),revenue=(\"grand_total\",\"sum\"),completion_rate=(\"status_group\",lambda s:s.eq(\"Completed\").mean()),cancellation_rate=(\"status_group\",lambda s:s.eq(\"Cancelled\").mean())))\n",
    "payment_perf[[\"completion_rate\",\"cancellation_rate\"]]*=100\n",
    "display(category_perf.head(15)); display(payment_perf.sort_values(\"revenue\",ascending=False))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,axes=plt.subplots(1,2,figsize=(17,6))\n",
    "sns.barplot(data=category_perf.head(12),y=\"category\",x=\"revenue\",ax=axes[0],color=\"#2563eb\")\n",
    "payment_plot=payment_perf.query(\"orders >= 100\").sort_values(\"revenue\",ascending=False).head(12)\n",
    "sns.scatterplot(data=payment_plot,x=\"orders\",y=\"completion_rate\",size=\"revenue\",hue=\"cancellation_rate\",palette=\"RdYlGn_r\",sizes=(80,700),ax=axes[1])\n",
    "axes[0].set_title(\"Top categories by revenue\")\n",
    "axes[1].set_title(\"Payment volume and completion\")\n",
    "plt.tight_layout();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Customer value segmentation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "customer_orders=(valid.groupby([\"customer_id\",\"increment_id\"],as_index=False).agg(order_date=(\"created_at\",\"min\"),order_value=(\"grand_total\",\"first\")))\n",
    "snapshot=customer_orders[\"order_date\"].max()+pd.Timedelta(days=1)\n",
    "rfm=(customer_orders.groupby(\"customer_id\",as_index=False).agg(last_purchase=(\"order_date\",\"max\"),frequency=(\"increment_id\",\"nunique\"),monetary=(\"order_value\",\"sum\")))\n",
    "rfm[\"recency\"]=(snapshot-rfm[\"last_purchase\"]).dt.days\n",
    "rfm[\"R\"]=pd.qcut(rfm[\"recency\"].rank(method=\"first\"),4,labels=[4,3,2,1]).astype(int)\n",
    "rfm[\"F\"]=pd.qcut(rfm[\"frequency\"].rank(method=\"first\"),4,labels=[1,2,3,4]).astype(int)\n",
    "rfm[\"M\"]=pd.qcut(rfm[\"monetary\"].rank(method=\"first\"),4,labels=[1,2,3,4]).astype(int)\n",
    "rfm[\"segment\"]=np.select([(rfm.R>=3)&(rfm.F>=3)&(rfm.M>=3),(rfm.R>=3)&(rfm.F<=2),(rfm.R<=2)&(rfm.M>=3)],[\"High value\",\"New / promising\",\"At risk\"],default=\"Regular\")\n",
    "segment_summary=(rfm.groupby(\"segment\",as_index=False).agg(customers=(\"customer_id\",\"nunique\"),revenue=(\"monetary\",\"sum\"),avg_frequency=(\"frequency\",\"mean\"),avg_recency=(\"recency\",\"mean\")))\n",
    "display(segment_summary.sort_values(\"revenue\",ascending=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Secure PostgreSQL load and reconciliation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Execute only when database credentials are available in the environment\n",
    "if DB_CONFIG[\"password\"]:\n",
    "    engine=create_engine(URL.create(**DB_CONFIG),pool_pre_ping=True)\n",
    "    with engine.begin() as connection:\n",
    "        connection.execute(text(\"CREATE SCHEMA IF NOT EXISTS analytics\"))\n",
    "    orders.to_sql(\"pakistan_ecommerce\",engine,schema=\"public\",if_exists=\"replace\",index=False,chunksize=10000,method=\"multi\")\n",
    "    with engine.connect() as connection:\n",
    "        db_check=pd.read_sql(text(\"SELECT COUNT(*) AS rows_loaded, COUNT(DISTINCT item_id) AS unique_items, SUM(grand_total) AS revenue_loaded FROM public.pakistan_ecommerce\"),connection)\n",
    "    local_check=pd.DataFrame({\"rows_loaded\":[len(orders)],\"unique_items\":[orders[\"item_id\"].nunique()],\"revenue_loaded\":[orders[\"grand_total\"].sum()]})\n",
    "    display(pd.concat({\"local\":local_check,\"database\":db_check}))\n",
    "    assert int(db_check.loc[0,\"rows_loaded\"])==len(orders)\n",
    "else:\n",
    "    print(\"Database load skipped: set PGPASSWORD to enable it.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9. Tableau-ready exports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "monthly.to_csv(EXPORT_DIR/\"monthly_performance.csv\",index=False)\n",
    "category_perf.to_csv(EXPORT_DIR/\"category_performance.csv\",index=False)\n",
    "product_perf.head(1000).to_csv(EXPORT_DIR/\"top_products.csv\",index=False)\n",
    "payment_perf.to_csv(EXPORT_DIR/\"payment_performance.csv\",index=False)\n",
    "status_perf.to_csv(EXPORT_DIR/\"status_performance.csv\",index=False)\n",
    "rfm.to_csv(EXPORT_DIR/\"customer_rfm.csv\",index=False)\n",
    "segment_summary.to_csv(EXPORT_DIR/\"customer_segments.csv\",index=False)\n",
    "print(f\"Created {len(list(EXPORT_DIR.glob('*.csv')))} CSV files in {EXPORT_DIR}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recommendations and limitations\n",
    "\n",
    "1. Monitor completion and cancellation by payment method, not only gross revenue.\n",
    "2. Use category contribution and customer reach together to distinguish scalable categories from concentrated revenue.\n",
    "3. Target High value customers for retention and At risk customers for carefully measured win-back campaigns.\n",
    "4. Keep source-to-database reconciliation as a mandatory pipeline control.\n",
    "\n",
    "Gross revenue can be repeated across item rows depending on source semantics. Before production reporting, confirm whether `grand_total` is an order-level or item-level measure and aggregate accordingly."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.x"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}