File size: 8,636 Bytes
85354fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
VERCEL_TOKEN = "azm0JC5lyPwah6qPGhbN5DL5"
PROJECT_ID = "prj_4RemrVT2H255cTcdXxkLqFJUD6Dq"
# Vercel Team ID is optional. Only include it if your project is under a team.
TEAM_ID = False
PROJECT_NAME = "matax-express"
# update_vercel_env.py
import os
import json
import requests
import sys

# --- Configuration ---

# --- Data to be Set ---
# This data will be converted to a JSON string and sent to Vercel.
# You can modify this data directly in the script before running it.

WHY_US_FEATURES_DATA = [
  { "icon": "EnergySavingsLeafIcon", "title": "Peak Freshness", "description": "Guaranteed farm-to-door freshness in every order." },
  { "icon": "YardIcon", "title": "Local Sourcing", "description": "Partnering with local farms to support the community." },
  { "icon": "CategoryIcon", "title": "Wide Selection", "description": "A diverse range of produce, dairy, and pantry staples." },
  { "icon": "LocalShippingIcon", "title": "Reliable Delivery", "description": "On-time, refrigerated delivery you can count on." },
]

FAQS_DATA = [
  { "question": "What regions do you deliver to?", "answer": "We currently deliver to all major metropolitan areas within the state. We are actively expanding our delivery network, so please check back for updates on new regions." },
  { "question": "How do I place an order?", "answer": "Once you register for an account and are approved, you can log in to our customer portal. From there, you can browse our product catalog, select quantities, and schedule your delivery." },
  { "question": "What are your quality standards?", "answer": "We pride ourselves on sourcing only the freshest, Grade A produce from trusted local and national farms. Every item is inspected for quality and freshness before it leaves our facility." },
  { "question": "Is there a minimum order requirement?", "answer": "Yes, there is a minimum order value for delivery. This amount varies by region. You can find the specific minimum for your area in your customer portal after logging in." },
]

def get_existing_env_var(key, headers, params):
    """Fetches all environment variables and returns the one matching the key."""
    api_url = f"https://api.vercel.com/v9/projects/{PROJECT_ID}/env"
    try:
        response = requests.get(api_url, headers=headers, params=params)
        response.raise_for_status()
        all_vars = response.json().get('envs', [])
        for var in all_vars:
            if var['key'] == key:
                print(f"Found existing variable '{key}' with ID: {var['id']}")
                return var
        return None
    except requests.exceptions.RequestException as err:
        print(f"❌ Error fetching environment variables: {err}")
        return None

def delete_env_var(var_id, headers, params):
    """Deletes an environment variable by its ID."""
    print(f"Attempting to delete variable with ID: {var_id}")
    api_url = f"https://api.vercel.com/v9/projects/{PROJECT_ID}/env/{var_id}"
    try:
        response = requests.delete(api_url, headers=headers, params=params)
        response.raise_for_status()
        print(f"✅ Successfully deleted variable.")
        return True
    except requests.exceptions.RequestException as err:
        print(f"❌ Error deleting environment variable: {err}")
        return False

def create_env_var(key, value_obj, target_environments, headers, params):
    """Creates a new environment variable."""
    print(f"Creating new environment variable '{key}'...")
    api_url = f"https://api.vercel.com/v9/projects/{PROJECT_ID}/env"
    payload = {
        "key": key,
        "value": json.dumps(value_obj),
        "type": "encrypted",
        "target": target_environments,
    }
    try:
        response = requests.post(api_url, headers=headers, json=payload, params=params)
        response.raise_for_status()
        print(f"✅ Successfully created environment variable '{key}'.")
        return True
    except requests.exceptions.RequestException as err:
        print(f"❌ HTTP Error creating '{key}': {err}")
        if err.response:
            print(f"   Response Body: {err.response.text}")
        return False

def set_vercel_env_var(key, value_obj, target_environments):
    """

    Main function to set an environment variable.

    It deletes the variable if it exists, then creates it.

    """
    print(f"--- Processing environment variable: {key} ---")
    headers = {"Authorization": f"Bearer {VERCEL_TOKEN}"}
    params = {"teamId": TEAM_ID} if TEAM_ID else {}

    existing_var = get_existing_env_var(key, headers, params)

    if existing_var:
        if not delete_env_var(existing_var['id'], headers, params):
            print(f"Aborting update for '{key}' due to deletion failure.")
            return False

    return create_env_var(key, value_obj, target_environments, headers, params)

def get_project_git_info(headers, params):
    """Fetches project details to get the linked Git repository ID and type."""
    print("Fetching project details to find Git repo ID...")
    api_url = f"https://api.vercel.com/v9/projects/{PROJECT_ID}"
    try:
        response = requests.get(api_url, headers=headers, params=params)
        response.raise_for_status()
        project_data = response.json()
        
        link_info = project_data.get('link')
        if not link_info or 'repoId' not in link_info or 'type' not in link_info:
            print("❌ Error: Could not find linked Git repository information (repoId).")
            print("   Please ensure your Vercel project is connected to a Git repository.")
            return None, None

        repo_id = link_info['repoId']
        git_type = link_info['type']
        print(f"✅ Found Git repo ID: {repo_id} (type: {git_type})")
        return repo_id, git_type

    except requests.exceptions.RequestException as err:
        print(f"❌ Error fetching project details: {err}")
        return None, None

def trigger_vercel_deployment():
    """Triggers a new Vercel deployment for the project."""
    print("\n--- Triggering new Vercel deployment ---")
    headers = {"Authorization": f"Bearer {VERCEL_TOKEN}", "Content-Type": "application/json"}
    params = {"teamId": TEAM_ID} if TEAM_ID else {}

    # Dynamically get the Git repo ID and type required for the deployment payload
    repo_id, git_type = get_project_git_info(headers, params)
    if not repo_id:
        print("Aborting deployment trigger due to missing Git info.")
        return

    api_url = "https://api.vercel.com/v13/deployments"
    
    # The payload now correctly includes the repoId
    payload = {
        "name": PROJECT_NAME,
        "target": "production",
        "gitSource": {
            "type": git_type,
            "repoId": repo_id,
            "ref": "main"  # Change 'main' to your default branch if it's different
        }
    }

    try:
        response = requests.post(api_url, headers=headers, json=payload, params=params)
        response.raise_for_status()
        deployment_url = response.json().get('url')
        print(f"✅ Successfully triggered new deployment.")
        print(f"   Inspect deployment: https://{deployment_url}")

    except requests.exceptions.HTTPError as err:
        print(f"❌ HTTP Error triggering deployment: {err}")
        print(f"   Response Body: {err.response.text}")
    except Exception as err:
        print(f"❌ An unexpected error occurred while triggering deployment: {err}")


def main():
    """Main function to run the script."""
    print("Starting Vercel environment variable update process...")
    
    if not all([VERCEL_TOKEN, PROJECT_ID, PROJECT_NAME]):
        print("❌ Error: Missing required environment variables.")
        print("   Please set VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_PROJECT_NAME.")
        sys.exit(1)

    target_environments = ["production", "preview", "development"]
    
    success1 = set_vercel_env_var(
        key="REACT_APP_WHY_US_FEATURES",
        value_obj=WHY_US_FEATURES_DATA,
        target_environments=target_environments
    )
    
    print("\n")

    success2 = set_vercel_env_var(
        key="REACT_APP_FAQS",
        value_obj=FAQS_DATA,
        target_environments=target_environments
    )
    
    if success1 and success2:
        trigger_vercel_deployment()
    else:
        print("\nSkipping deployment due to errors in updating environment variables.")

    print("\nScript finished.")


if __name__ == "__main__":
    main()