mirror of
https://github.com/rjNemo/rentease.git
synced 2026-06-06 02:36:49 +00:00
181 lines
7.7 KiB
Go
181 lines
7.7 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/labstack/gommon/log"
|
|
|
|
"github.com/rjNemo/rentease/internal/booking"
|
|
)
|
|
|
|
type BookingInfo struct {
|
|
Content string `json:"content"`
|
|
}
|
|
|
|
func handleSync() 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))
|
|
if err != nil {
|
|
return c.String(http.StatusInternalServerError, err.Error())
|
|
}
|
|
log.Warnf("%+v", b)
|
|
|
|
return c.String(http.StatusCreated, "👍")
|
|
}
|
|
}
|
|
|
|
func parseBooking(jsonString string) (*booking.Booking, error) {
|
|
//jsonString = `"{\"content\":\" Date d'arrivée ven.\u00a024\u00a0mai\u00a02024 Date de départ lun.\u00a027\u00a0mai\u00a02024 Durée de séjour\u00a0: 3 nuits Nombre de personnes\u00a0: \\n \\n Nombre d'hébergements \\n 1\\n Montant total € 186 Nom du client\u00a0: \\n Katrin Anschütz\\n \\n mq\\n \\n kansch.199923@guest.booking.com\\n Contactez vos clients\u00a0! Indiquez-leur l'heure à laquelle vous souhaitez les accueillir ou l'endroit où ils récupéreront leurs clés. Un simple appel suffit\u00a0: Afficher le numéro de téléphone Vous pouvez également leur envoyer un e-mail ou un message. Langue préférée \\n allemand\\n Canal\u00a0: Booking.com Code IATA/TIDS\u00a0: \\n PC029090\\n Numéro de réservation\u00a0: \\n 4489841169\\n Montant soumis à commission\u00a0: € 177 Reçu jeu.\u00a016\u00a0mai\u00a02024 Commission\u00a0: € 31,86 Bloc-notes (usage interne) Ajoutez une note ici Heure d'arrivée approximative\u00a0: Entre 16:00 et 17:00 \\n\\n Maison 1 Chambre (T2 - VillaFleurie au bourg du Gosier)\\n € 186 ven.\u00a024\u00a0mai\u00a02024 lun.\u00a027\u00a0mai\u00a02024 Nom du client \\n Katrin Anschütz\\n Occupation maximum 2 adultes, 2 enfants (3 personnes max.) Photo de l'hébergement Date Tarif Tarif par nuit \\n 24 - 25 mai\\n \\n Standard Rate\\n € 59\\n 25 - 26 mai\\n \\n Standard Rate\\n € 59\\n 26 - 27 mai\\n \\n Standard Rate\\n € 59Sous-total € 177\\n Taxe de séjour\\n € 1.50 par personne et par nuit € 9Tarif total de l'hébergement € 186 Le tarif comprend 8.9 % de TVA Conversation avec le client \\n Aucun message\\n \\n Les conversations avec vos clients apparaîtront ici.\\n Booking.com reçoit tous les messages écrits ici et les traite selon sa Charte de confidentialité et informations sur les cookies Conditions \"}"}`
|
|
|
|
var bookingInfo BookingInfo
|
|
err := json.Unmarshal([]byte(jsonString), &bookingInfo)
|
|
if err != nil {
|
|
fmt.Println("Error unmarshalling JSON:", err)
|
|
return nil, err
|
|
}
|
|
content := bookingInfo.Content
|
|
log.Info(extractData(content))
|
|
|
|
arrivalDate := extractDate(`Date de d'arrivée `, content)
|
|
log.Info(arrivalDate)
|
|
departureDate := extractDate(`Date de départ `, content)
|
|
log.Info(departureDate)
|
|
stayLength := extractInt(`Durée de séjour : (\d+) nuits`, content)
|
|
totalAmount := extractFloat(`Montant total € (\d+)`, content)
|
|
customerName := extractString(`Nom du client : \\n\s*(\S.+)\\n`, content)
|
|
commissionAmount := extractFloat(`Commission : € (\d+,\d+)`, content)
|
|
item := extractString(`Maison 1 Chambre \((T2|T3) -`, content)
|
|
standardRate := extractFloat(`Standard Rate\\n\s*€ (\d+)`, content)
|
|
taxesAmount := extractFloat(`Taxe de séjour\\n\s*€ (\d+,\d+)`, content)
|
|
|
|
result := map[string]any{
|
|
"from": formatDate(arrivalDate),
|
|
"to": formatDate(departureDate),
|
|
"stay_length": stayLength,
|
|
"total_amount": totalAmount,
|
|
"customer_name": customerName,
|
|
"commission_amount": commissionAmount,
|
|
"item": item,
|
|
"price": standardRate,
|
|
"taxes_amount": taxesAmount,
|
|
}
|
|
|
|
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 {
|
|
cleanedInput := strings.ReplaceAll(content, "\u00a0", " ")
|
|
re := regexp.MustCompile(pattern + `\w+\.\s*\d{1,2}\s\w+\.\s\d{4}`)
|
|
dateMatch := re.FindString(cleanedInput)
|
|
|
|
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 ""
|
|
}
|
|
|
|
func formatDate(date string) string {
|
|
months := map[string]string{
|
|
"janv.": "01", "fév": "02", "mar": "03", "avr": "04",
|
|
"mai": "05", "jun": "06", "jul": "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 ""
|
|
}
|
|
|
|
func extractData(content string) (string, string, string, string, string, string, string, string, string) {
|
|
// Define regex patterns for each field
|
|
arrivalDatePattern := regexp.MustCompile(`Date d'arrivée ven\\u00a0(\d{2}\\u00a0mai\\u00a020\d{2})`)
|
|
departureDatePattern := regexp.MustCompile(`Date de départ lun\\u00a0(\d{2}\\u00a0mai\\u00a020\d{2})`)
|
|
commissionPattern := regexp.MustCompile(`Commission\\u00a0: € (\d{2},\d{2})`)
|
|
customerNamePattern := regexp.MustCompile(`Nom du client\\u00a0: \\n\s+([\w\s]+)\\n`)
|
|
itemNamePattern := regexp.MustCompile(`Maison 1 Chambre $begin:math:text$([^)]+)$end:math:text$`)
|
|
itemPricePattern := regexp.MustCompile(`Tarif total de l'hébergement € (\d{3})`)
|
|
lengthOfStayPattern := regexp.MustCompile(`Durée de séjour\\u00a0: (\d{1}) nuits`)
|
|
amountOfTaxesPattern := regexp.MustCompile(`Taxe de séjour\\n\\u00a0€ (\d\.\d{2})`)
|
|
totalPricePattern := regexp.MustCompile(`Montant total € (\d{3})`)
|
|
|
|
// Extract data using regex
|
|
arrivalDate := arrivalDatePattern.FindStringSubmatch(content)
|
|
departureDate := departureDatePattern.FindStringSubmatch(content)
|
|
commission := commissionPattern.FindStringSubmatch(content)
|
|
customerName := customerNamePattern.FindStringSubmatch(content)
|
|
itemName := itemNamePattern.FindStringSubmatch(content)
|
|
itemPrice := itemPricePattern.FindStringSubmatch(content)
|
|
lengthOfStay := lengthOfStayPattern.FindStringSubmatch(content)
|
|
amountOfTaxes := amountOfTaxesPattern.FindStringSubmatch(content)
|
|
totalPrice := totalPricePattern.FindStringSubmatch(content)
|
|
|
|
// Return extracted data
|
|
return arrivalDate[1], departureDate[1], commission[1], customerName[1], itemName[1], itemPrice[1], lengthOfStay[1], amountOfTaxes[1], totalPrice[1]
|
|
}
|