2024-01-16 16:13:06 +00:00
|
|
|
package mysqladdress
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-05-21 19:46:06 +00:00
|
|
|
"database/sql"
|
2024-01-16 16:13:06 +00:00
|
|
|
|
|
|
|
"git.gocasts.ir/ebhomengo/niki/entity"
|
|
|
|
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
|
|
|
|
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
|
|
|
|
)
|
|
|
|
|
2024-01-19 16:37:15 +00:00
|
|
|
func (d *DB) CreateBenefactorAddress(ctx context.Context, address entity.Address) (entity.Address, error) {
|
2024-01-16 16:13:06 +00:00
|
|
|
const op = "mysqlbenefactor.createBenefactorAddress"
|
|
|
|
|
2024-05-21 19:46:06 +00:00
|
|
|
// 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)
|
2024-01-16 16:13:06 +00:00
|
|
|
if err != nil {
|
|
|
|
return entity.Address{}, richerror.New(op).WithErr(err).
|
|
|
|
WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindUnexpected)
|
|
|
|
}
|
|
|
|
|
2024-05-21 19:46:06 +00:00
|
|
|
// 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)
|
|
|
|
}
|
2024-01-16 16:13:06 +00:00
|
|
|
address.ID = uint(id)
|
|
|
|
|
|
|
|
return address, nil
|
|
|
|
}
|