Update app.py
Browse files7 unmodified lines891011121314151617181 unmodified line20212223242526272829303132333412 unmodified lines47484950515253545528 unmodified lines8485868788899012 unmodified lines10310410510610710810911064 unmodified lines1751761771781791801811821831841851861871881891907 unmodified lines# 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),1 unmodified linetimeout=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."""12 unmodified linesreturn blank_area, cost# Streamlit UIst.title("📦 Packaging Box Cost Calculator")# Input formcompany_name = st.text_input("Company Name (optional)")28 unmodified lines# 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) * 10012 unmodified lines"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")64 unmodified lines9. **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"""7 unmodified lines8910111213141516171819202122232425262728293031321 unmodified line343536373839404142434445464748495051525354555612 unmodified lines6970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611728 unmodified lines14614714814915015115212 unmodified lines16516616716816917017117217317417517617717864 unmodified lines2432442452467 unmodified lines# Your Google Apps Script webhook URLWEBHOOK_URL = "https://script.google.com/macros/s/AKfycbwTaxcC3pymkV3aibq14edS8ZH0KwJfFg0_NSMhnp2Hz8gWowxzcamWl1g80eRLV8EA/exec"def test_webhook_connection():"""Test if the webhook is reachable"""try:# Test with GET request firstresponse = requests.get(WEBHOOK_URL, timeout=10)return response.status_code, response.textexcept 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),1 unmodified linetimeout=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."""12 unmodified linesreturn blank_area, cost# Add debug section at the topst.title("📦 Packaging Box Cost Calculator")# Debug sectionwith st.expander("🔧 Debug & Testing"):st.write("Use this section to test your Google Sheets integration")if st.button("Test Webhook Connection"):status_code, response_text = test_webhook_connection()if status_code:if status_code == 200:st.success(f"✅ Webhook is reachable! Status: {status_code}")st.code(response_text)else:st.error(f"❌ Webhook returned status {status_code}")st.code(response_text)else:st.error(f"❌ Cannot reach webhook: {response_text}")debug_mode = st.checkbox("Enable Debug Mode (shows detailed logging info)")if st.button("Send Test Data"):test_data = {"company_name": "Test Company","box_length": 12.0,"box_width": 10.0,"box_height": 6.0,"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}success, message = send_to_google_sheet(test_data, debug=True)if success:st.success("✅ Test data sent successfully!")else:st.error(f"❌ Failed to send test data: {message}")st.markdown("---")# Input formcompany_name = st.text_input("Company Name (optional)")28 unmodified lines# 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) * 10012 unmodified lines"price_difference_percent": round(price_difference_percent, 2) if price_difference_percent is not None else ""}# Send data to Google Sheetssuccess, message = send_to_google_sheet(sheet_data, debug=debug_mode)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 resultsst.subheader("Cost Calculation Results")64 unmodified lines9. **Supply Chain Efficiency**: Optimized supply chains with reduced waste and efficient distribution networks can lower overall packaging costs."""st.markdown(factors_text)
app.py+79-23