func createPublishEvent(db *gorm.DB, value interface{}) (err error) { // Create Publish Event in Draft Mode if publish.IsDraftMode(db) && publish.IsPublishableModel(value) { scope := db.NewScope(value) var sortingPublishEvent = changedSortingPublishEvent{ Table: scope.TableName(), } for _, field := range scope.PrimaryFields() { sortingPublishEvent.PrimaryKeys = append(sortingPublishEvent.PrimaryKeys, field.DBName) } var result []byte if result, err = json.Marshal(sortingPublishEvent); err == nil { err = db.New().Where("publish_status = ?", publish.DIRTY).Where(map[string]interface{}{ "name": "changed_sorting", "argument": string(result), }).Attrs(map[string]interface{}{ "publish_status": publish.DIRTY, "description": "Changed sort order for " + scope.GetModelStruct().ModelType.Name(), }).FirstOrCreate(&publish.PublishEvent{}).Error } } return }
func (sm *StateMachine) Trigger(name string, value Stater, tx *gorm.DB, notes ...string) error { stateWas := value.GetState() if stateWas == "" { stateWas = sm.initialState } newTx := tx.New() if event := sm.events[name]; event != nil { var matchedTransitions []*EventTransition for _, transition := range event.transitions { var validFrom = len(transition.froms) == 0 if len(transition.froms) > 0 { for _, from := range transition.froms { if from == stateWas { validFrom = true } } } if validFrom { matchedTransitions = append(matchedTransitions, transition) } } if len(matchedTransitions) == 1 { transition := matchedTransitions[0] // State: exit if state, ok := sm.states[stateWas]; ok { for _, exit := range state.exits { if err := exit(value, newTx); err != nil { return err } } } // Transition: before for _, before := range transition.befores { if err := before(value, newTx); err != nil { return err } } value.SetState(transition.to) // State: enter if state, ok := sm.states[transition.to]; ok { for _, enter := range state.enters { if err := enter(value, newTx); err != nil { return err } } } // Transition: after for _, after := range transition.afters { if err := after(value, newTx); err != nil { return err } } scope := newTx.NewScope(value) primaryKey := fmt.Sprintf("%v", scope.PrimaryKeyValue()) log := StateChangeLog{ ReferTable: scope.TableName(), ReferId: primaryKey, From: stateWas, To: transition.to, Note: strings.Join(notes, ""), } return newTx.Save(&log).Error } } return fmt.Errorf("failed to perform event %s from state %s", name, stateWas) }