87 lines
2.5 KiB
Go
87 lines
2.5 KiB
Go
package listing
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
|
|
"hfb_sys/backend/internal/model"
|
|
"hfb_sys/backend/internal/tenancy"
|
|
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
func (r *Repository) FindTenantOffer(ctx context.Context, listingID uint64) (*TenantListingOfferDTO, error) {
|
|
tenantID := tenancy.IDFromContext(ctx)
|
|
if tenantID == 0 {
|
|
return nil, ErrTenantRequired
|
|
}
|
|
var listing model.RentalListing
|
|
if err := r.db.WithContext(ctx).Select("id, price_cent").First(&listing, listingID).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
var offer model.TenantListingOffer
|
|
if err := r.db.WithContext(ctx).
|
|
Where("tenant_id = ? AND listing_id = ?", tenantID, listingID).
|
|
First(&offer).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return tenantOfferDTO(offer, listing.PriceCent), nil
|
|
}
|
|
|
|
func (r *Repository) UpdateTenantOffer(
|
|
ctx context.Context,
|
|
listingID uint64,
|
|
req UpdateTenantListingOfferRequest,
|
|
) (*TenantListingOfferDTO, error) {
|
|
tenantID := tenancy.IDFromContext(ctx)
|
|
if tenantID == 0 {
|
|
return nil, ErrTenantRequired
|
|
}
|
|
displayStatus := strings.TrimSpace(req.DisplayStatus)
|
|
if displayStatus == "" {
|
|
displayStatus = "enabled"
|
|
}
|
|
if displayStatus != "enabled" && displayStatus != "disabled" {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
if req.PriceCent != nil && *req.PriceCent < 0 {
|
|
return nil, ErrInvalidPrice
|
|
}
|
|
var listing model.RentalListing
|
|
if err := r.db.WithContext(ctx).Select("id, price_cent").First(&listing, listingID).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, ErrListingNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
offer := model.TenantListingOffer{
|
|
TenantID: tenantID,
|
|
ListingID: listingID,
|
|
DisplayStatus: displayStatus,
|
|
PriceCent: req.PriceCent,
|
|
}
|
|
if err := r.db.WithContext(ctx).Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "listing_id"}},
|
|
DoUpdates: clause.AssignmentColumns([]string{"display_status", "price_cent", "updated_at"}),
|
|
}).Create(&offer).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return tenantOfferDTO(offer, listing.PriceCent), nil
|
|
}
|
|
|
|
func tenantOfferDTO(offer model.TenantListingOffer, basePriceCent int64) *TenantListingOfferDTO {
|
|
effectivePriceCent := basePriceCent
|
|
if offer.PriceCent != nil && *offer.PriceCent > 0 {
|
|
effectivePriceCent = *offer.PriceCent
|
|
}
|
|
return &TenantListingOfferDTO{
|
|
TenantID: offer.TenantID,
|
|
ListingID: offer.ListingID,
|
|
DisplayStatus: offer.DisplayStatus,
|
|
PriceCent: offer.PriceCent,
|
|
EffectivePriceCent: effectivePriceCent,
|
|
}
|
|
}
|