70 lines
2.0 KiB
Go
Raw Normal View History

package repository
import (
"context"
"database/sql"
"fmt"
"github.com/muyuqingfeng/iloom/auth-service/internal/model"
)
type CompanyRepo struct {
db *sql.DB
}
func NewCompanyRepo(db *sql.DB) *CompanyRepo {
return &CompanyRepo{db: db}
}
func (r *CompanyRepo) Create(ctx context.Context, c *model.Company) error {
query := `INSERT INTO ilm_company (id, name, type, address, phone, status, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`
_, err := r.db.ExecContext(ctx, query,
c.ID, c.Name, c.Role, c.Address, c.Phone, c.Status, c.CreatedAt,
)
if err != nil {
return fmt.Errorf("insert company: %w", err)
}
return nil
}
func (r *CompanyRepo) GetByID(ctx context.Context, id string) (*model.Company, error) {
query := `SELECT id, name, type, address, phone, status, created_at FROM ilm_company WHERE id = ?`
c := &model.Company{}
err := r.db.QueryRowContext(ctx, query, id).Scan(
&c.ID, &c.Name, &c.Role, &c.Address, &c.Phone, &c.Status, &c.CreatedAt,
)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, fmt.Errorf("get company by id: %w", err)
}
return c, nil
}
func (r *CompanyRepo) ListRelationships(ctx context.Context, companyID string) ([]model.CompanyRelationship, error) {
query := `SELECT id, purchaser_company_id, factory_company_id, factory_type, status, created_at, updated_at
FROM ilm_company_relationship
WHERE purchaser_company_id = ? OR factory_company_id = ?
ORDER BY created_at DESC`
rows, err := r.db.QueryContext(ctx, query, companyID, companyID)
if err != nil {
return nil, fmt.Errorf("list relationships: %w", err)
}
defer rows.Close()
var rels []model.CompanyRelationship
for rows.Next() {
var rel model.CompanyRelationship
if err := rows.Scan(
&rel.ID, &rel.PurchaserCompanyID, &rel.FactoryCompanyID,
&rel.FactoryType, &rel.Status, &rel.CreatedAt, &rel.UpdatedAt,
); err != nil {
return nil, fmt.Errorf("scan relationship: %w", err)
}
rels = append(rels, rel)
}
return rels, nil
}