File size: 6,640 Bytes
3dbfa56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
198
199
200
201
202
203
204
205
206
document.addEventListener("DOMContentLoaded", () => {
  const userName = "Bipul Sardar";
  const today = new Date();
  const day = String(today.getDate()).padStart(2, "0");
  const month = String(today.getMonth() + 1).padStart(2, "0");
  const year = today.getFullYear();
  const reportDate = `${year}-${month}-${day}`;
  const displayDate = `${day}-${month}-${year}`;
  document.getElementById("reportDate").value = displayDate;

  const entriesTableBody = document.querySelector("#entriesTable tbody");
  let entryCount = 0;

  document.getElementById("addRow").addEventListener("click", () => {
    entryCount++;
    const row = document.createElement("tr");
    row.innerHTML = `
      <td>${entryCount}</td>
      <td><textarea class="form-control" required></textarea></td>
      <td><input type="time" class="form-control" required></td>
      <td><input type="time" class="form-control" required></td>
      <td><button type="button" class="btn btn-danger btn-sm removeRow">Remove</button></td>
    `;
    entriesTableBody.appendChild(row);

    row.querySelector(".removeRow").addEventListener("click", () => {
      row.remove();
      updateSlNos();
    });
  });

  function updateSlNos() {
    entryCount = 0;
    entriesTableBody.querySelectorAll("tr").forEach((row) => {
      entryCount++;
      row.querySelector("td:first-child").textContent = entryCount;
    });
  }

  document
    .getElementById("reportForm")
    .addEventListener("submit", async (e) => {
      e.preventDefault();
      const technology = document.getElementById("technology").value.trim();
      if (!technology) return alert("Technology is required.");

      const entries = [];
      let valid = true;
      entriesTableBody.querySelectorAll("tr").forEach((row) => {
        const work = row.querySelector("textarea").value.trim();
        const from = row.querySelector(
          'input[type="time"]:first-of-type'
        ).value;
        const to = row.querySelector('input[type="time"]:last-of-type').value;
        if (!work || !from || !to) valid = false;
        entries.push({
          sl_no: parseInt(row.querySelector("td:first-child").textContent),
          work_completed: work,
          from_time: from,
          to_time: to,
        });
      });
      if (!valid || entries.length === 0)
        return alert("All fields in entries must be filled.");

      try {
        const response = await fetch("/save", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ date: reportDate, technology, entries }),
        });
        const data = await response.json();
        if (!data.success) throw new Error("Save failed.");

        const wsData = [
          ["Name", userName, "Date", displayDate],
          ["Technology", technology],
          [],
          ["Sl. No", "Work Completed", "From", "To"],
          ...entries.map((e) => [
            e.sl_no,
            e.work_completed,
            e.from_time,
            e.to_time,
          ]),
        ];

        const ws = XLSX.utils.aoa_to_sheet(wsData);

        ws["!ref"] = XLSX.utils.encode_range({
          s: { c: 0, r: 0 },
          e: { c: 3, r: wsData.length - 1 },
        });

        const boldCells = [
          "A1",
          "B1",
          "C1",
          "D1",
          "A2",
          "B2",
          "A4",
          "B4",
          "C4",
          "D4",
        ];
        boldCells.forEach((cell) => {
          if (ws[cell]) {
            ws[cell].s = {
              font: { bold: true },
              border: {
                top: { style: "thin", color: { auto: 1 } },
                bottom: { style: "thin", color: { auto: 1 } },
                left: { style: "thin", color: { auto: 1 } },
                right: { style: "thin", color: { auto: 1 } },
              },
            };
            console.log(`Applied bold and border to cell ${cell}`);
          } else {
            console.warn(`Cell ${cell} not found in worksheet`);
          }
        });

        for (let cell in ws) {
          if (cell[0] === "!") continue;
          if (!ws[cell].s) ws[cell].s = {};
          ws[cell].s.border = {
            top: { style: "thin", color: { auto: 1 } },
            bottom: { style: "thin", color: { auto: 1 } },
            left: { style: "thin", color: { auto: 1 } },
            right: { style: "thin", color: { auto: 1 } },
          };
          if (!boldCells.includes(cell)) {
            ws[cell].s.font = { bold: false };
          }
          console.log(`Applied border to cell ${cell}`);
        }

        ws["!cols"] = [{ wch: 10 }, { wch: 40 }, { wch: 10 }, { wch: 10 }];

        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Work-Report");
        XLSX.writeFile(
          wb,
          `${userName.replace(/\s/g, "")}-WorkReport-${displayDate}.xlsx`
        );

        alert("Report submitted and saved successfully.");

        document.getElementById("technology").value = "";
        entriesTableBody.innerHTML = "";
        entryCount = 0;
      } catch (error) {
        alert(`Error: ${error.message}`);
      }
    });

  document.getElementById("fetchReport").addEventListener("click", async () => {
    const fetchDateInput = document.getElementById("fetchDate").value;
    if (!fetchDateInput) return alert("Select a date.");

    try {
      const response = await fetch(`/fetch?date=${fetchDateInput}`);
      const records = await response.json();
      const previousReportDiv = document.getElementById("previousReport");
      previousReportDiv.innerHTML = "";

      if (records.length === 0) {
        previousReportDiv.innerHTML = "<p>No records found for this date.</p>";
        return;
      }

      const tech = records[0].technology;
      let html = `
        <h5>Report for ${fetchDateInput}</h5>
        <p><strong>Name:</strong> ${userName}</p>
        <p><strong>Technology:</strong> ${tech}</p>
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>Sl. No</th>
              <th>Work Completed</th>
              <th>From</th>
              <th>To</th>
            </tr>
          </thead>
          <tbody>
      `;
      records.forEach((rec) => {
        html += `
          <tr>
            <td>${rec.sl_no}</td>
            <td>${rec.work_completed}</td>
            <td>${rec.from_time}</td>
            <td>${rec.to_time}</td>
          </tr>
        `;
      });
      html += "</tbody></table>";
      previousReportDiv.innerHTML = html;
    } catch (error) {
      alert(`Error: ${error.message}`);
    }
  });
});