From 24362b95eb975437a961e2c7e5ac62b21d85a769 Mon Sep 17 00:00:00 2001 From: Ruidy Date: Sun, 4 Feb 2024 15:24:16 +0100 Subject: [PATCH] can create a booking --- internal/server/handlers.go | 318 ++++++--------------------- internal/server/server.go | 3 + internal/views/bookings_new.templ | 9 +- internal/views/bookings_new_templ.go | 2 +- 4 files changed, 72 insertions(+), 260 deletions(-) diff --git a/internal/server/handlers.go b/internal/server/handlers.go index 76a1add..92a6ed6 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -2,8 +2,10 @@ package server import ( "net/http" + "time" "github.com/labstack/echo/v4" + "github.com/labstack/gommon/log" "github.com/rjNemo/rentease/constants" "github.com/rjNemo/rentease/internal/views" @@ -23,257 +25,65 @@ func (s Server) handleNewBookingPage() echo.HandlerFunc { } } -//func (s Server) handleLoginPage() echo.HandlerFunc { -// return func(c echo.Context) error { -// qs := c.QueryParams() -// errs := qs["err"] -// -// component := views.LoginPage(errs) -// return s.renderTempl(c, http.StatusOK, component) -// } -//} -// -//func (s Server) handleLogin() echo.HandlerFunc { -// return func(c echo.Context) error { -// email := c.FormValue("email") -// pwd := c.FormValue("password") -// -// user, err := s.us.SignIn(email, pwd) -// if err != nil { -// return c.Redirect(http.StatusSeeOther, fmt.Sprintf("%s?err=invalid+credentials", constants.RouteLogin)) -// } -// if err = writeCookie(c, user.Id, email, user.PaymentValid); err != nil { -// return c.Redirect(http.StatusSeeOther, fmt.Sprintf("%s?err=invalid+credentials", constants.RouteLogin)) -// } -// return c.Redirect(http.StatusFound, constants.RouteHome) -// } -//} -// -//func (s Server) handleLogout() echo.HandlerFunc { -// return func(c echo.Context) error { -// cookie := new(http.Cookie) -// cookie.Name = cookieName -// cookie.Value = "" -// cookie.MaxAge = 0 -// c.SetCookie(cookie) -// return c.Redirect(http.StatusFound, constants.RouteLogin) -// } -//} -// -//func (s Server) handleHomePage() echo.HandlerFunc { -// return func(c echo.Context) error { -// user := c.Get("user").(services.User) -// -// component := views.Home(&user, s.ms.List(user.Id)) -// return s.renderTempl(c, http.StatusOK, component) -// } -//} -// -//func (s Server) handleCreateMeetingNote() echo.HandlerFunc { -// return func(c echo.Context) error { -// memberId, err := strconv.Atoi(c.FormValue("member_id")) -// if err != nil { -// return err -// } -// -// audioFile, err := c.FormFile("audio_file") -// if err != nil { -// return err -// } -// -// err = s.ms.CreateNote(audioFile, memberId) -// if err != nil { -// return err -// } -// -// return c.Redirect(http.StatusFound, fmt.Sprintf("%s/%d", constants.RouteTeam, memberId)) -// } -//} -// -//func (s Server) handleTeamPage() echo.HandlerFunc { -// return func(c echo.Context) error { -// user := c.Get("user").(services.User) -// -// component := views.Team(&user, s.ms.List(user.Id)) -// return s.renderTempl(c, http.StatusOK, component) -// } -//} -// -//func (s Server) handleCreateTeamMember() echo.HandlerFunc { -// return func(c echo.Context) error { -// name := c.FormValue("name") -// user := c.Get("user").(services.User) -// if _, err := s.ms.Create(name, user.Id); err != nil { -// return err -// } -// return c.Redirect(http.StatusFound, constants.RouteTeam) -// } -//} -// -//func (s Server) handleUpdateTeamMember() echo.HandlerFunc { -// return func(c echo.Context) error { -// name := c.FormValue("name") -// description := c.FormValue("description") -// memberId, _ := strconv.Atoi(c.Param("id")) -// -// if _, err := s.ms.Update(name, description, memberId); err != nil { -// return err -// } -// return c.Redirect(http.StatusFound, fmt.Sprintf("%s/%d", constants.RouteTeam, memberId)) -// } -//} -// -//func (s Server) handleTeamMemberPage() echo.HandlerFunc { -// return func(c echo.Context) error { -// id, err := strconv.Atoi(c.Param("id")) -// if err != nil { -// return err -// } -// -// user := c.Get("user").(services.User) -// -// component := views.TeamMember(&user, s.ms.One(id)) -// return s.renderTempl(c, http.StatusOK, component) -// } -//} -// -//func (s Server) handleCheckoutPage() echo.HandlerFunc { -// return func(c echo.Context) error { -// component := views.Checkout(os.Getenv("STRIPE_LOOKUP_KEY")) -// return s.renderTempl(c, http.StatusOK, component) -// } -//} -// -//func (s Server) handleSuccessPage() echo.HandlerFunc { -// return func(c echo.Context) error { -// stripe.Key = os.Getenv("STRIPE_API_KEY") -// -// ss, _ := session.Get(c.QueryParam("session_id"), nil) -// log.Infof("%+v", ss.Customer) -// -// uid := c.QueryParam("u") -// userId, _ := strconv.Atoi(uid) -// err := s.us.SetPaymentStatus(userId, ss.Customer.ID) -// if err != nil { -// return c.Redirect(302, constants.RouteCancel) -// } -// -// component := views.Success() -// return s.renderTempl(c, http.StatusOK, component) -// } -//} -// -//func (s Server) handleCancelPage() echo.HandlerFunc { -// return func(c echo.Context) error { -// component := views.Cancel() -// return s.renderTempl(c, http.StatusOK, component) -// } -//} -// -//func (s Server) handleCreateCheckoutSession() echo.HandlerFunc { -// return func(c echo.Context) error { -// stripe.Key = os.Getenv("STRIPE_API_KEY") -// lookupKey := c.FormValue("lookup_key") -// -// params := &stripe.PriceListParams{ -// LookupKeys: stripe.StringSlice([]string{lookupKey}), -// } -// i := price.List(params) -// sp := new(stripe.Price) -// for i.Next() { -// p := i.Price() -// sp = p -// } -// -// domain := os.Getenv("STRIPE_DOMAIN") -// user := c.Get("user").(services.User) -// checkoutParams := &stripe.CheckoutSessionParams{ -// Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)), -// LineItems: []*stripe.CheckoutSessionLineItemParams{ -// {Price: stripe.String(sp.ID), Quantity: stripe.Int64(1)}, -// }, -// SuccessURL: stripe.String(fmt.Sprintf("%s%s?u=%d&session_id={CHECKOUT_SESSION_ID}", domain, constants.RouteSuccess, user.Id)), -// CancelURL: stripe.String(fmt.Sprintf("%s/cancel", domain)), -// } -// s, err := session.New(checkoutParams) -// if err != nil { -// log.Warnf("session.New %v", err) -// } -// -// return c.Redirect(http.StatusSeeOther, s.URL) -// } -//} -// -//func (s Server) handleCreatePortalSession() echo.HandlerFunc { -// return func(c echo.Context) error { -// stripe.Key = os.Getenv("STRIPE_API_KEY") -// u := c.Get("user").(services.User) -// user := s.us.One(u.Id) -// -// params := &stripe.BillingPortalSessionParams{ -// Customer: stripe.String(user.PaymentId), -// ReturnURL: stripe.String(os.Getenv("STRIPE_DOMAIN")), -// } -// ps, _ := portalsession.New(params) -// -// return c.Redirect(http.StatusSeeOther, ps.URL) -// } -//} -// -//func (s Server) handleWebhook() echo.HandlerFunc { -// return func(c echo.Context) error { -// payload, err := io.ReadAll(c.Request().Body) -// if err != nil { -// return c.String(http.StatusBadRequest, "Error reading request body: %v\n") -// } -// -// endpointSecret := os.Getenv("STRIPE_WEBHOOK_SECRET") -// signatureHeader := c.Request().Header.Get("Stripe-Signature") -// event, err := webhook.ConstructEvent(payload, signatureHeader, endpointSecret) -// if err != nil { -// return c.String(http.StatusBadRequest, fmt.Sprintf("⚠️ Webhook signature verification failed. %v\n", err)) -// } -// // Unmarshal the event data into an appropriate struct depending on its Type -// switch event.Type { -// case "customer.subscription.deleted": -// var subscription stripe.Subscription -// err := json.Unmarshal(event.Data.Raw, &subscription) -// if err != nil { -// return c.String(http.StatusBadRequest, "Error parsing webhook JSON: %v\n") -// } -// log.Printf("Subscription deleted for %s.", subscription.ID) -// // Then define and call a func to handle the deleted subscription. -// // handleSubscriptionCanceled(subscription) -// case "customer.subscription.updated": -// var subscription stripe.Subscription -// err := json.Unmarshal(event.Data.Raw, &subscription) -// if err != nil { -// return c.String(http.StatusBadRequest, "Error parsing webhook JSON: %v\n") -// } -// log.Printf("Subscription updated for %s.", subscription.ID) -// // Then define and call a func to handle the successful attachment of a PaymentMethod. -// // handleSubscriptionUpdated(subscription) -// case "customer.subscription.created": -// var subscription stripe.Subscription -// err := json.Unmarshal(event.Data.Raw, &subscription) -// if err != nil { -// return c.String(http.StatusBadRequest, "Error parsing webhook JSON: %v\n") -// } -// log.Printf("Subscription created for %s.", subscription.ID) -// // Then define and call a func to handle the successful attachment of a PaymentMethod. -// // handleSubscriptionCreated(subscription) -// case "customer.subscription.trial_will_end": -// var subscription stripe.Subscription -// err := json.Unmarshal(event.Data.Raw, &subscription) -// if err != nil { -// return c.String(http.StatusBadRequest, "Error parsing webhook JSON: %v\n") -// } -// log.Printf("Subscription trial will end for %s.", subscription.ID) -// // Then define and call a func to handle the successful attachment of a PaymentMethod. -// // handleSubscriptionTrialWillEnd(subscription) -// default: -// return c.String(http.StatusBadRequest, "Unhandled event type: %s\n") -// } -// return c.NoContent(http.StatusOK) -// } -//} +func (s Server) handleCreateBooking() echo.HandlerFunc { + return func(c echo.Context) error { + type NewBooking struct { + Name string `form:"name"` + PhoneNumber string `form:"phone_number"` + CustomerNumber string `form:"customer_number"` + Email string `form:"email"` + From time.Time `json:"from"` + To time.Time `from:"to"` + Platform string `form:"platform"` + PlatformFees string `form:"platform_fees"` + } + + nb := new(NewBooking) + err := c.Bind(nb) + if err != nil { + log.Warn(err) + return err + } + + ts, err := parseTime(c.FormValue("from")) + nb.From = ts + ts, err = parseTime(c.FormValue("to")) + nb.To = ts + + type Booking struct { + Id int + Name string `gorm:"column:customer_name"` + PhoneNumber string + CustomerNumber string `gorm:"column:customers"` + Email string + From time.Time + To time.Time + Platform string + PlatformFees string + } + // create a booking object + result := s.db.Create(&Booking{ + Name: nb.Name, + PhoneNumber: nb.PhoneNumber, + CustomerNumber: nb.CustomerNumber, + Email: nb.Email, + From: nb.From, + To: nb.To, + Platform: nb.Platform, + PlatformFees: nb.PlatformFees, + }) + log.Info(result.Error) + log.Info(result.RowsAffected) + // store it + // redirect to the booking page + return nil + } +} + +func parseTime(src string) (time.Time, error) { + ts, err := time.Parse("2006-01-02", src) + if err != nil { + return time.Time{}, err + } + return ts, nil +} diff --git a/internal/server/server.go b/internal/server/server.go index 919cd8c..b7f20e1 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -20,6 +20,7 @@ import ( type Server struct { Router *echo.Echo + db *gorm.DB //ms *services.MemberService //us *services.UserService addr string @@ -28,6 +29,7 @@ type Server struct { func New(db *gorm.DB) *Server { return &Server{ Router: echo.New(), + db: db, //ms: services.NewMemberService(db), //us: services.NewUserService(db), addr: fmt.Sprintf("0.0.0.0:%s", os.Getenv("PORT")), @@ -50,6 +52,7 @@ func (s Server) MountHandlers() { // landing page s.Router.GET("/", s.handleHomePage()) s.Router.GET(constants.RouteNewBooking, s.handleNewBookingPage()) + s.Router.POST(constants.RouteNewBooking, s.handleCreateBooking()) } func (s Server) Start() { diff --git a/internal/views/bookings_new.templ b/internal/views/bookings_new.templ index 6fcad65..0ae3389 100644 --- a/internal/views/bookings_new.templ +++ b/internal/views/bookings_new.templ @@ -1,13 +1,12 @@ package views - templ NewBooking(platforms []string) { @BaseLayout() {

New Booking

Create a new booking

-
+