models

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 19, 2020 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ErrNotFound is returned when a resource cannot be found
	// in the database.
	ErrNotFound modelError = "models: resource not found"

	// ErrIDInvalid is returned when an invalid ID is provided
	// to a method like Delete.
	ErrIDInvalid modelError = "models: ID provided was invalid"

	// ErrPasswordIncorrect is returned when an incorrect
	// password is used when authenticating a user.
	ErrPasswordIncorrect modelError = "models: incorrect password provided"

	// ErrLoginIncorrect is returned when an incorrect
	// password is used when authenticating a user.
	ErrLoginIncorrect modelError = "models: incorrect login provided"

	// ErrEmailRequired is returned when an email address is
	// not provided when creating a user
	ErrEmailRequired modelError = "models: email address is required"

	// ErrEmailInvalid is returned when an email address provided
	// does not match any of our requirements
	ErrEmailInvalid modelError = "models: email address is not valid"

	// ErrEmailTaken is returned when an update or create is attempted
	// with an email address that is already in use.
	ErrEmailTaken modelError = "models: email address is already taken"

	// ErrPasswordTooShort is returned when a user tries to set
	// a password that is less than 8 characters long.
	ErrPasswordTooShort modelError = "models: password must be at least 8 characters long"

	// ErrPasswordRequired is returned when a create or login is attempted
	// without a user password provided.
	ErrPasswordRequired modelError = "models: password is required"

	// ErrLoginRequired is returned when a create or login is attempted
	// without a user login provided.
	ErrLoginRequired modelError = "models: login is required"

	// ErrRememberRequired is returned when a create or update
	// is attempted without a user remember token hash
	ErrRememberRequired modelError = "models: remember token is required"

	// ErrRememberTooShort is returned when a remember token is
	// not at least 32 bytes
	ErrRememberTooShort modelError = "models: remember token must be at least 32 bytes"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cathedra

type Cathedra struct {
	gorm.Model
	Name        string       `gorm:"unique_index"`
	Disciplines []Discipline `gorm:"foreignkey:Cathedra;association_foreignkey:Name"`
	Teachers    []*Teacher   `gorm:"many2many:cathedras_teachers"`
}

Кафедра не сделана просто полем у какой-нибудь структуры по той же причине, что и Number

type Discipline

type Discipline struct {
	gorm.Model
	Name     string
	Cathedra string
	Teachers []*Teacher `gorm:"many2many:disciplines_teachers"`
	Skips    []Skip
	Scores   []Score
	Groups   []*Group `gorm:"many2many:disciplines_groups"`
}

type FilterScoresQueryParams

type FilterScoresQueryParams struct {
	GroupID  *uint   `schema:"group_id"`
	Year     *int    `schema:"year"`
	Semester *string `schema:"semester"`
}

Указатели используются потому, что иначе будет инициализация 0-ми значениями

type FilterSkipsQueryParams

type FilterSkipsQueryParams struct {
	GroupID  *uint   `schema:"group_id"`
	Year     *int    `schema:"year"`
	Semester *string `schema:"semester"`
}

type Group

type Group struct {
	gorm.Model
	Name     string     `gorm:"not null;unique_index"`
	Students []*Student `gorm:"many2many:students_groups"` //`gorm:"many2many:students_groups;foreignkey:Name;association_foreignkey:ID"`
	Status   string     `sql:"type:group_status"`
	//Status bool // пока оставлю логический тип, дабы избавиться от if-ов лучше использовать enum тип, если есть [возможность]
	Year               uint          // год начала обучения
	EducationPeriod    int           // период обучения, например, 4
	Numbers            []Number      `gorm:"foreignkey:Group;association_foreignkey:Name"`
	EducationForm      string        `sql:"type:education_form"`
	EducationLevel     string        `sql:"type:education_level"`
	Institute          string        `sql:"type:institute"`
	Teachers           []*Teacher    `gorm:"many2many:groups_teachers"`
	Disciplines        []*Discipline `gorm:"many2many:disciplines_groups"`
	Starosta           Student
	Schedules          []Schedule
	GroupSemesterInfos []GroupSemesterInfo
}

type GroupDB

type GroupDB interface {
	ByUserStatuses(user *User) ([]StarostaGroupStatuses, error)
	Update(group *Group) error
}

type GroupSemesterInfo

type GroupSemesterInfo struct {
	gorm.Model
	Semester           string `sql:"type:semester"`
	Year               uint   // год начала обучения
	GroupID            uint
	EducationStartDate time.Time
	EducationEndDate   time.Time
	DisciplinesIDs     pq.Int64Array `gorm:"type:integer[]"`
}

type GroupService

type GroupService interface {
	GroupDB
}

func NewGroupService

func NewGroupService(db *gorm.DB) GroupService

type Number

type Number struct {
	gorm.Model
	Number    uint `sql:"unique"`
	StudentID uint
	Group     string
}

Номер зачетки Отдельная табилца нужна потому, чтоб понимать, к какой группе относится зачетка, а не просто поле типа "массив" у студента с номерами зачеток

type Schedule

type Schedule struct {
	gorm.Model
	Day time.Weekday
	//Disciplines []Discipline // не сейвит
	DisciplinesIDs pq.Int64Array `gorm:"type:integer[]"`
	Semester       string        `sql:"type:semester"`
	Year           uint          // год начала обучения
	GroupID        uint
	IsEvenWeek     bool
}

type Score

type Score struct {
	gorm.Model
	// todo лучше поменять uint на int
	Year                    uint   // год начала обучения, e.g. если учебный год 2016 - 2017, то Year = 2016
	AttestationOne          string `sql:"type:score_value"`
	AttestationTwo          string `sql:"type:score_value"`
	AttestationThree        string `sql:"type:score_value"`
	IntermediateAttestation string `sql:"type:score_value"`
	Semester                string `sql:"type:semester"`
	StudentID               uint
	DisciplineID            uint
}

todo rename to "Grade"

type ScoreDB

type ScoreDB interface {
	LastUpdated() (string, error)
	ByUser(user *User, GETParams interface{}) (*ScoresResult, []string, error)
	ByUserFilterData(user *User, GETParams *FilterScoresQueryParams) (*ScoresResult, error)
	Update(score *Score) error
	ReportByUser(user *User, GETParams *ScoresStarostaQueryParams) (*excelize.File, error)
}

type ScoreService

type ScoreService interface {
	ScoreDB
}

func NewScoreService

func NewScoreService(db *gorm.DB) ScoreService

type ScoresResult

type ScoresResult struct {
	StudentScoresResult
	StarostaScoresResult
}

Структура нужна, дабы не менять всякий раз сигнатуру методу

type ScoresStarostaQueryParams

type ScoresStarostaQueryParams struct {
	GroupID      *uint   `schema:"group_id"`
	Year         *uint   `schema:"year"`
	Semester     *string `schema:"semester"`
	DisciplineID *uint   `schema:"discipline_id"`
}

type ScoresStudentQueryParams

type ScoresStudentQueryParams struct {
	GroupID        *uint   `schema:"group_id"`
	Year           *uint   `schema:"year"`
	Semester       *string `schema:"semester"`
	DisciplinesIDs []uint  `schema:"disciplines_ids"`
}

type SelectOptionData

type SelectOptionData struct {
	Value      interface{}
	Text       string
	IsSelected bool
}

type Services

type Services struct {
	User UserService

	Score ScoreService
	Group GroupService
	Skip  SkipService
	// contains filtered or unexported fields
}

func NewServices

func NewServices(cfgs ...ServicesConfig) (*Services, error)

NewServices now will accept a list of config functions to run. Each function will accept a pointer to the current Services object as its only argument and will edit that object inline and return an error if there is one. Once we have run all configs we will return the Services object.

func (*Services) AutoMigrate

func (s *Services) AutoMigrate() error

AutoMigrate will attempt to automatically migrate all tables todo по мере реализации моделей ресурсов, нуно добавлять их в AutoMigrate ниже

func (*Services) Close

func (s *Services) Close() error

Closes the database connection

func (*Services) DestructiveReset

func (s *Services) DestructiveReset() error

DestructiveReset drops all tables and rebuilds them todo по мере реализации моделей ресурсов, нуно добавлять их в DestructiveReset ниже

type ServicesConfig

type ServicesConfig func(*Services) error

ServicesConfig is really just a function, but I find using types like this are easier to read in my source code.

func WithGorm

func WithGorm(dialect, connectionInfo string) ServicesConfig

func WithGroup

func WithGroup() ServicesConfig

func WithLogMode

func WithLogMode(mode bool) ServicesConfig

func WithScore

func WithScore() ServicesConfig

func WithSkip

func WithSkip() ServicesConfig

func WithTesting

func WithTesting() ServicesConfig

func WithUser

func WithUser(pepper, hmacKey string) ServicesConfig

type Skip

type Skip struct {
	gorm.Model          // дата содержится в Created_at - отменено использование этого поля в кач-ве даты, выделено отдельное
	Reason       string `sql:"type:reason"`
	DisciplineID uint
	StudentID    uint
	Date         time.Time // нужна потому, что в методе skipsC.Show отсутсвующие пропуски за конкретную дату создаются на ходу
	LessonNumber int
}

type SkipDB

type SkipDB interface {
	ByUser(user *User, GETParams interface{}) (*SkipsResult, []string, error)
	Update(skip *Skip) error
	Edit(user *User, GETParams *SkipsEditStarostaQueryParams) (*StarostaSkipsEditResult, error)
	ByUserFilterData(user *User, GETParams interface{}) (interface{}, error)
	ByUserEditFilterData(user *User, GETParams *SkipsEditStarostaQueryParams) (*StarostaSkipsEditResult, error)
}

type SkipRow

type SkipRow struct {
	SkipDate   string
	SkipReason string
}

type SkipService

type SkipService interface {
	SkipDB
}

func NewSkipService

func NewSkipService(db *gorm.DB) SkipService

type SkipsEditStarostaQueryParams

type SkipsEditStarostaQueryParams struct {
	GroupID        *uint   `schema:"group_id"`
	Date           *string `schema:"date"`
	DisciplineInfo *string `schema:"discipline_info"`
}

type SkipsResult

type SkipsResult struct {
	StudentSkipsResult
	StarostaSkipsResult
}

type SkipsStarostaQueryParams

type SkipsStarostaQueryParams struct {
	GroupID   *uint   `schema:"group_id"`
	Year      *uint   `schema:"year"`
	Semester  *string `schema:"semester"`
	StudentID *uint   `schema:"student_id"`
}

type SkipsStudentQueryParams

type SkipsStudentQueryParams struct {
	GroupID  *uint   `schema:"group_id"`
	Year     *uint   `schema:"year"`
	Semester *string `schema:"semester"`
}

type StarostaGroupStatuses

type StarostaGroupStatuses struct {
	GroupName string
	GroupID   uint
	IsActual  bool
}

type StarostaScoresFilterData

type StarostaScoresFilterData struct {
	Groups      []SelectOptionData
	Years       []SelectOptionData
	Semesters   []SelectOptionData
	Disciplines []SelectOptionData
}

type StarostaScoresResult

type StarostaScoresResult struct {
	StarostaScoresFilterData
	StarostaScoresResultData
}

type StarostaScoresResultData

type StarostaScoresResultData struct {
	Result StarostaScoresRows
}

type StarostaScoresRows

type StarostaScoresRows struct {
	DisciplineID uint   //исп-ся в методе ReportByStarosta - больше так не делать, отдельную структуру на каждый метод
	Discipline   string //исп-ся в методе ReportByStarosta
	Teacher      string
	Cathedra     string
	StudentsInfo []StarostaScoresStudentInfo
}

type StarostaScoresStudentInfo

type StarostaScoresStudentInfo struct {
	ScoreID         uint
	StudentName     string
	AttOne          string
	AttTwo          string
	AttThree        string
	AttIntermediate string
	Skips           string
}

type StarostaSkipsEditFilterData

type StarostaSkipsEditFilterData struct {
	Groups      []SelectOptionData
	Date        string
	Disciplines []SelectOptionData
}

type StarostaSkipsEditResultData

type StarostaSkipsEditResultData struct {
	Rows []StarostaSkipsEditRow
}

type StarostaSkipsEditRow

type StarostaSkipsEditRow struct {
	StudentName string
	SkipID      uint
	SkipReason  string
}

type StarostaSkipsFilterData

type StarostaSkipsFilterData struct {
	Groups    []SelectOptionData
	Years     []SelectOptionData
	Semesters []SelectOptionData
	Students  []SelectOptionData
}

type StarostaSkipsResult

type StarostaSkipsResult struct {
	StarostaSkipsFilterData
	StarostaSkipsResultData
}

type StarostaSkipsResultData

type StarostaSkipsResultData struct {
	Rows []StarostaSkipsRow
}

type StarostaSkipsRow

type StarostaSkipsRow struct {
	DisciplineName string
	Skips          []SkipRow
	NumberOfUHours float32
	NumberOfNHours float32
	TotalHours     float32
}

type Student

type Student struct {
	gorm.Model
	FirstName  string
	MiddleName string // отчество
	LastName   string
	Numbers    []Number // Номера зачеток, без тегов возможно не будет подгружаться
	Users      []*User  `gorm:"many2many:users_students"`
	Groups     []*Group `gorm:"many2many:students_groups"`
	Scores     []Score
	Skips      []Skip
	GroupID    uint
}

type StudentScoresFilterData

type StudentScoresFilterData struct {
	Groups      []SelectOptionData
	Years       []SelectOptionData
	Semesters   []SelectOptionData
	Disciplines []SelectOptionData
	Teachers    []SelectOptionData
}

type StudentScoresResult

type StudentScoresResult struct {
	StudentScoresFilterData
	StudentScoresResultData
}

Просто назвать её Result и поля filterData и resultdata, а в структуре выше сделать поле Student с типом Result

type StudentScoresResultData

type StudentScoresResultData struct {
	Result []StudentScoresRows
}

type StudentScoresRows

type StudentScoresRows struct {
	DisciplineName  string
	TeacherName     string
	Cathedra        string
	AttOne          string
	AttTwo          string
	AttThree        string
	AttIntermediate string
	Skips           string
}

type StudentSkipsFilterData

type StudentSkipsFilterData struct {
	Groups    []SelectOptionData
	Years     []SelectOptionData
	Semesters []SelectOptionData
}

type StudentSkipsResult

type StudentSkipsResult struct {
	StudentSkipsFilterData
	StudentSkipsResultData
}

type StudentSkipsResultData

type StudentSkipsResultData struct {
	Rows []StudentSkipsRow
}

type StudentSkipsRow

type StudentSkipsRow struct {
	DisciplineName string
	Skips          []SkipRow
	NumberOfUHours float32
	NumberOfNHours float32
	TotalHours     float32
}

type Teacher

type Teacher struct {
	gorm.Model
	FirstName   string
	MiddleName  string // отчество
	LastName    string
	Disciplines []*Discipline `gorm:"many2many:disciplines_teachers"`
	Cathedras   []*Cathedra   `gorm:"many2many:cathedras_teachers"`
	Groups      []*Group      `gorm:"many2many:groups_teachers"`
}

Преподаватель

type User

type User struct {
	gorm.Model
	FirstName    string
	MiddleName   string // отчество
	LastName     string
	Email        string     //`gorm:"not null;unique_index"`
	Password     string     `gorm:"-"`
	PasswordHash string     `gorm:"not null"`
	Remember     string     `gorm:"-"`
	RememberHash string     `gorm:"not null;unique_index"`
	Login        string     `gorm:"not null;unique_index"`
	Class        string     `sql:"type:class"`
	Students     []*Student `gorm:"many2many:users_students"`
}

type UserDB

type UserDB interface {
	// Methods for querying for single users
	ByID(id uint) (*User, error)
	ByEmail(email string) (*User, error)
	ByRemember(token string) (*User, error)
	ByLogin(login string) (*User, error)
	// Methods for altering users
	Create(user *User) error
	Update(user *User) error
	Delete(id uint) error
	//
	Authenticate(login, password string) (*User, error)
}

UserDB is used to interact with the users database.

For pretty much all single user queries: If the user is found, we will return a nil error If the user is not found, we will return ErrNotFound If there is another error, we will return an error with more information about what went wrong. This may not be an error generated by the models package.

For single user queries, any error but ErrNotFound should probably result in a 500 error until we make "public" facing errors.

type UserService

type UserService interface {
	// Authenticate will verify the provided email address and
	// password are correct. If they are correct, the user
	// corresponding to that email will be returned. Otherwise
	// You will receive either:
	// ErrNotFound, ErrPasswordIncorrect, or another error if
	// something goes wrong.
	UserDB
}

UserService is a set of methods used to manipulate and work with the user model

func NewUserService

func NewUserService(db *gorm.DB, pepper, hmacKey string) UserService

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL