File size: 1,843 Bytes
360b354
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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