87 lines
2.4 KiB
Go
87 lines
2.4 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"git.techease.ru/Smart-search/smart-search-back/internal/repository"
|
|
"git.techease.ru/Smart-search/smart-search-back/pkg/errors"
|
|
"github.com/google/uuid"
|
|
"github.com/xuri/excelize/v2"
|
|
)
|
|
|
|
type supplierService struct {
|
|
supplierRepo repository.SupplierRepository
|
|
requestRepo repository.RequestRepository
|
|
}
|
|
|
|
func NewSupplierService(supplierRepo repository.SupplierRepository, requestRepo repository.RequestRepository) SupplierService {
|
|
return &supplierService{
|
|
supplierRepo: supplierRepo,
|
|
requestRepo: requestRepo,
|
|
}
|
|
}
|
|
|
|
func (s *supplierService) ExportExcel(ctx context.Context, requestID uuid.UUID, userID int) ([]byte, error) {
|
|
isOwner, err := s.requestRepo.CheckOwnership(ctx, requestID, userID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !isOwner {
|
|
return nil, errors.NewBusinessError(errors.PermissionDenied, "access denied to this request")
|
|
}
|
|
|
|
suppliers, err := s.supplierRepo.GetByRequestID(ctx, requestID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
f := excelize.NewFile()
|
|
defer func() { _ = f.Close() }()
|
|
|
|
sheetName := "Suppliers"
|
|
index, err := f.NewSheet(sheetName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
headers := []string{"Company ID", "Email", "Phone", "Company Name", "URL"}
|
|
for i, header := range headers {
|
|
cell := fmt.Sprintf("%c1", 'A'+i)
|
|
_ = f.SetCellValue(sheetName, cell, header)
|
|
}
|
|
|
|
style, err := f.NewStyle(&excelize.Style{
|
|
Font: &excelize.Font{Bold: true},
|
|
Fill: excelize.Fill{Type: "pattern", Color: []string{"#E0E0E0"}, Pattern: 1},
|
|
})
|
|
if err == nil {
|
|
_ = f.SetCellStyle(sheetName, "A1", fmt.Sprintf("%c1", 'A'+len(headers)-1), style)
|
|
}
|
|
|
|
for i, supplier := range suppliers {
|
|
row := i + 2
|
|
_ = f.SetCellValue(sheetName, fmt.Sprintf("A%d", row), supplier.ID)
|
|
_ = f.SetCellValue(sheetName, fmt.Sprintf("B%d", row), supplier.Email)
|
|
_ = f.SetCellValue(sheetName, fmt.Sprintf("C%d", row), supplier.Phone)
|
|
_ = f.SetCellValue(sheetName, fmt.Sprintf("D%d", row), supplier.Name)
|
|
_ = f.SetCellValue(sheetName, fmt.Sprintf("E%d", row), supplier.URL)
|
|
}
|
|
|
|
_ = f.SetColWidth(sheetName, "A", "A", 12)
|
|
_ = f.SetColWidth(sheetName, "B", "B", 30)
|
|
_ = f.SetColWidth(sheetName, "C", "C", 20)
|
|
_ = f.SetColWidth(sheetName, "D", "D", 40)
|
|
_ = f.SetColWidth(sheetName, "E", "E", 40)
|
|
|
|
f.SetActiveSheet(index)
|
|
_ = f.DeleteSheet("Sheet1")
|
|
|
|
buffer, err := f.WriteToBuffer()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return buffer.Bytes(), nil
|
|
}
|