Domain: Business Operations & Analytics

The operations team is putting together the 2025 annual performance review and needs a breakdown of how different product category and customer segment combinations performed.

Using the provided SalesMind datasets, compute the following for each product category and customer segment pair:

1. Total return-adjusted revenue, calculated per transaction as: `total_sales_revenue * (1 - return_rate) - total_discount_given`, then summed across the group.
2. Gross profit ratio: `sum(gross_profit) / sum(return_adjusted_revenue)` for the group.
3. Discount ratio: `sum(total_discount_given) / sum(total_sales_revenue)` for the group.
4. Dominant sales channel: the most frequent store type (Online, Offline, or Hybrid) among all transactions in the group.
5. Transaction count.

Cross-reference transactions against inventory supply records and exclude any involving out-of-stock products before running the calculations.

Rank all combinations by total return-adjusted revenue descending and output the top 5 to `results.csv` with columns: `rank, category, segment, adjusted_revenue, gp_ratio, discount_ratio, dominant_channel, transaction_count`.

Round monetary values to 2 decimal places and ratios to 4 decimal places.

Grading rubric:
criterion: The output includes Electric Accessories as a category value in at least one of the top 5 rows.
weight: 5
criterion: The output identifies the rank 2 category as AI Gadgets.
weight: 10
criterion: The rank 1 adjusted_revenue value in the output is 555614.86
weight: 15
criterion: The rank 1 transaction_count value in the output is 30.
weight: 10
criterion: The output identifies the rank 3 category as AI Gadgets.
weight: 10
criterion: The rank 1 dominant_channel value in the output is Hybrid.
weight: 10
criterion: The rank 2 gp_ratio value in the output is 0.3225
weight: 10
criterion: The rank 3 adjusted_revenue value in the output is 325008.41
weight: 10
criterion: The rank 4 dominant_channel value in the output is Offline.
weight: 10
criterion: The rank 5 discount_ratio value in the output is 0.0882
weight: 10

Golden answer:
## Complete Python Code
```python
import pandas as pd

# Load the dataset, update the path as needed
sales = pd.read_csv('SalesMind_Sales_Transactions_2026.csv')
products = pd.read_csv('SalesMind_Products_Master_2026.csv')
inventory = pd.read_csv('SalesMind_Inventory_Supply_2026.csv')
stores = pd.read_csv('SalesMind_Stores_Master_2026.csv')

sales['date'] = pd.to_datetime(sales['date'])

# 2025 only
df = sales[sales['date'].dt.year == 2025].copy()

# bring in product category
df = df.merge(products[['product_id', 'product_category']], on='product_id', how='left')

# inventory has a stockout flag per product/store combo
# drop anything flagged as out of stock
df = df.merge(
    inventory[['product_id', 'store_id', 'stockout_flag']],
    on=['product_id', 'store_id'], how='left'
)
df = df[df['stockout_flag'] == 0].copy()  # 172 left

# stores table has tons of duplicate rows per store_id with conflicting
# info, so take the mode of store_type per store_id to clean it up
stores_clean = stores.groupby('store_id').agg(
    store_type=('store_type', lambda x: x.mode().iloc[0])
).reset_index()
df = df.merge(stores_clean, on='store_id', how='left')

# formula from prompt
df['adj_rev'] = df['total_sales_revenue'] * (1 - df['return_rate']) - df['total_discount_given']

# aggregate by category + segment
grouped = df.groupby(['product_category', 'customer_segment']).agg(
    total_adj_rev=('adj_rev', 'sum'),
    total_gp=('gross_profit', 'sum'),
    txn_count=('transaction_id', 'count'),
    total_discount=('total_discount_given', 'sum'),
    total_raw_rev=('total_sales_revenue', 'sum'),
).reset_index()

grouped['gp_ratio'] = (grouped['total_gp'] / grouped['total_adj_rev']).round(4)
grouped['discount_ratio'] = (grouped['total_discount'] / grouped['total_raw_rev']).round(4)

# dominant channel = most frequent store_type per group
channel_counts = df.groupby(
    ['product_category', 'customer_segment', 'store_type']
).size().reset_index(name='cnt')

dominant = channel_counts.sort_values('cnt', ascending=False).drop_duplicates(
    subset=['product_category', 'customer_segment'], keep='first'
)[['product_category', 'customer_segment', 'store_type']].rename(
    columns={'store_type': 'dominant_channel'}
)

grouped = grouped.merge(dominant, on=['product_category', 'customer_segment'], how='left')
grouped = grouped.sort_values('total_adj_rev', ascending=False).reset_index(drop=True)

# top 5
top5 = grouped.head(5).copy()
top5['rank'] = range(1, 6)

result = top5[['rank', 'product_category', 'customer_segment',
               'total_adj_rev', 'gp_ratio', 'discount_ratio',
               'dominant_channel', 'txn_count']]
result.columns = ['rank', 'category', 'segment', 'adjusted_revenue',
                   'gp_ratio', 'discount_ratio', 'dominant_channel',
                   'transaction_count']
result['adjusted_revenue'] = result['adjusted_revenue'].round(2)

result.to_csv('results.csv', index=False)
print(result.to_string(index=False))
```

### Explanation

- We filter sales to 2025 (365 transactions) and join the products table for category labels.
- The inventory table is joined on product_id and store_id to identify out-of-stock products. Transactions where stockout_flag == 1 are excluded, leaving 172 transactions.
- The stores master table has multiple duplicate rows per store_id with inconsistent store_type values. To get reliable channel data for the dominant sales channel metric, we resolve each store_id to the most frequently occurring store_type using the statistical mode. This produces 20 clean store records.
- Return-adjusted revenue follows the formula given in the prompt. Gross profit ratio and discount ratio are computed at the group level after aggregation. The dominant channel for each group is whichever store_type appears most often among that group's transactions.

### Ground Truth Final Answer (CSV)

```
rank,category,segment,adjusted_revenue,gp_ratio,discount_ratio,dominant_channel,transaction_count
1,Electric Accessories,Budget,555614.86,0.3431,0.0724,Hybrid,30
2,AI Gadgets,Premium,405927.70,0.3225,0.0726,Online,24
3,AI Gadgets,Enterprise,325008.41,0.2955,0.0836,Hybrid,25
4,Electric Accessories,Enterprise,322420.20,0.3091,0.0878,Offline,21
5,Electric Accessories,Premium,320702.82,0.3176,0.0882,Hybrid,21
```