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-06-06 17:54:56 +00:00
|
|
|
const op = "mysqladdress.createBenefactorAddress"
|
2024-01-16 16:13:06 +00:00
|
|
|
|
2024-06-06 17:54:56 +00:00
|
|
|
provinceID, err := d.getProvinceIDByCityID(ctx, address.CityID)
|
|
|
|
if err != nil {
|
|
|
|
return entity.Address{}, err
|
2024-05-26 16:26:18 +00:00
|
|
|
}
|
|
|
|
address.ProvinceID = provinceID
|
2024-05-21 19:46:06 +00:00
|
|
|
|
|
|
|
// Insert the new address
|
2024-05-30 12:57:33 +00:00
|
|
|
res, err := d.conn.Conn().ExecContext(ctx, `INSERT INTO addresses (postal_code, address, lat, lon, name, city_id, province_id, benefactor_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
|
|
address.PostalCode, address.Address, address.Lat, address.Lon, address.Name, address.CityID, provinceID, address.BenefactorID)
|
2024-01-16 16:13:06 +00:00
|
|
|
if err != nil {
|
|
|
|
return entity.Address{}, richerror.New(op).WithErr(err).
|
2024-06-06 17:54:56 +00:00
|
|
|
WithMessage(errmsg.ErrorMsgCantInsertRecord).WithKind(richerror.KindUnexpected)
|
2024-01-16 16:13:06 +00:00
|
|
|
}
|
|
|
|
|
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).
|
2024-06-06 17:54:56 +00:00
|
|
|
WithMessage(errmsg.ErrorMsgCantRetrieveLastInsertID).WithKind(richerror.KindUnexpected)
|
2024-05-21 19:46:06 +00:00
|
|
|
}
|
2024-01-16 16:13:06 +00:00
|
|
|
address.ID = uint(id)
|
|
|
|
|
|
|
|
return address, nil
|
|
|
|
}
|
2024-06-06 17:54:56 +00:00
|
|
|
|
|
|
|
func (d *DB) getProvinceIDByCityID(ctx context.Context, cityID uint) (uint, error) {
|
|
|
|
const op = "mysqladdress.getProvinceIDByCityID"
|
|
|
|
|
|
|
|
var provinceID uint
|
|
|
|
pErr := d.conn.Conn().QueryRowContext(ctx, `SELECT province_id FROM cities WHERE id = ?`, cityID).Scan(&provinceID)
|
|
|
|
if pErr != nil && pErr != sql.ErrNoRows {
|
|
|
|
return 0, richerror.New(op).WithErr(pErr).
|
|
|
|
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
|
|
|
|
}
|
|
|
|
|
|
|
|
return provinceID, nil
|
|
|
|
}
|