package handlers import ( "net/http" "github.com/jmoiron/sqlx" "workorders/internal/model" ) type AccountingHandler struct{ db *sqlx.DB } func NewAccountingHandler(db *sqlx.DB) *AccountingHandler { return &AccountingHandler{db: db} } func (h *AccountingHandler) Get(w http.ResponseWriter, r *http.Request) { woID, err := intParam(r, "id") if err != nil { respondError(w, http.StatusBadRequest, "invalid id") return } var codes []model.AccountingCode h.db.Select(&codes, `SELECT * FROM wo_accounting WHERE wo_id=@p1`, woID) respond(w, http.StatusOK, codes) } func (h *AccountingHandler) Upsert(w http.ResponseWriter, r *http.Request) { woID, err := intParam(r, "id") if err != nil { respondError(w, http.StatusBadRequest, "invalid id") return } var codes []model.AccountingCode if err := decode(r, &codes); err != nil { respondError(w, http.StatusBadRequest, "invalid body") return } for _, c := range codes { h.db.Exec(` MERGE wo_accounting AS t USING (SELECT @p1 AS wo_id, @p2 AS code_type) AS s ON t.wo_id=s.wo_id AND t.code_type=s.code_type WHEN MATCHED THEN UPDATE SET code_value=@p3,description=@p4 WHEN NOT MATCHED THEN INSERT (wo_id,code_type,code_value,description) VALUES (@p1,@p2,@p3,@p4);`, woID, c.CodeType, c.CodeValue, c.Description, ) } var result []model.AccountingCode h.db.Select(&result, `SELECT * FROM wo_accounting WHERE wo_id=@p1`, woID) respond(w, http.StatusOK, result) }