company.go 8.0 KB
package service

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

	"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 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"`          //备注
	Status         int8   `json:"status"`
}

// 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")
	}
}

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())
	}
	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.CompanyEnableNo, //默认初始化值
	}
	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{},             //默认初始化
	}
	err = userRespository.Add(&user)
	if err != nil {
		return fmt.Errorf("添加用户数据失败,%s", err)
	}
	err = transactionContext.CommitTransaction()
	return nil
}

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
		oldUser            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,
	})
	oldUser, err = userRespository.FindOne(domain.UsersFindOneQuery{
		Id: data.User.Id,
	})
	oldCompany.Update(map[string]interface{}{
		"Name":           data.Company.Name,
		"Logo":           data.Company.Logo,
		"Remarks":        data.Company.Remarks,
		"AdminCompanyId": data.Company.AdminCompanyId,
		"Status":         data.User.Status,
	})
	entryTime, _ := time.Parse("2006-01-02", data.User.EntryTime)
	oldUser.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,
	})
	err = companyRespository.Edit(&oldCompany)
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	err = userRespository.Edit(&oldUser)
	if err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	err = transactionContext.CommitTransaction()
	return nil
}

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{}{
			"charge_status": 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{}{
			"charge_status": 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
}