package repository import ( "time" "users_management/m/model/entity" "github.com/google/uuid" "gorm.io/gorm" ) type DevicesRepo interface { Post(device entity.Device) error GetAll() ([]entity.Device, error) Update(id uuid.UUID,updates map[string]interface{}) error GetByID(id uuid.UUID) (entity.Device, error) GetByType(deviceType string) ([]entity.Device, error) } type devicesRepo struct { db *gorm.DB } func NewDevicesRepo(db *gorm.DB) DevicesRepo { return &devicesRepo{ db: db, } } func (r *devicesRepo) Post(device entity.Device) error { return r.db.Transaction(func(tx *gorm.DB) error { // Create the device first if err := tx.Create(&device).Error; err != nil { return err } // Create the corresponding DevicePort record customerCount := 0 customerNames := make([]string, 0) // For ODP devices, initialize customer tracking if device.DeviceType == "ODP" { // Customer count starts at 0, will be updated when fishbones are connected customerCount = 0 } devicePort := entity.DevicePort{ ID: uuid.New(), DeviceID: device.ID, PortUsed: 0, PortAvailable: device.PortAmount, CustomerCount: customerCount, CustomerNames: customerNames, CreatedAt: time.Now(), UpdatedAt: time.Now(), } if err := tx.Create(&devicePort).Error; err != nil { return err } return nil }) } func (r *devicesRepo) GetAll() ([]entity.Device, error) { var devices []entity.Device err := r.db.Find(&devices).Error if err != nil { return devices, err } return devices, nil } func (r *devicesRepo) Update(id uuid.UUID,updates map[string]interface{}) error { err := r.db.Model(&entity.Device{}).Where("id = ?", id).Updates(updates).Error if err != nil { return err } return nil } func (r *devicesRepo) GetByID(id uuid.UUID) (entity.Device, error) { var device entity.Device err := r.db.Where("id = ?", id).First(&device).Error if err != nil { return device, err } return device, nil } func (r *devicesRepo) GetByType(deviceType string) ([]entity.Device, error) { var devices []entity.Device err := r.db.Where("device_type = ?", deviceType).Find(&devices).Error if err != nil { return devices, err } return devices, nil }