company.go 9.6 KB
package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"github.com/astaxie/beego/logs"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
)

type SyncCompanyService struct{}

var _ SyncAction = (*SyncCompanyService)(nil)

type CompanyBaseApplet struct {
	Name string `json:"name"`
	URL  string `json:"url"`
	Id   string `json:"id"`
}

//企业平台的公司基础数据
type CompanyBase struct {
	Id             int64               `json:"id"`               //id
	Name           string              `json:"name"`             //公司名称名称
	AdminCompanyId int                 `json:"admin_company_id"` //总后台的公司id
	Logo           string              `json:"logo"`             //公司图标
	Remarks        string              `json:"remarks"`          //备注
	Abbreviation   string              `json:"abbreviation"`     //公司简称
	Applets        []CompanyBaseApplet `json:"applets"`          //公司对接的小程序
}

// CompanytData 企业平台发送过来的公司数据数据
type CompanytData struct {
	Company CompanyBase  `json:"company"`
	User    EmployeeData `json:"user"`
}

//CompanyCharge 企业平台发送过来的变更公司主管数据
type CompanyCharge struct {
	Id     int64   `json:"id"`
	Charge []int64 `json:"charge"`
}

func (service SyncCompanyService) DoAction(action string, byteData []byte) error {
	switch action {
	case "add":
		//添加公司
		var (
			data CompanytData
			err  error
		)
		err = json.Unmarshal(byteData, &data)
		if err != nil {
			return fmt.Errorf("数据解析失败:%s", err)
		}
		return service.addCompany(data)
	case "edit":
		//编辑
		var (
			data CompanytData
			err  error
		)
		err = json.Unmarshal(byteData, &data)
		if err != nil {
			return fmt.Errorf("数据解析失败:%s", err)
		}
		return service.updateCompany(data)
	case "setCompanyCharge":
		//设置公司主管
		var (
			data CompanyCharge
			err  error
		)
		err = json.Unmarshal(byteData, &data)
		if err != nil {
			return fmt.Errorf("数据解析失败:%s", err)
		}
		return service.updateCompanyCharge(data)
	default:
		return errors.New("action not found")
	}
}

//addCompany 添加公司
func (service SyncCompanyService) addCompany(data CompanytData) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var (
		companyRespository domain.CompanyRepository
		userRespository    domain.UsersRepository
	)
	if companyRespository, err = factory.CreateCompanyRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if userRespository, err = factory.CreateUsersRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	applets := []domain.CompanyApplets{}
	for _, v := range data.Company.Applets {
		app := domain.CompanyApplets{
			Name: v.Name,
			URL:  v.URL,
			Id:   v.Id,
		}
		applets = append(applets, app)
	}
	comany := domain.Company{
		Id:             data.Company.Id,
		Name:           data.Company.Name,
		Phone:          "",
		Logo:           data.Company.Logo,
		Remarks:        data.Company.Remarks,
		AdminCompanyId: data.Company.AdminCompanyId,
		//Status:         data.Company.Status,
		Enable:       domain.CompanyEnableYes, //默认初始化值
		Abbreviation: data.Company.Abbreviation,
		Applets:      applets,
	}

	err = companyRespository.Add(&comany)
	if err != nil {
		return fmt.Errorf("添加公司数据失败,%s", err)
	}
	user := domain.Users{
		Id:             data.User.Id,
		CompanyId:      data.User.CompanyId,
		OpenId:         data.User.OpenId,
		Name:           data.User.Name,
		Sex:            data.User.Sex,
		JobNum:         data.User.JobNum,
		Phone:          data.User.Phone,
		PrivatePhone:   data.User.PrivatePhone,
		Email:          data.User.Email,
		ExtensionNum:   data.User.ExtensionNum,
		Workspace:      data.User.WorkSpace,
		Status:         data.User.Status,
		Avatar:         data.User.Avatar,
		Remarks:        data.User.Remarks,
		ChargeStatus:   data.User.ChargeStatus,
		Permission:     []domain.AdminPermissionBase{}, //初始化权限
		AccessPartners: []domain.Partner{},
		AdminType:      data.User.AdminType,
	}
	err = userRespository.Add(&user)
	if err != nil {
		return fmt.Errorf("添加用户数据失败,%s", err)
	}
	err = transactionContext.CommitTransaction()
	return nil
}

//updateCompany 更新公司数据
func (service SyncCompanyService) updateCompany(data CompanytData) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var (
		companyRespository domain.CompanyRepository
		userRespository    domain.UsersRepository
		oldCompany         domain.Company
		oldCompanyAdmins   []domain.Users
		newUser            domain.Users
	)
	if companyRespository, err = factory.CreateCompanyRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if userRespository, err = factory.CreateUsersRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	oldCompany, err = companyRespository.FindOne(domain.CompanyFindOneOptions{
		Id: data.Company.Id,
	})
	_, oldCompanyAdmins, err = userRespository.Find(domain.UsersFindQuery{
		CompanyId: data.Company.Id,
		AdminType: domain.UserIsAdmin,
	})
	newUser, err = userRespository.FindOne(domain.UsersFindOneQuery{
		Id: data.User.Id,
	})
	applets := []domain.CompanyApplets{}
	for _, v := range data.Company.Applets {
		app := domain.CompanyApplets{
			Name: v.Name,
			URL:  v.URL,
			Id:   v.Id,
		}
		applets = append(applets, app)
	}
	oldCompany.Update(map[string]interface{}{
		"Name":           data.Company.Name,
		"Logo":           data.Company.Logo,
		"Remarks":        data.Company.Remarks,
		"AdminCompanyId": data.Company.AdminCompanyId,
		"Abbreviation":   data.Company.Abbreviation,
		"Applets":        applets,
	})
	for i := range oldCompanyAdmins {
		oldCompanyAdmins[i].Update(map[string]interface{}{
			"AdminType": domain.UserIsNotAdmin,
		})
		err = userRespository.Edit(&oldCompanyAdmins[i])
		if err != nil {
			e := fmt.Sprintf("更新公司主管user数据(id=%d)失败:%s",
				oldCompanyAdmins[i].Id, err)
			return lib.ThrowError(lib.BUSINESS_ERROR, e)
		}
	}
	err = companyRespository.Edit(&oldCompany)
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	var entryTime time.Time
	if len(data.User.EntryTime) > 0 {
		entryTime, err = time.Parse("2006-01-02", data.User.EntryTime)
		if err != nil {
			logs.Error("Parse User.EntryTime 错误:%s", err)
		}
	}
	newUser.Update(map[string]interface{}{
		"CompanyId":    data.User.CompanyId,
		"OpenId":       data.User.OpenId,
		"Name":         data.User.Name,
		"Sex":          data.User.Sex,
		"JobNum":       data.User.JobNum,
		"Phone":        data.User.Phone,
		"PrivatePhone": data.User.PrivatePhone,
		"Email":        data.User.Email,
		"ExtensionNum": data.User.ExtensionNum,
		"Workspace":    data.User.WorkSpace,
		"Status":       data.User.Status,
		"Avatar":       data.User.Avatar,
		"Remarks":      data.User.Remarks,
		"ChargeStatus": data.User.ChargeStatus,
		"EntryTime":    entryTime,
		"AdminType":    data.User.AdminType,
	})
	err = userRespository.Edit(&newUser)
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	err = transactionContext.CommitTransaction()
	return nil
}

//updateCompanyCharge 变更公司的负责人
func (service SyncCompanyService) updateCompanyCharge(data CompanyCharge) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var (
		userRespository domain.UsersRepository
	)
	if userRespository, err = factory.CreateUsersRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	var oldUsers []domain.Users
	_, oldUsers, err = userRespository.Find(domain.UsersFindQuery{
		CompanyId:    data.Id,
		ChargeStatus: domain.UserIsCompanyCharge,
		Limit:        -1,
	})
	for i := range oldUsers {
		_ = oldUsers[i].Update(map[string]interface{}{
			"ChargeStatus": domain.UserIsNotCompanyCharge,
		})
		err = userRespository.Edit(&oldUsers[i])
		if err != nil {
			return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, "更新用户的charge_status失败:"+err.Error())
		}
	}
	for _, v := range data.Charge {
		var userToUpdate domain.Users
		userToUpdate, err := userRespository.FindOne(domain.UsersFindOneQuery{
			Id: v,
		})
		if err != nil {
			return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("获取用户(id=%d)的数据失败:%s", v, err.Error()))
		}
		_ = userToUpdate.Update(map[string]interface{}{
			"ChargeStatus": domain.UserIsCompanyCharge,
		})
		err = userRespository.Edit(&userToUpdate)
		if err != nil {
			return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, fmt.Sprintf("更新用户(id=%d)的数据失败:%s", v, err.Error()))
		}
	}
	err = transactionContext.CommitTransaction()
	return nil
}