Analytics-Bot / src /json_creation /order_states_timestamp.py
Viraj2307
Initial Commit
360b354
raw
history blame
1.84 kB
from collections import defaultdict
from datetime import datetime
def count_orders_by_state_and_day(data):
"""
Count the number of orders for each state day-wise, considering only the last state for each order on a given day.
Args:
data (list): A list of orders, where each order contains state changes and timestamps.
Returns:
dict: A dictionary with states as keys and another dictionary as values.
The inner dictionary contains dates as keys and their counts as values.
"""
last_state_by_order_and_date = {}
# Iterate through the orders to track the last state for each order on each date
for order in data.get("data", []):
for detail in order.get("data", []):
state = detail.get("order_state")
timestamp = detail.get("timestamp_unix")
order_id = detail.get("order_id")
if state and timestamp and order_id:
date = datetime.fromtimestamp(timestamp / 1000).date()
last_state_by_order_and_date[(order_id, date)] = state
# Count the last states for each date
orders_state_count_by_day = defaultdict(lambda: defaultdict(int))
for (order_id, date), state in last_state_by_order_and_date.items():
orders_state_count_by_day[date][state] += 1
# Prepare the final output in the desired format
formatted_output = defaultdict(lambda: defaultdict(int))
for date, state_counts in orders_state_count_by_day.items():
for state, count in state_counts.items():
state_key = f"number_of_order_{state.lower()}"
formatted_output[state_key][str(date)] += count
# Convert defaultdict to regular dict for cleaner output
final_output = {state: dict(date_counts) for state, date_counts in formatted_output.items()}
return final_output