package web
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"log"
"math"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
root "marmic/servicetrade-toolbox"
"marmic/servicetrade-toolbox/internal/api"
"marmic/servicetrade-toolbox/internal/middleware"
)
// DocumentsHandler handles the document upload page
func DocumentsHandler(w http.ResponseWriter, r *http.Request) {
session, ok := r.Context().Value(middleware.SessionKey).(*api.Session)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
tmpl := root.WebTemplates
data := map[string]interface{}{
"Title": "Document Uploads",
"Session": session,
}
if r.Header.Get("HX-Request") == "true" {
// For HTMX requests, just send the document_upload partial
if err := tmpl.ExecuteTemplate(w, "document_upload", data); err != nil {
log.Printf("Template execution error: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
} else {
// For full page requests, first render document_upload into a buffer
var contentBuf bytes.Buffer
if err := tmpl.ExecuteTemplate(&contentBuf, "document_upload", data); err != nil {
log.Printf("Template execution error: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Add the rendered content to the data for the layout
data["BodyContent"] = contentBuf.String()
// Now render the layout with our content
if err := tmpl.ExecuteTemplate(w, "layout.html", data); err != nil {
log.Printf("Template execution error: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
}
// ProcessCSVHandler processes a CSV file with job numbers
func ProcessCSVHandler(w http.ResponseWriter, r *http.Request) {
_, ok := r.Context().Value(middleware.SessionKey).(*api.Session)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Check if the request method is POST
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse the multipart form data with a 10MB limit
if err := r.ParseMultipartForm(10 << 20); err != nil {
http.Error(w, "Unable to parse form: "+err.Error(), http.StatusBadRequest)
return
}
// Get the file from the form
file, _, err := r.FormFile("csvFile")
if err != nil {
http.Error(w, "Error retrieving file: "+err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
// Read the CSV data
csvData, err := csv.NewReader(file).ReadAll()
if err != nil {
http.Error(w, "Error reading CSV file: "+err.Error(), http.StatusBadRequest)
return
}
if len(csvData) < 2 {
http.Error(w, "CSV file must contain at least a header row and one data row", http.StatusBadRequest)
return
}
// Find the index of the 'id' column
headerRow := csvData[0]
idColumnIndex := -1
for i, header := range headerRow {
if strings.ToLower(strings.TrimSpace(header)) == "id" {
idColumnIndex = i
break
}
}
// If 'id' column not found, try the first column
if idColumnIndex == -1 {
idColumnIndex = 0
log.Printf("No 'id' column found in CSV, using first column (header: %s)", headerRow[0])
} else {
log.Printf("Found 'id' column at index %d", idColumnIndex)
}
// Extract job numbers from the CSV
var jobNumbers []string
for rowIndex, row := range csvData {
// Skip header row
if rowIndex == 0 {
continue
}
if len(row) > idColumnIndex {
// Extract and clean up the job ID
jobID := strings.TrimSpace(row[idColumnIndex])
if jobID != "" {
jobNumbers = append(jobNumbers, jobID)
}
}
}
totalJobs := len(jobNumbers)
log.Printf("Extracted %d job IDs from CSV", totalJobs)
if totalJobs == 0 {
http.Error(w, "No valid job IDs found in the CSV file", http.StatusBadRequest)
return
}
// Create a hidden input with the job IDs
jobsValue := strings.Join(jobNumbers, ",")
jobSampleDisplay := getJobSampleDisplay(jobNumbers)
// Generate HTML for the main response (hidden input for job-ids-container)
var responseHTML bytes.Buffer
responseHTML.WriteString(fmt.Sprintf(``, jobsValue))
responseHTML.WriteString(fmt.Sprintf(`
") // End of file-results
} else {
resultHTML.WriteString("
No files processed for this job.
")
}
resultHTML.WriteString("
") // End of job-result
}
resultHTML.WriteString("
") // End of job-results
w.Header().Set("Content-Type", "text/html")
w.Write(resultHTML.Bytes())
}
// readCloserWithSize is a custom io.Reader that counts the bytes read
type readCloserWithSize struct {
reader io.ReadCloser
size int64
}
func (r *readCloserWithSize) Read(p []byte) (n int, err error) {
n, err = r.reader.Read(p)
r.size += int64(n)
return n, err
}
func (r *readCloserWithSize) Close() error {
return r.reader.Close()
}
// Size returns the current size of data read
func (r *readCloserWithSize) Size() int64 {
return r.size
}
// DocumentFieldAddHandler generates a new document field for the form
func DocumentFieldAddHandler(w http.ResponseWriter, r *http.Request) {
// Generate a random ID for the new field
newId := fmt.Sprintf("%d", time.Now().UnixNano())
// Create HTML for a new document row
html := fmt.Sprintf(`
`, newId, newId, newId, newId, newId, newId, newId, newId, newId)
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(html))
}
// DocumentFieldRemoveHandler handles the removal of a document field
func DocumentFieldRemoveHandler(w http.ResponseWriter, r *http.Request) {
// We read the ID but don't need to use it for simple removal
_ = r.URL.Query().Get("id")
// Count how many document rows exist
// For simplicity, we'll just return an empty response to remove the field
// In a complete implementation, we'd check if this is the last field and handle that case
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(""))
}