Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151function doPost(e) {try {// Log the incoming request for debuggingconsole.log('Received POST request');console.log('Post data:', e.postData);if (!e.postData || !e.postData.contents) {throw new Error('No data received in POST request');}// Parse the JSON dataconst data = JSON.parse(e.postData.contents);console.log('Parsed data:', data);// Open your Google Sheet (replace with your actual Sheet ID)const SHEET_ID = 'https://docs.google.com/spreadsheets/d/1mzUqAwLNVnIdJ4RI4emcHGosYVtlIDM2DlC2yULAfOM/edit?gid=0#gid=0';let sheet;try {const spreadsheet = SpreadsheetApp.openById(SHEET_ID);sheet = spreadsheet.getActiveSheet();console.log('Sheet opened successfully');} catch (sheetError) {throw new Error(`Failed to open sheet: ${sheetError.message}. Check your Sheet ID: ${SHEET_ID}`);}// Prepare the row data for packaging calculatorconst timestamp = new Date();const rowData = [timestamp,data.company_name || '',data.box_length || '',data.box_width || '',data.box_height || '',data.material_type || '',data.moq || '',data.current_price || '',data.blank_area || '',data.estimated_cost || '',data.price_difference_percent || ''];console.log('Row data prepared:', rowData);// Append the data to the sheetsheet.appendRow(rowData);console.log('Data appended to sheet successfully');// Return success responsereturn ContentService.createTextOutput(JSON.stringify({status: 'success',message: 'Data added successfully',timestamp: timestamp,rowData: rowData})).setMimeType(ContentService.MimeType.JSON);} catch (error) {console.error('Error in doPost:', error);// Return detailed error responsereturn ContentService.createTextOutput(JSON.stringify({status: 'error',message: error.toString(),stack: error.stack || 'No stack trace available'})).setMimeType(ContentService.MimeType.JSON);}}function doGet(e) {console.log('Received GET request');return ContentService.createTextOutput(JSON.stringify({status: 'success',message: 'Webhook is active and ready to receive POST requests',timestamp: new Date(),parameters: e.parameter || {}})).setMimeType(ContentService.MimeType.JSON);}// Function to set up headers in your sheetfunction setupSheetHeaders() {const SHEET_ID = 'your-google-sheet-id-here';try {const sheet = SpreadsheetApp.openById(SHEET_ID).getActiveSheet();console.log('Setting up sheet headers...');// Clear existing content and add headers for packaging calculatorsheet.clear();const headers = ['Timestamp','Company Name','Box Length (in)','Box Width (in)','Box Height (in)','Material Type','MOQ','Current Price ($)','Blank Area (sq ft)','Estimated Cost ($)','Price Difference (%)'];sheet.getRange(1, 1, 1, headers.length).setValues([headers]);sheet.getRange(1, 1, 1, headers.length).setFontWeight('bold');console.log('Headers set up successfully');return 'Headers set up successfully';} catch (error) {console.error('Error setting up headers:', error);throw error;}}// Test function to verify everything is workingfunction testFunction() {console.log('Test function called');// Test dataconst testData = {company_name: 'Test Company',box_length: 12,box_width: 10,box_height: 6,material_type: '32 ECT C-Flute',moq: 1000,current_price: 0.50,blank_area: 5.625,estimated_cost: 0.5625,price_difference_percent: -11.1};// Simulate a POST requestconst mockEvent = {postData: {contents: JSON.stringify(testData)}};const result = doPost(mockEvent);console.log('Test result:', result.getContent());return result.getContent();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190import streamlit as stimport requestsimport jsonfrom datetime import datetimest.set_page_config(page_title="Packaging Box Cost Calculator", layout="wide")# Your Google Apps Script webhook URLWEBHOOK_URL = "https://script.google.com/macros/s/AKfycbwTaxcC3pymkV3aibq14edS8ZH0KwJfFg0_NSMhnp2Hz8gWowxzcamWl1g80eRLV8EA/exec"def send_to_google_sheet(data):"""Send calculation data to Google Sheet via Apps Script webhook"""try:response = requests.post(WEBHOOK_URL,data=json.dumps(data),headers={'Content-Type': 'application/json'},timeout=10)if response.status_code == 200:return Trueelse:st.warning("Data logging failed, but calculation completed successfully.")return Falseexcept Exception as e:st.warning("Unable to log data to spreadsheet, but calculation completed successfully.")return Falsedef calculate_box_cost(length, width, height, material_type):"""Calculates the box cost based on dimensions and material type."""# Calculate blank area in square feetblank_area = ((2 * length + 2 * width + 1.5) * height) / 144# Set material cost multiplier based on material typematerial_cost_multiplier = {"32 ECT C-Flute": 0.1,"44 ECT C-Flute": 0.15,"200# C-Flute": 0.08}# Calculate the total costcost = blank_area * material_cost_multiplier[material_type]return blank_area, cost# Streamlit UIst.title("📦 Packaging Box Cost Calculator")# Input formcompany_name = st.text_input("Company Name (optional)")# Important note about box stylest.info("For accurate results the box style must be a standard RSC container")# Box dimensionscol1, 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 selectionmaterial_type = st.selectbox("Material Type*",["32 ECT C-Flute", "44 ECT C-Flute", "200# C-Flute"])# New fields - Minimum Order Quantity and Current Pricecol1, 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 buttonif st.button("Calculate Box Cost"):if not all([box_length, box_width, box_height, material_type]):st.error("Please fill in all required fields marked with *")else:# Calculate the box costblank_area, cost = calculate_box_cost(box_length, box_width, box_height, material_type)# Calculate price difference if current price is providedprice_difference_percent = Noneif current_price > 0:price_difference_percent = ((current_price - cost) / current_price) * 100# Prepare data for Google Sheetssheet_data = {"company_name": company_name,"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 (non-blocking)send_to_google_sheet(sheet_data)# Display resultsst.subheader("Cost Calculation Results")# Display metricst.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 opportunitiesContact 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 pointsContact 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 costst.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)# Optional: Add a footer with data logging noticest.markdown("---")st.caption("💡 All calculations are automatically logged for analysis and improvement of our service.")# Add requirements.txt content as a comment for easy deployment"""To run this app, you'll need these packages in your requirements.txt:streamlitrequests"""
app.py+183-144