-
Notifications
You must be signed in to change notification settings - Fork 59
/
docevent.go
331 lines (283 loc) · 9.12 KB
/
docevent.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// (c) Copyright 2015-2017 JONNALAGADDA Srinivas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package flow
import (
"database/sql"
"errors"
"fmt"
"math"
"strings"
"time"
)
// EventStatus enumerates the query parameter values for filtering by
// event state.
type EventStatus uint8
const (
// EventStatusAll does not filter events.
EventStatusAll EventStatus = iota
// EventStatusApplied selects only those events that have been successfully applied.
EventStatusApplied
// EventStatusPending selects only those events that are pending application.
EventStatusPending
)
// DocEventID is the type of unique document event identifiers.
type DocEventID int64
// DocEvent represents a user action performed on a document in the
// system.
//
// Together with documents and nodes, events are central to the
// workflow engine in `flow`. Events cause documents to transition
// from one state to another, usually in response to user actions. It
// is possible for system events to cause state transitions, as well.
type DocEvent struct {
ID DocEventID `json:"ID"` // Unique ID of this event
DocType DocTypeID `json:"DocType"` // Document type of the document to which this event is to be applied
DocID DocumentID `json:"DocID"` // Document to which this event is to be applied
State DocStateID `json:"DocState"` // Current state of the document must equal this
Action DocActionID `json:"DocAction"` // Action performed by the user
Group GroupID `json:"Group"` // Group (singleton) who caused this action
Text string `json:"Text"` // Comment or other content
Ctime time.Time `json:"Ctime"` // Time at which the event occurred
Status EventStatus `json:"Status"` // Status of this event
}
// StatusInDB answers the status of this event.
func (e *DocEvent) StatusInDB() (EventStatus, error) {
var dstatus string
row := db.QueryRow("SELECT status FROM wf_docevents WHERE id = ?", e.ID)
err := row.Scan(&dstatus)
if err != nil {
return 0, err
}
switch dstatus {
case "A":
e.Status = EventStatusApplied
case "P":
e.Status = EventStatusPending
default:
return 0, fmt.Errorf("unknown event status : %s", dstatus)
}
return e.Status, nil
}
// Unexported type, only for convenience methods.
type _DocEvents struct{}
// DocEvents exposes a resource-like interface to document events.
var DocEvents _DocEvents
// DocEventsNewInput holds information needed to create a new document
// event in the system.
type DocEventsNewInput struct {
DocTypeID // Type of the document; required
DocumentID // Unique identifier of the document; required
DocStateID // Document must be in this state for this event to be applied; required
DocActionID // Action performed by `Group`; required
GroupID // Group (user) who performed the action that raised this event; required
Text string // Any comments or notes; required
}
// New creates and initialises an event that transforms the document
// that it refers to.
func (_DocEvents) New(otx *sql.Tx, input *DocEventsNewInput) (DocEventID, error) {
if input.DocTypeID <= 0 || input.DocumentID <= 0 || input.DocStateID <= 0 || input.DocActionID <= 0 || input.GroupID <= 0 {
return 0, errors.New("all identifiers should be positive integers")
}
if input.Text == "" {
return 0, errors.New("please add comments or notes")
}
var tx *sql.Tx
var err error
if otx == nil {
tx, err = db.Begin()
if err != nil {
return 0, err
}
defer tx.Rollback()
} else {
tx = otx
}
// Workflow is tracked at the level of root documents.
doc, err := Documents.Get(tx, input.DocTypeID, input.DocumentID)
if err != nil {
return 0, err
}
rdtid, rdid, err := doc.Path.Root()
if err != nil {
return 0, err
}
if rdid > 0 { // A different document is the root.
input.DocTypeID = rdtid
input.DocumentID = rdid
}
// Register the event using the root document.
q := `
INSERT INTO wf_docevents(doctype_id, doc_id, docstate_id, docaction_id, group_id, data, ctime, status)
VALUES(?, ?, ?, ?, ?, ?, NOW(), 'P')
`
res, err := tx.Exec(q, input.DocTypeID, input.DocumentID, input.DocStateID, input.DocActionID, input.GroupID, input.Text)
if err != nil {
return 0, err
}
var id int64
id, err = res.LastInsertId()
if err != nil {
return 0, err
}
if otx == nil {
err = tx.Commit()
if err != nil {
return 0, err
}
}
return DocEventID(id), nil
}
// DocEventsListInput specifies a set of filter conditions to narrow
// down document listings.
type DocEventsListInput struct {
DocTypeID // Events on documents of this type are listed
AccessContextID // Access context from within which to list
GroupID // List events created by this (singleton) group
DocStateID // List events acting on this state
CtimeStarting time.Time // List events created after this time
CtimeBefore time.Time // List events created before this time
Status EventStatus // List events that are in this state of application
}
// List answers a subset of document events, based on the input
// specification.
//
// `status` should be one of `all`, `applied` and `pending`.
//
// Result set begins with ID >= `offset`, and has not more than
// `limit` elements. A value of `0` for `offset` fetches from the
// beginning, while a value of `0` for `limit` fetches until the end.
func (_DocEvents) List(input *DocEventsListInput, offset, limit int64) ([]*DocEvent, error) {
if offset < 0 || limit < 0 {
return nil, errors.New("offset and limit must be non-negative integers")
}
if limit == 0 {
limit = math.MaxInt64
}
// Base query.
q := `
SELECT de.id, de.doctype_id, de.doc_id, de.docstate_id, de.docaction_id, de.group_id, de.data, de.ctime, de.status
FROM wf_docevents de
`
// Process input specification.
where := []string{}
args := []interface{}{}
if input.DocTypeID > 0 {
where = append(where, `de.doctype_id = ?`)
args = append(args, input.DocTypeID)
}
if input.AccessContextID > 0 {
tbl := DocTypes.docStorName(input.DocTypeID)
q += `JOIN ` + tbl + ` docs ON docs.id = de.doc_id
`
where = append(where, `docs.ac_id = ?`)
args = append(args, input.AccessContextID)
}
switch input.Status {
case EventStatusAll:
// Intentionally left blank
case EventStatusApplied:
where = append(where, `status = 'A'`)
case EventStatusPending:
where = append(where, `status = 'P'`)
default:
return nil, fmt.Errorf("unknown event status specified in filter : %d", input.Status)
}
if input.GroupID > 0 {
where = append(where, `de.group_id = ?`)
args = append(args, input.GroupID)
}
if input.DocStateID > 0 {
where = append(where, `de.docstate_id = ?`)
args = append(args, input.DocStateID)
}
if !input.CtimeStarting.IsZero() {
where = append(where, `de.ctime >= ?`)
args = append(args, input.CtimeStarting)
}
if !input.CtimeBefore.IsZero() {
where = append(where, `de.ctime < ?`)
args = append(args, input.CtimeBefore)
}
if len(where) > 0 {
q += ` WHERE ` + strings.Join(where, ` AND `)
}
q += `
ORDER BY de.id
LIMIT ? OFFSET ?
`
args = append(args, limit, offset)
rows, err := db.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var text sql.NullString
var dstatus string
ary := make([]*DocEvent, 0, 10)
for rows.Next() {
var elem DocEvent
err = rows.Scan(&elem.ID, &elem.DocType, &elem.DocID, &elem.State, &elem.Action, &elem.Group, &text, &elem.Ctime, &dstatus)
if err != nil {
return nil, err
}
if text.Valid {
elem.Text = text.String
}
switch dstatus {
case "A":
elem.Status = EventStatusApplied
case "P":
elem.Status = EventStatusPending
default:
return nil, fmt.Errorf("unknown event status : %s", dstatus)
}
ary = append(ary, &elem)
}
if err = rows.Err(); err != nil {
return nil, err
}
return ary, nil
}
// Get retrieves a document event from the database, using the given
// event ID.
func (_DocEvents) Get(eid DocEventID) (*DocEvent, error) {
if eid <= 0 {
return nil, errors.New("event ID should be a positive integer")
}
var text sql.NullString
var dstatus string
var elem DocEvent
q := `
SELECT id, doctype_id, doc_id, docstate_id, docaction_id, group_id, data, ctime, status
FROM wf_docevents
WHERE id = ?
`
row := db.QueryRow(q, eid)
err := row.Scan(&elem.ID, &elem.DocType, &elem.DocID, &elem.State, &elem.Action, &elem.Group, &text, &elem.Ctime, &dstatus)
if err != nil {
return nil, err
}
if text.Valid {
elem.Text = text.String
}
switch dstatus {
case "A":
elem.Status = EventStatusApplied
case "P":
elem.Status = EventStatusPending
default:
return nil, fmt.Errorf("unknown event status : %s", dstatus)
}
return &elem, nil
}