-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfresto_to_bigquery.py
More file actions
157 lines (119 loc) · 3.56 KB
/
Copy pathfresto_to_bigquery.py
File metadata and controls
157 lines (119 loc) · 3.56 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import requests
import pandas as pd
from google.cloud import bigquery
from datetime import datetime
import json
import os
# -----------------------
# CONFIG
# -----------------------
CLIENT_ID = os.environ["FRESTO_CLIENT_ID"]
CLIENT_SECRET = os.environ["FRESTO_CLIENT_SECRET"]
TOKEN_URL = "https://auth.fresto.io/oauth/token"
API_URL = "https://api.fresto.io/sales/daily"
PROJECT_ID = "laposatametabase"
DATASET = "fresto_raw"
TABLE = "daily_sales_cleaned"
# -----------------------
# PRODUCT GROUP RULES
# -----------------------
def assign_group(title):
t = title.lower()
if t.startswith("f"):
return "Focaccia"
if "pasta" in t:
return "Pasta"
if any(x in t for x in ["wine", "vino", "beer", "birra", "spritz", "gin", "rum"]):
return "Drinks"
if any(x in t for x in ["cappuccino", "latte", "espresso", "americano"]):
return "Coffee"
if any(x in t for x in ["tiramisu", "cookie", "dessert"]):
return "Dessert"
if "staff" in t:
return "Staff"
return "Other"
# -----------------------
# CLEAN NAME MAPPING (add more over time)
# -----------------------
NAME_MAP = {
"F1 - Bella Vita": "F1. Bella Vita",
"F1. Bella Vita Combo": "F1. Bella Vita",
"F2 - Summer Vibe": "F2. Summer Vibe",
"F3. Doppia Combo": "F3. La Doppia",
"Gp1. Gigante Pasta Carbonara": "P1. Pasta Carbonara",
}
def normalize_title(x):
x = x.strip().title()
return NAME_MAP.get(x, x)
# -----------------------
# AUTHENTICATION
# -----------------------
def get_token():
response = requests.post(
TOKEN_URL,
data={
"grant_type": "client_credentials",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
}
)
return response.json()["access_token"]
# -----------------------
# GET RAW DATA FROM API
# -----------------------
def get_sales(date):
token = get_token()
r = requests.get(
API_URL,
headers={"Authorization": f"Bearer {token}"},
params={"date": date}
)
data = r.json().get("data", [])
if not data:
print("⚠ No data returned for date", date)
return pd.DataFrame(data)
# -----------------------
# CLEAN & TRANSFORM
# -----------------------
def transform(df):
# Only keep the columns we need
keep = ["businessDate", "productTitle", "quantity", "location_slug"]
df = df[[col for col in keep if col in df.columns]]
# Convert date
df["businessDate"] = pd.to_datetime(df["businessDate"]).dt.date
# Normalize names
df["productTitle"] = df["productTitle"].astype(str).apply(normalize_title)
# Add group category
df["group"] = df["productTitle"].apply(assign_group)
# Deduplicate
df = df.drop_duplicates()
# Timestamp
df["loaded_at"] = datetime.utcnow()
return df
# -----------------------
# LOAD TO BIGQUERY
# -----------------------
def load_to_bq(df):
client = bigquery.Client(project=PROJECT_ID)
table_id = f"{PROJECT_ID}.{DATASET}.{TABLE}"
job = client.load_table_from_dataframe(
df,
table_id,
job_config=bigquery.LoadJobConfig(
write_disposition="WRITE_APPEND"
)
)
job.result()
print(f"✔ Loaded {len(df)} rows into {table_id}")
# -----------------------
# MAIN EXECUTION
# -----------------------
if __name__ == "__main__":
today = datetime.today().strftime("%Y-%m-%d")
print("📡 Pulling data for:", today)
df = get_sales(today)
if not df.empty:
df_clean = transform(df)
load_to_bq(df_clean)
else:
print("⚠ No data to load.")