package repositories import ( "context" "errors" "gorm.io/gorm" "sorbet/internal/entities" "sorbet/pkg/db" "sorbet/pkg/ticket" ) type CompanyAuthTicketRepository struct { *db.Repository[entities.CompanyAuthTicket] } // NewCompanyAuthTicketRepository 创建公司部门仓库 func NewCompanyAuthTicketRepository(orm *gorm.DB) *CompanyAuthTicketRepository { return &CompanyAuthTicketRepository{ db.NewRepositoryWith[entities.CompanyAuthTicket](orm, "id"), } } // TicketForLastLogin 最后一次登录生成的 ticket 信息 func (r *CompanyAuthTicketRepository) TicketForLastLogin(ctx context.Context, openid string) (*entities.CompanyAuthTicket, error) { var authTicket entities.CompanyAuthTicket res := r.DB(ctx). Model(&authTicket). Where("wechat_openid=?", openid). Order("updated_at DESC"). Preload("Employee", func(tx *gorm.DB) *gorm.DB { //return tx. // Preload("Company"). // 当前员工所在公司 // Preload("Departments", func(tx *gorm.DB) *gorm.DB { // // 只查询当前公司的部门 // return tx.Where("company_id = ?") // }) // 当前员工所在部门 return tx.Preload("Company") }). Last(&authTicket) if err := res.Error; err != nil { return nil, err } return &authTicket, nil } // EmployeeForLastLogin 使用微信最后一次登录的员工信息 func (r *CompanyAuthTicketRepository) EmployeeForLastLogin(ctx context.Context, openid string) (*entities.CompanyEmployee, error) { authTicket, err := r.TicketForLastLogin(ctx, openid) if err != nil { return nil, err } return authTicket.Employee, nil } func (r *CompanyAuthTicketRepository) GenerateForWechat(ctx context.Context, openid string) (employee *entities.CompanyEmployee, ticketString string, err error) { employee, err = r.EmployeeForLastLogin(ctx, openid) if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { return } // 通过最后一个 ticket 生成新的 if employee == nil { // 随机取一个员工信息 var temp entities.CompanyEmployee res := r.DB(ctx). Where("wechat_openid=?", openid). Preload("Departments"). Preload("Company"). Order("updated_at"). First(&temp) if err = res.Error; err != nil { return } employee = &temp } ticketString, err = ticket.Create(&ticket.Claims{ UID: employee.ID, Role: "company:employee", }) authTicket := &entities.CompanyAuthTicket{ CompanyID: employee.CompanyID, EmployeeID: employee.ID, WechatOpenid: employee.WechatOpenid, Ticket: ticketString, } err = r.Create(ctx, authTicket) return }