# Google Sheets Setup & Troubleshooting Guide

Follow these steps to connect your Expense Tracker application to your Google Sheet and fix common sync issues.

---

## 1. Quick Setup Instructions

1. Open your Google Sheet.
2. Click **Extensions** -> **Apps Script**.
3. Replace all code in the editor with the following self-contained script:

```javascript
function doPost(e) {
  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet() || ss.getSheets()[0];
    var contents = (e && e.postData && e.postData.contents) ? e.postData.contents : "{}";
    var data = JSON.parse(contents);

    if (data.test) {
      sheet.appendRow([new Date(), "TEST CONNECTION", "System", 0, "Test", "Connection Verified"]);
      return ContentService.createTextOutput(JSON.stringify({ result: "success", test: true }))
        .setMimeType(ContentService.MimeType.JSON);
    }

    sheet.appendRow([
      new Date(),
      data.date || new Date().toISOString().split('T')[0],
      data.paidBy || "Dodo",
      parseFloat(data.amount) || 0,
      data.category || "General",
      data.notes || ""
    ]);

    return ContentService.createTextOutput(JSON.stringify({ result: "success" }))
      .setMimeType(ContentService.MimeType.JSON);
  } catch (error) {
    return ContentService.createTextOutput(JSON.stringify({ result: "error", error: error.toString() }))
      .setMimeType(ContentService.MimeType.JSON);
  }
}
```

4. Click **Deploy** -> **New deployment**.
5. Select **Web app**:
   - **Execute as**: `Me`
   - **Who has access**: `Anyone` *(Crucial step!)*
6. Click **Deploy**, grant permissions if prompted, and copy the **Web App URL** (`https://script.google.com/macros/s/.../exec`).
7. Paste the URL into your web app Settings modal (⚙️) and click **Save Settings**.

---

## 2. Troubleshooting: Why Data Might Not Save & How to Fix It

| Potential Issue | Root Cause | Solution |
| :--- | :--- | :--- |
| **Old Deployment Version** | Editing code in Apps Script does not update live Web App URLs automatically | Go to **Deploy -> Manage deployments -> Edit (Pencil icon) -> Select "New Version" -> Click Deploy** |
| **Access Restriction** | "Who has access" set to "Only myself" | Set access to **"Anyone"** in Web App deployment settings |
| **Wrong Web App URL** | Using the `/dev` URL or editing URL instead of `/exec` | Ensure Web App URL ends with `/exec` |
| **Incomplete Code Copy** | Missing functions due to multiple files | Copy the full self-contained script from `google-script.js` |

---

## 3. How to Verify Fix

1. Open your web app and click ⚙️ **Settings**.
2. Click **Test Connection**.
3. If successful, check your Google Sheet for a `TEST CONNECTION` row.
4. Submit a new expense in the web app form. The row will immediately appear in your sheet!
