Skip to content
Snippets Groups Projects
consent.go 6.08 KiB
Newer Older
  • Learn to ignore specific revisions
  • package models
    
    import (
    	"encoding/json"
    
    	"log"
    	"net/http"
    	"time"
    
    	"forge.grandlyon.com/web-et-numerique/llle_project/backoffice-server/internal/common"
    	"github.com/meilisearch/meilisearch-go"
    	"gorm.io/gorm"
    )
    
    type Consent struct {
    	gorm.Model
    	Firstname  string    `json:"firstname"`
    	Lastname   string    `json:"lastname"`
    	Address    string    `json:"address"`
    	PointID    int       `json:"pointID"`
    	PostalCode string    `json:"postalCode"`
    	InseeCode  string    `json:"inseeCode"`
    	EndDate    time.Time `json:"endDate"`
    	ServiceID  int       `json:"serviceID,omitempty"`
    }
    
    func (dh *DataHandler) GetConsentById(w http.ResponseWriter, r *http.Request) {
    	id, err := common.IdFromRequest(r)
    	if err != nil {
    		http.Error(w, err.Error(), http.StatusBadRequest)
    		return
    	}
    
    	var consent Consent
    	err = dh.sqlClient.First(&consent, id).Error
    	if err != nil {
    
    		if errors.Is(err, gorm.ErrRecordNotFound) {
    			http.Error(w, "consent not found", http.StatusNotFound)
    			return
    		}
    		http.Error(w, "error while finding consent", http.StatusInternalServerError)
    
    		return
    	}
    
    	w.Header().Set("Content-Type", "application/json")
    	json.NewEncoder(w).Encode(consent)
    
    	log.Printf("| get consent | name : %v | %v", consent.Lastname, r.RemoteAddr)
    }
    
    func (dh *DataHandler) PostConsent(w http.ResponseWriter, r *http.Request) {
    	if r.Body == http.NoBody {
    		http.Error(w, "request body is empty", http.StatusBadRequest)
    		return
    	}
    
    	decoder := json.NewDecoder(r.Body)
    	var consent Consent
    	err := decoder.Decode(&consent)
    	if err != nil {
    		http.Error(w, "couldn't parse body", http.StatusInternalServerError)
    		log.Println(err.Error())
    		return
    	}
    	consent.EndDate = time.Now().AddDate(1, 0, 0)
    
    	// Create a consent in SQL
    	err = dh.sqlClient.Create(&consent).Error
    	if err != nil {
    		http.Error(w, "couldn't create consent", http.StatusInternalServerError)
    		log.Println(err.Error())
    		return
    	}
    	// Adding consent in Meilisearch
    	_, err = dh.meiliClient.Index("consents").AddDocuments(consent)
    	if err != nil {
    		log.Println(err)
    		http.Error(w, "error when saving new consent", http.StatusInternalServerError)
    		return
    	}
    
    	w.Header().Set("Content-Type", "application/json")
    	w.WriteHeader(http.StatusCreated)
    	json.NewEncoder(w).Encode(consent)
    
    	log.Printf("| new consent | name : %v | %v", consent.Lastname, r.RemoteAddr)
    }
    
    func (dh *DataHandler) UpdateConsent(w http.ResponseWriter, r *http.Request) {
    	if r.Body == http.NoBody {
    		http.Error(w, "request body is empty", http.StatusBadRequest)
    		return
    	}
    	id, err := common.IdFromRequest(r)
    	if err != nil {
    		http.Error(w, err.Error(), http.StatusBadRequest)
    		return
    	}
    
    	// Find consent
    	var consent Consent
    	err = dh.sqlClient.First(&consent, id).Error
    	if err != nil {
    		http.Error(w, "couldn't find consent", http.StatusInternalServerError)
    		log.Println(err.Error())
    		return
    	}
    	// Get service ID
    	decoder := json.NewDecoder(r.Body)
    	var body struct {
    		ServiceID int `json:"serviceID"`
    	}
    	err = decoder.Decode(&body)
    	if err != nil {
    		http.Error(w, "couldn't parse body", http.StatusInternalServerError)
    		return
    	}
    	if body.ServiceID <= 0 {
    		http.Error(w, "invalid service id", http.StatusBadRequest)
    		return
    	}
    
    	// Update and save consent
    	consent.ServiceID = body.ServiceID
    	err = dh.sqlClient.Save(&consent).Error
    	if err != nil {
    		w.WriteHeader(http.StatusInternalServerError)
    		log.Println(err.Error())
    		return
    	}
    
    	w.Header().Set("Content-Type", "application/json")
    	json.NewEncoder(w).Encode(consent)
    
    	log.Printf("| updated consent | name : %v | serviceID : %v | %v", consent.Lastname, consent.ServiceID, r.RemoteAddr)
    }
    
    func (dh *DataHandler) DeleteConsentById(w http.ResponseWriter, r *http.Request) {
    	id, err := common.IdFromRequest(r)
    	if err != nil {
    		http.Error(w, err.Error(), http.StatusBadRequest)
    		return
    	}
    
    	var consent = Consent{}
    	err = dh.sqlClient.First(&consent, id).Error
    	if err != nil {
    		http.Error(w, "couldn't find consent", http.StatusInternalServerError)
    		log.Println(err.Error())
    		return
    	}
    
    
    	// Update and save consent in MySQL
    
    	consent.EndDate = time.Now()
    	err = dh.sqlClient.Save(&consent).Error
    	if err != nil {
    		w.WriteHeader(http.StatusInternalServerError)
    		log.Println(err.Error())
    		return
    	}
    
    	dh.sqlClient.Delete(&consent)
    
    
    	// Update and save consent in Meilisearch
    	deletedConsent := []map[string]interface{}{
    		{
    			"ID":        consent.ID,
    			"endDate":   consent.EndDate,
    			"DeletedAt": consent.DeletedAt,
    		},
    	}
    	dh.meiliClient.Index("consents").UpdateDocuments(deletedConsent)
    
    
    	log.Printf("| deleted consent | id : %d | %v", id, r.RemoteAddr)
    }
    
    func (dh *DataHandler) SearchConsent(w http.ResponseWriter, r *http.Request) {
    	search := r.URL.Query().Get("search")
    	if search != "" {
    		resp, err := dh.meiliClient.Index("consents").Search(search, &meilisearch.SearchRequest{
    			Limit: 50,
    		})
    		if err != nil {
    			http.Error(w, "error when searching consents", http.StatusInternalServerError)
    			log.Println(err.Error())
    			return
    		}
    
    		hits, err := json.Marshal(resp.Hits)
    		if err != nil {
    
    			http.Error(w, "error when marshal hits", http.StatusInternalServerError)
    			log.Println(err.Error())
    			return
    
    		}
    		var consents []Consent
    		err = json.Unmarshal(hits, &consents)
    
    		if err != nil {
    			http.Error(w, "error when unmarshal hits", http.StatusInternalServerError)
    			log.Println(err.Error())
    			return
    		}
    
    
    		w.Header().Set("Content-Type", "application/json")
    		json.NewEncoder(w).Encode(consents)
    
    		log.Printf("| searched consents | search : %v | %v", search, r.RemoteAddr)
    	} else {
    		page, limit, err := common.PageLimitFromRequest(r)
    		if err != nil {
    			http.Error(w, err.Error(), http.StatusBadRequest)
    			return
    		}
    
    		var totalRows int64
    		dh.sqlClient.Model(Consent{}).Count(&totalRows)
    		offset := page * limit
    
    		var consents []Consent
    		dh.sqlClient.Offset(offset).Limit(limit).Find(&consents)
    
    		var pagination struct {
    			TotalRows int64     `json:"totalRows"`
    			Rows      []Consent `json:"rows"`
    		}
    		pagination.TotalRows = totalRows
    		pagination.Rows = consents
    
    		w.Header().Set("Content-Type", "application/json")
    		json.NewEncoder(w).Encode(pagination)
    
    		log.Printf("| get all consents | limit : %d | page : %d | %v", limit, page, r.RemoteAddr)
    	}
    }