| name | retail-expert |
| version | 1.0.0 |
| description | Expert-level retail systems, POS, inventory management, e-commerce, customer analytics, and omnichannel retail |
| category | domains |
| tags | ["retail","pos","ecommerce","inventory","crm","omnichannel"] |
| allowed-tools | ["Read","Write","Edit"] |
Retail Expert
Expert guidance for retail systems, point-of-sale solutions, inventory management, e-commerce platforms, customer analytics, and omnichannel retail strategies.
Core Concepts
Retail Systems
- Point of Sale (POS) systems
- Inventory Management Systems (IMS)
- Customer Relationship Management (CRM)
- Order Management Systems (OMS)
- Warehouse Management Systems (WMS)
- E-commerce platforms
- Payment processing
Omnichannel Retail
- Online-to-offline (O2O) integration
- Buy online, pick up in store (BOPIS)
- Ship from store
- Unified customer profiles
- Cross-channel inventory visibility
- Consistent pricing across channels
- Integrated loyalty programs
Technologies
- Mobile POS (mPOS)
- Self-checkout systems
- Electronic shelf labels (ESL)
- RFID for inventory tracking
- Computer vision for analytics
- AI-powered recommendations
- Contactless payments
Point of Sale System
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import List, Optional
from enum import Enum
class PaymentMethod(Enum):
CASH = "cash"
CREDIT_CARD = "credit_card"
DEBIT_CARD = "debit_card"
MOBILE_PAYMENT = "mobile_payment"
GIFT_CARD = "gift_card"
class TransactionStatus(Enum):
PENDING = "pending"
COMPLETED = "completed"
VOIDED = "voided"
REFUNDED = "refunded"
@dataclass
class Product:
"""Product/SKU information"""
sku: str
name: str
description: str
price: Decimal
cost: Decimal
barcode: str
category: str
department: str
tax_rate: Decimal
is_taxable: bool
stock_quantity: int
reorder_point: int
@dataclass
class LineItem:
"""Transaction line item"""
sku: str
product_name: str
quantity: int
unit_price: Decimal
discount_amount: Decimal
tax_amount: Decimal
line_total: Decimal
:
transaction_id:
store_id:
register_id:
cashier_id:
timestamp: datetime
items: [LineItem]
subtotal: Decimal
tax_total: Decimal
discount_total: Decimal
grand_total: Decimal
payment_method: PaymentMethod
status: TransactionStatus
customer_id: []
:
():
.store_id = store_id
.register_id = register_id
.current_transaction =
.products = {}
() -> :
transaction_id = ._generate_transaction_id()
.current_transaction = Transaction(
transaction_id=transaction_id,
store_id=.store_id,
register_id=.register_id,
cashier_id=cashier_id,
timestamp=datetime.now(),
items=[],
subtotal=Decimal(),
tax_total=Decimal(),
discount_total=Decimal(),
grand_total=Decimal(),
payment_method=,
status=TransactionStatus.PENDING,
customer_id=
)
transaction_id
() -> :
.current_transaction:
{: }
product = ._lookup_product(barcode)
product:
{: , : barcode}
product.stock_quantity < quantity:
{
: ,
: product.stock_quantity
}
unit_price = product.price
line_subtotal = unit_price * quantity
discount_amount = Decimal()
tax_amount = Decimal()
product.is_taxable:
tax_amount = (line_subtotal - discount_amount) * product.tax_rate
line_total = line_subtotal - discount_amount + tax_amount
line_item = LineItem(
sku=product.sku,
product_name=product.name,
quantity=quantity,
unit_price=unit_price,
discount_amount=discount_amount,
tax_amount=tax_amount,
line_total=line_total
)
.current_transaction.items.append(line_item)
._recalculate_totals()
{
: ,
: {
: product.name,
: quantity,
: (unit_price),
: (line_total)
},
: (.current_transaction.grand_total)
}
() -> :
.current_transaction:
{: }
discount = ._validate_discount(discount_code)
discount:
{: }
discount[] == :
discount_amount = .current_transaction.subtotal * (discount[] / )
discount[] == :
discount_amount = Decimal((discount[]))
:
{: }
.current_transaction.discount_total += discount_amount
._recalculate_totals()
{
: ,
: (discount_amount),
: (.current_transaction.grand_total)
}
() -> :
.current_transaction:
{: }
amount < .current_transaction.grand_total:
{: }
payment_result = ._process_payment_gateway(
payment_method,
amount,
payment_details
)
payment_result[]:
payment_result
.current_transaction.payment_method = payment_method
.current_transaction.status = TransactionStatus.COMPLETED
._update_inventory()
change = amount - .current_transaction.grand_total
receipt = ._generate_receipt()
transaction_id = .current_transaction.transaction_id
.current_transaction =
{
: ,
: transaction_id,
: (amount),
: (change),
: receipt
}
() -> :
.current_transaction:
{: }
.current_transaction.status = TransactionStatus.VOIDED
transaction_id = .current_transaction.transaction_id
.current_transaction =
{
: ,
: transaction_id,
: reason
}
():
.current_transaction.subtotal = (
item.unit_price * item.quantity item .current_transaction.items
)
.current_transaction.tax_total = (
item.tax_amount item .current_transaction.items
)
.current_transaction.grand_total = (
.current_transaction.subtotal +
.current_transaction.tax_total -
.current_transaction.discount_total
)
() -> [Product]:
.products.get(barcode)
() -> []:
() -> :
{: , : }
():
item .current_transaction.items:
product = .products.get(item.sku)
product:
product.stock_quantity -= item.quantity
() -> :
{
: .current_transaction.transaction_id,
: .current_transaction.timestamp.isoformat(),
: [
{
: item.product_name,
: item.quantity,
: (item.unit_price),
: (item.line_total)
}
item .current_transaction.items
],
: (.current_transaction.subtotal),
: (.current_transaction.tax_total),
: (.current_transaction.discount_total),
: (.current_transaction.grand_total)
}
() -> :
uuid
Inventory Management
import numpy as np
from datetime import datetime, timedelta
class InventoryManagementSystem:
"""Inventory management and optimization"""
def __init__(self):
self.products = {}
self.warehouses = {}
self.transfer_orders = []
def calculate_reorder_point(self,
average_daily_demand: float,
lead_time_days: int,
service_level: float = 0.95) -> dict:
"""Calculate optimal reorder point"""
demand_std_dev = average_daily_demand * 0.2
from scipy import stats
z_score = stats.norm.ppf(service_level)
safety_stock = z_score * demand_std_dev * np.sqrt(lead_time_days)
reorder_point = (average_daily_demand * lead_time_days) + safety_stock
return {
'reorder_point': int(np.ceil(reorder_point)),
'safety_stock': int(np.ceil(safety_stock)),
'average_daily_demand': average_daily_demand,
'lead_time_days': lead_time_days,
'service_level': service_level
}
def calculate_economic_order_quantity(self,
annual_demand: ,
ordering_cost: Decimal,
holding_cost_per_unit: Decimal) -> :
eoq = np.sqrt(
( * annual_demand * (ordering_cost)) /
(holding_cost_per_unit)
)
number_of_orders = annual_demand / eoq
ordering_cost_total = number_of_orders * (ordering_cost)
holding_cost_total = (eoq / ) * (holding_cost_per_unit)
total_cost = ordering_cost_total + holding_cost_total
{
: (np.ceil(eoq)),
: number_of_orders,
: ( / number_of_orders),
: total_cost,
: ordering_cost_total,
: holding_cost_total
}
() -> :
product products:
product[] = (
product[] * product[]
)
sorted_products = (
products,
key= x: x[],
reverse=
)
total_value = (p[] p sorted_products)
cumulative_value =
results = {: [], : [], : []}
product sorted_products:
cumulative_value += product[]
percentage = (cumulative_value / total_value) *
percentage <= :
category =
percentage <= :
category =
:
category =
product[] = category
results[category].append(product)
{
: results,
: {
: (results[]),
: (results[]),
: (results[]),
: total_value
}
}
() -> :
alpha =
beta =
gamma =
season_length =
n = (historical_sales)
forecast = []
level = np.mean(historical_sales[:season_length])
trend = (np.mean(historical_sales[season_length:*season_length]) -
np.mean(historical_sales[:season_length])) / season_length
seasonal = np.array(historical_sales[:season_length]) / level
i (periods_ahead):
season_idx = i % season_length
forecast_value = (level + trend * (i + )) * seasonal[season_idx]
forecast.append((, forecast_value))
{
: forecast,
: periods_ahead,
: ,
: ._calculate_confidence_interval(
historical_sales,
forecast
)
}
() -> []:
alerts = []
sku, product .products.items():
product.stock_quantity <= product.reorder_point:
alerts.append({
: ,
: ,
: sku,
: product.name,
: product.stock_quantity,
: product.reorder_point,
:
})
max_stock = product.reorder_point *
product.stock_quantity > max_stock:
alerts.append({
: ,
: ,
: sku,
: product.name,
: product.stock_quantity,
: max_stock,
:
})
alerts
() -> :
std_error = np.std(historical) *
{
: [(, f - * std_error) f forecast],
: [f + * std_error f forecast]
}
Customer Analytics
from sklearn.cluster import KMeans
import pandas as pd
class CustomerAnalytics:
"""Customer segmentation and analytics"""
def __init__(self):
self.customers = {}
self.transactions = []
def calculate_rfm(self, customer_transactions: pd.DataFrame) -> pd.DataFrame:
"""Calculate RFM (Recency, Frequency, Monetary) scores"""
current_date = datetime.now()
rfm = customer_transactions.groupby('customer_id').agg({
'transaction_date': lambda x: (current_date - x.max()).days,
'transaction_id': 'count',
'amount': 'sum'
})
rfm.columns = ['recency', 'frequency', 'monetary']
rfm['r_score'] = pd.qcut(rfm['recency'], 5, labels=[5, 4, 3, 2, 1])
rfm['f_score'] = pd.qcut(rfm['frequency'].rank(method='first'), 5, labels=[1, 2, 3, 4, ])
rfm[] = pd.qcut(rfm[], , labels=[, , , , ])
rfm[] = (
rfm[].astype() +
rfm[].astype() +
rfm[].astype()
)
rfm
() -> :
segments = {}
customer_id, row rfm_data.iterrows():
r, f, m = (row[]), (row[]), (row[])
r >= f >= m >= :
segment =
r >= f >= m >= :
segment =
r >= f <= :
segment =
r <= f >= :
segment =
r <= f <= :
segment =
m >= :
segment =
:
segment =
segments[customer_id] = {
: segment,
: {: r, : f, : m}
}
segments
() -> Decimal:
clv = (
(average_purchase_value) *
purchase_frequency *
customer_lifespan_years
)
Decimal((clv)).quantize(Decimal())
() -> :
churn_score =
churn_score > :
risk =
action =
churn_score > :
risk =
action =
:
risk =
action =
{
: churn_score,
: risk,
: action
}
() -> []:
recommendations = [
{
: ,
: ,
: ,
:
}
]
recommendations[:top_n]
Best Practices
POS Operations
- Ensure POS system uptime (99.9%+)
- Implement offline mode for network outages
- Use barcode scanning for accuracy
- Support multiple payment methods
- Enable quick item lookup
- Implement receipt management (print/email)
- Track cashier performance metrics
Inventory Management
- Implement cycle counting programs
- Use ABC analysis for prioritization
- Maintain accurate stock records
- Set appropriate reorder points
- Use RFID for high-value items
- Implement first-in-first-out (FIFO)
- Track inventory turnover ratios
E-commerce
- Optimize for mobile shopping
- Implement abandoned cart recovery
- Use high-quality product images
- Enable customer reviews
- Provide multiple shipping options
- Implement real-time inventory updates
- Support guest checkout
Customer Experience
- Personalize marketing communications
- Implement loyalty programs
- Provide omnichannel support
- Enable easy returns and exchanges
- Use customer feedback
- Implement chatbots for support
- Track Net Promoter Score (NPS)
Anti-Patterns
❌ No inventory tracking or inaccurate counts
❌ Single payment method only
❌ Poor checkout experience (slow/complex)
❌ No customer data collection
❌ Siloed online and offline systems
❌ Manual price updates across locations
❌ No backup for POS systems
❌ Ignoring cart abandonment
❌ No product recommendations
Resources