dealroom/internal/handler/contacts.go

53 lines
1.5 KiB
Go

package handler
import (
"database/sql"
"net/http"
"dealroom/internal/model"
"dealroom/templates"
)
func (h *Handler) handleContacts(w http.ResponseWriter, r *http.Request) {
profile := getProfile(r.Context())
dealID := r.URL.Query().Get("deal_id")
deals := h.getDeals(profile)
var rows *sql.Rows
var err error
if dealID != "" {
rows, err = h.db.Query(`SELECT c.id, c.full_name, c.email, c.phone, c.company, c.title, c.contact_type, c.tags
FROM contacts c JOIN contact_deals cd ON c.id = cd.contact_id
WHERE c.organization_id = ? AND cd.deal_id = ? ORDER BY c.full_name`, profile.OrganizationID, dealID)
} else {
rows, err = h.db.Query("SELECT id, full_name, email, phone, company, title, contact_type, tags FROM contacts WHERE organization_id = ? ORDER BY full_name", profile.OrganizationID)
}
if err != nil {
http.Error(w, "Error loading contacts", 500)
return
}
defer rows.Close()
var contacts []*model.Contact
for rows.Next() {
c := &model.Contact{}
rows.Scan(&c.ID, &c.FullName, &c.Email, &c.Phone, &c.Company, &c.Title, &c.ContactType, &c.Tags)
contacts = append(contacts, c)
}
// Load deal names for each contact
for _, c := range contacts {
drows, _ := h.db.Query(`SELECT d.name FROM deals d JOIN contact_deals cd ON d.id = cd.deal_id WHERE cd.contact_id = ?`, c.ID)
if drows != nil {
for drows.Next() {
var name string
drows.Scan(&name)
c.DealNames = append(c.DealNames, name)
}
drows.Close()
}
}
templates.ContactsPage(profile, contacts, deals, dealID).Render(r.Context(), w)
}