From cee291a88f925020058b78aa6821af5d66dea71f Mon Sep 17 00:00:00 2001 From: Ruidy Date: Fri, 14 Jun 2024 13:07:53 +0200 Subject: [PATCH] move to service --- internal/booking/service.go | 120 +++++++++++++++++++++++++++ internal/server/handle_api_sync.go | 129 +---------------------------- 2 files changed, 123 insertions(+), 126 deletions(-) diff --git a/internal/booking/service.go b/internal/booking/service.go index 89522ac..b1a45fb 100644 --- a/internal/booking/service.go +++ b/internal/booking/service.go @@ -1,8 +1,11 @@ package booking import ( + "encoding/json" "fmt" + "regexp" "strconv" + "strings" "time" u "github.com/rjNemo/underscore" @@ -217,3 +220,120 @@ func (bs Service) Cancel(id int) { b := &Booking{Id: id} bs.db.Model(&b).Update("canceled", true) } + +type BookingInfo struct { + Content string `json:"content"` +} + +func (bs Service) ParseFromApi(rawContent string) (*Booking, error) { + var bookingInfo BookingInfo + err := json.Unmarshal([]byte(rawContent), &bookingInfo) + if err != nil { + return nil, fmt.Errorf("Error unmarshalling JSON:", err) + } + + content := strings.ReplaceAll(strings.TrimSpace(bookingInfo.Content), "\u00a0", " ") + + arrivalDate := extractDate(`Date d'arrivée `, content) + departureDate := extractDate(`Date de départ `, content) + stayLength := extractInt(`Durée de séjour : (\d+) nuits`, content) + totalAmount := extractFloat(`Montant total € (\d+)`, content) + customerName := extractString(`Nom du client : \n\s+([\w\s]+)`, content) + customerName = strings.SplitN(customerName, "\n", 2)[0] + customerEmail := extractString(`[\w\.\-]+@[\w\.\-]+\.\w+`, content) + customerNumber := extractInt(`Nombre de personnes : \s*\n\s*(\d+)`, content) + commissionAmount := extractFloat(`Commission : € (\d+,\d+)`, content) + item := extractString(`Maison 1 Chambre \((T2|T3) -`, content) + standardRate := extractFloat(`Standard Rate\n\s+€ (\d+)`, content) + + result := map[string]any{ + "from": formatDate(arrivalDate), + "to": formatDate(departureDate), + "stay_length": stayLength, + "total_amount": totalAmount, + "customer_name": customerName, + "email": customerEmail, + "customer_number": customerNumber, + "commission_amount": commissionAmount, + "item": item, + "price": standardRate, + } + + jsonResult, err := json.MarshalIndent(result, "", " ") + if err != nil { + return nil, fmt.Errorf("error unmarshalling JSON: %w", err) + } + + b := new(Booking) + + if err = json.Unmarshal(jsonResult, b); err != nil { + return nil, fmt.Errorf("error unmarshalling JSON: %w", err) + } + + return b, nil +} + +func extractDate(pattern, content string) string { + re := regexp.MustCompile(pattern + `\w+\.\s*\d{1,2}\s\w+\.\s\d{4}`) + dateMatch := re.FindString(content) + + if dateMatch == "" { + fmt.Println("date not found") + return "" + } + + // Regular expression to remove the prefix + rePrefix := regexp.MustCompile(pattern + `\w+\.\s*`) + dateString := rePrefix.ReplaceAllString(dateMatch, "") + return dateString +} + +func extractInt(pattern, content string) int { + re := regexp.MustCompile(pattern) + match := re.FindStringSubmatch(content) + if len(match) > 1 { + val, err := strconv.Atoi(match[1]) + if err == nil { + return val + } + } + return 0 +} + +func extractFloat(pattern, content string) float64 { + re := regexp.MustCompile(pattern) + match := re.FindStringSubmatch(content) + if len(match) > 1 { + val, err := strconv.ParseFloat(strings.ReplaceAll(match[1], ",", "."), 64) + if err == nil { + return val + } + } + return 0.0 +} + +func extractString(pattern, content string) string { + re := regexp.MustCompile(pattern) + match := re.FindStringSubmatch(content) + if len(match) > 1 { + return strings.TrimSpace(match[1]) + } + return strings.TrimSpace(match[0]) +} + +func formatDate(date string) string { + months := map[string]string{ + "janv.": "01", "fév": "02", "mar": "03", "avr": "04", + "mai": "05", "jun": "06", "juil.": "07", "aoû": "08", + "sep": "09", "oct": "10", "nov": "11", "déc": "12", + } + re := regexp.MustCompile(`(\d+)\s([^\s]+)\s(\d{4})`) + match := re.FindStringSubmatch(date) + if len(match) > 3 { + day := match[1] + month := months[match[2]] + year := match[3][2:] + return fmt.Sprintf("%02s/%02s/%s", day, month, year) + } + return "" +} diff --git a/internal/server/handle_api_sync.go b/internal/server/handle_api_sync.go index c38e6f2..7fdb521 100644 --- a/internal/server/handle_api_sync.go +++ b/internal/server/handle_api_sync.go @@ -1,13 +1,8 @@ package server import ( - "encoding/json" - "fmt" "io" "net/http" - "regexp" - "strconv" - "strings" "github.com/labstack/echo/v4" "github.com/labstack/gommon/log" @@ -15,137 +10,19 @@ import ( "github.com/rjNemo/rentease/internal/booking" ) -type BookingInfo struct { - Content string `json:"content"` -} - -func handleSync() echo.HandlerFunc { +func handleSync(bs *booking.Service) echo.HandlerFunc { return func(c echo.Context) error { x := c.Request().Body body, err := io.ReadAll(x) if err != nil { return c.String(http.StatusInternalServerError, err.Error()) } - b, err := parseBooking(string(body)) + b, err := bs.ParseFromApi(string(body)) if err != nil { return c.String(http.StatusInternalServerError, err.Error()) } log.Warnf("%+v", b) - return c.String(http.StatusCreated, "👍") + return c.JSON(http.StatusCreated, b) } } - -func parseBooking(jsonString string) (*booking.Booking, error) { - var bookingInfo BookingInfo - err := json.Unmarshal([]byte(jsonString), &bookingInfo) - if err != nil { - return nil, fmt.Errorf("Error unmarshalling JSON:", err) - } - - content := strings.ReplaceAll(strings.TrimSpace(bookingInfo.Content), "\u00a0", " ") - - arrivalDate := extractDate(`Date d'arrivée `, content) - departureDate := extractDate(`Date de départ `, content) - stayLength := extractInt(`Durée de séjour : (\d+) nuits`, content) - totalAmount := extractFloat(`Montant total € (\d+)`, content) - customerName := extractString(`Nom du client : \n\s+([\w\s]+)`, content) - customerName = strings.SplitN(customerName, "\n", 2)[0] - customerEmail := extractString(`[\w\.\-]+@[\w\.\-]+\.\w+`, content) - customerNumber := extractInt(`Nombre de personnes : \s*\n\s*(\d+)`, content) - commissionAmount := extractFloat(`Commission : € (\d+,\d+)`, content) - item := extractString(`Maison 1 Chambre \((T2|T3) -`, content) - standardRate := extractFloat(`Standard Rate\n\s+€ (\d+)`, content) - - result := map[string]any{ - "from": formatDate(arrivalDate), - "to": formatDate(departureDate), - "stay_length": stayLength, - "total_amount": totalAmount, - "customer_name": customerName, - "email": customerEmail, - "customer_number": customerNumber, - "commission_amount": commissionAmount, - "item": item, - "price": standardRate, - } - - jsonResult, err := json.MarshalIndent(result, "", " ") - if err != nil { - return nil, fmt.Errorf("error unmarshalling JSON: %w", err) - } - - fmt.Println(string(jsonResult)) - b := new(booking.Booking) - - if err = json.Unmarshal(jsonResult, b); err != nil { - return nil, fmt.Errorf("error unmarshalling JSON: %w", err) - } - - return b, nil -} - -func extractDate(pattern, content string) string { - re := regexp.MustCompile(pattern + `\w+\.\s*\d{1,2}\s\w+\.\s\d{4}`) - dateMatch := re.FindString(content) - - if dateMatch == "" { - fmt.Println("date not found") - return "" - } - - // Regular expression to remove the prefix - rePrefix := regexp.MustCompile(pattern + `\w+\.\s*`) - dateString := rePrefix.ReplaceAllString(dateMatch, "") - return dateString -} - -func extractInt(pattern, content string) int { - re := regexp.MustCompile(pattern) - match := re.FindStringSubmatch(content) - if len(match) > 1 { - val, err := strconv.Atoi(match[1]) - if err == nil { - return val - } - } - return 0 -} - -func extractFloat(pattern, content string) float64 { - re := regexp.MustCompile(pattern) - match := re.FindStringSubmatch(content) - if len(match) > 1 { - val, err := strconv.ParseFloat(strings.ReplaceAll(match[1], ",", "."), 64) - if err == nil { - return val - } - } - return 0.0 -} - -func extractString(pattern, content string) string { - re := regexp.MustCompile(pattern) - match := re.FindStringSubmatch(content) - if len(match) > 1 { - return strings.TrimSpace(match[1]) - } - return strings.TrimSpace(match[0]) -} - -func formatDate(date string) string { - months := map[string]string{ - "janv.": "01", "fév": "02", "mar": "03", "avr": "04", - "mai": "05", "jun": "06", "juil.": "07", "aoû": "08", - "sep": "09", "oct": "10", "nov": "11", "déc": "12", - } - re := regexp.MustCompile(`(\d+)\s([^\s]+)\s(\d{4})`) - match := re.FindStringSubmatch(date) - if len(match) > 3 { - day := match[1] - month := months[match[2]] - year := match[3][2:] - return fmt.Sprintf("%02s/%02s/%s", day, month, year) - } - return "" -}