From 53017a31a5ec2a33f5c56d0506dc245ef5fba2f1 Mon Sep 17 00:00:00 2001 From: javadifa Date: Tue, 21 May 2024 23:16:06 +0330 Subject: [PATCH] feat(repository): configured is_main field for CreateBenefactorAddress --- repository/mysql/address/create.go | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/repository/mysql/address/create.go b/repository/mysql/address/create.go index 926c45e..6a1557a 100644 --- a/repository/mysql/address/create.go +++ b/repository/mysql/address/create.go @@ -2,6 +2,7 @@ package mysqladdress import ( "context" + "database/sql" "git.gocasts.ir/ebhomengo/niki/entity" errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" @@ -11,16 +12,31 @@ import ( func (d *DB) CreateBenefactorAddress(ctx context.Context, address entity.Address) (entity.Address, error) { const op = "mysqlbenefactor.createBenefactorAddress" - res, err := d.conn.Conn().ExecContext(ctx, `insert into addresses(postal_code, address, lat, lon,province_id,city_id,benefactor_id) values(?, ?, ?,?,?,?,?)`, - address.PostalCode, address.Address, address.Lat, address.Lon, address.ProvinceID, address.CityID, address.BenefactorID) + // Check if the user already has a main address + var count int + err := d.conn.Conn().QueryRowContext(ctx, `SELECT COUNT(*) FROM addresses WHERE is_main = true AND benefactor_id = ?`, address.BenefactorID).Scan(&count) + if err != nil && err != sql.ErrNoRows { + return entity.Address{}, richerror.New(op).WithErr(err). + WithMessage("error querying for existing main address").WithKind(richerror.KindUnexpected) + } + + // Set is_main field based on the count + address.IsMain = count == 0 + + // Insert the new address + res, err := d.conn.Conn().ExecContext(ctx, `INSERT INTO addresses (postal_code, address, lat, lon, is_main, city_id, province_id, benefactor_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + address.PostalCode, address.Address, address.Lat, address.Lon, address.IsMain, address.CityID, address.ProvinceID, address.BenefactorID) if err != nil { return entity.Address{}, richerror.New(op).WithErr(err). WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindUnexpected) } - //nolint - // error is always nil - id, _ := res.LastInsertId() + // Get the ID of the newly inserted record + id, err := res.LastInsertId() + if err != nil { + return entity.Address{}, richerror.New(op).WithErr(err). + WithMessage("error retrieving last insert id").WithKind(richerror.KindUnexpected) + } address.ID = uint(id) return address, nil