import streamlit as st import requests import json from datetime import datetime st.set_page_config(page_title="Packaging Box Cost Calculator", layout="wide") # Your Google Apps Script webhook URL WEBHOOK_URL = "https://script.google.com/macros/s/AKfycbxnwn6cawlgemYjPNwB_09oPUt28oEN1pRpqgw7OCoV1_Ub_A6cl98jFGHPw3LOME1L/exec" def test_webhook_connection(): """Test if the webhook is reachable""" try: # Test with GET request first response = requests.get(WEBHOOK_URL, timeout=10) return response.status_code, response.text except Exception as e: return None, str(e) def send_to_google_sheet(data, debug=False): """ Send calculation data to Google Sheet via Apps Script webhook """ try: if debug: st.write("🔍 **Debug Info:**") st.write(f"Webhook URL: {WEBHOOK_URL}") st.write(f"Data being sent: {json.dumps(data, indent=2)}") response = requests.post( WEBHOOK_URL, data=json.dumps(data), headers={'Content-Type': 'application/json'}, timeout=10 ) if debug: st.write(f"Response Status Code: {response.status_code}") st.write(f"Response Text: {response.text}") if response.status_code == 200: try: response_json = response.json() if debug: st.write(f"Response JSON: {response_json}") return True, "Success" except: return True, "Success (non-JSON response)" else: return False, f"HTTP {response.status_code}: {response.text}" except Exception as e: return False, f"Error: {str(e)}" def calculate_box_cost(length, width, height, material_type): """Calculates the box cost based on dimensions and material type.""" # Calculate blank area in square feet blank_area = ((2 * length + 2 * width + 1.5) * height) / 144 # Set material cost multiplier based on material type material_cost_multiplier = { "32 ECT C-Flute": 0.1, "44 ECT C-Flute": 0.15, "200# C-Flute": 0.08 } # Calculate the total cost cost = blank_area * material_cost_multiplier[material_type] return blank_area, cost st.title("📦 Packaging Box Cost Calculator") # Input form company_name = st.text_input("Company Name*", placeholder="Enter your company name") # Important note about box style st.info("For accurate results the box style must be a standard RSC container") # Box dimensions col1, col2, col3 = st.columns(3) with col1: box_length = st.number_input("Box Length (inches)*", min_value=0.1, value=12.0, step=0.1) with col2: box_width = st.number_input("Box Width (inches)*", min_value=0.1, value=10.0, step=0.1) with col3: box_height = st.number_input("Box Height (inches)*", min_value=0.1, value=6.0, step=0.1) # Material type selection material_type = st.selectbox("Material Type*", ["32 ECT C-Flute", "44 ECT C-Flute", "200# C-Flute"]) # New fields - Minimum Order Quantity and Current Price col1, col2 = st.columns(2) with col1: moq = st.number_input("Minimum Order Quantity (optional)", min_value=0, value=0, step=100) with col2: current_price = st.number_input("Current Price per Box ($) (optional)", min_value=0.0, value=0.0, step=0.01, format="%.4f") # Calculate button if st.button("Calculate Box Cost"): # Updated validation to include company_name if not all([company_name.strip(), box_length, box_width, box_height, material_type]): st.error("Please fill in all required fields marked with *") if not company_name.strip(): st.error("Company Name is required") else: # Calculate the box cost blank_area, cost = calculate_box_cost(box_length, box_width, box_height, material_type) # Calculate price difference if current price is provided price_difference_percent = None if current_price > 0: price_difference_percent = ((current_price - cost) / current_price) * 100 # Prepare data for Google Sheets sheet_data = { "company_name": company_name.strip(), "box_length": box_length, "box_width": box_width, "box_height": box_height, "material_type": material_type, "moq": moq if moq > 0 else "", "current_price": current_price if current_price > 0 else "", "blank_area": round(blank_area, 4), "estimated_cost": round(cost, 4), "price_difference_percent": round(price_difference_percent, 2) if price_difference_percent is not None else "" } # Send data to Google Sheets success, message = send_to_google_sheet(sheet_data) if success: st.success("📊 Data logged successfully!") else: st.warning(f"⚠️ Data logging failed: {message}") st.info("Calculation completed successfully, but data wasn't saved to spreadsheet.") # Display results st.subheader("Cost Calculation Results") # Display metric st.metric("Estimated Cost per Box", f"${cost:.4f}") # MOQ validation (if provided) if moq > 0: st.subheader("Minimum Order Quantity") st.info(f"You specified a minimum order quantity of {moq}. Please ensure your future orders meet or exceed this requirement.") # Price comparison (if current price provided) if current_price > 0: st.subheader("Price Comparison Analysis") if cost < current_price: st.info(f""" Your current price (${current_price:.4f}) is approximately {abs(price_difference_percent):.1f}% higher than our estimate. We can help analyze why there might be a difference: - Material sourcing options - Production efficiency improvements - Box design optimization - Bulk purchasing opportunities Contact us for a detailed cost analysis of your current packaging solution. """) elif cost > current_price: st.success(f""" Your current price (${current_price:.4f}) is approximately {abs(price_difference_percent):.1f}% lower than our estimate. You're getting a great price on your packaging! We'd be happy to: - Review your other SKUs to identify additional savings - Analyze alternative packaging solutions that could work for your product - Evaluate if there are sustainability improvements possible at similar price points Contact us to review your other packaging needs. """) else: st.info(f""" Your current price matches our estimate exactly. This suggests your current pricing is well-aligned with market rates. We'd be happy to review your other packaging needs or discuss ways to improve sustainability without increasing costs. """) # Information about factors affecting box cost st.subheader("Factors Affecting Box Cost") factors_text = """ **Key Factors That Impact Packaging Box Costs:** 1. **Material Type and Quality**: Higher ECT (Edge Crush Test) ratings indicate stronger boxes that can bear more weight, but increase cost. Premium materials with better moisture resistance or sustainability features also affect pricing. 2. **Box Dimensions**: Larger boxes require more material and cost more. Non-standard sizes may require custom manufacturing, increasing costs further. 3. **Order Volume**: Larger orders typically reduce per-unit costs due to economies of scale in production and shipping. 4. **Printing and Finishing**: Custom printing, specialized coatings, or premium finishes add to the base cost of boxes. 5. **Market Conditions**: Paper prices fluctuate based on supply chain issues, pulp availability, and energy costs. Recent global disruptions have caused significant price volatility. 6. **Regulatory Compliance**: Meeting specific industry regulations (food safety, hazardous materials, etc.) may require specialized materials or treatments. 7. **Shipping Distance**: Transportation costs are affected by fuel prices, distance, and logistics efficiency. 8. **Sustainability Features**: Eco-friendly materials or manufacturing processes may add premium costs but can reduce environmental impact. 9. **Supply Chain Efficiency**: Optimized supply chains with reduced waste and efficient distribution networks can lower overall packaging costs. """ st.markdown(factors_text)