-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathdoctype.go
411 lines (365 loc) · 9.71 KB
/
doctype.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// (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"
)
// DocTypeID is the type of unique identifiers of document types.
type DocTypeID int64
// DocType enumerates the types of documents in the system, as defined
// by the consuming application. Each document type has an associated
// workflow definition that drives its life cycle.
//
// Accordingly, `flow` does not assume anything about the specifics of
// the any document type. Instead, it treats document types as plain,
// but controlled, vocabulary. Nonetheless, it is highly recommended,
// but not necessary, that document types be defined in a system of
// hierarchical namespaces. For example:
//
// PUR:RFQ
//
// could mean that the department is 'Purchasing', while the document
// type is 'Request For Quotation'. As a variant,
//
// PUR:ORD
//
// could mean that the document type is 'Purchase Order'.
//
// N.B. All document types must be defined as constant strings.
type DocType struct {
ID DocTypeID `json:"ID,omitempty"` // Unique identifier of this document type
Name string `json:"Name,omitempty"` // Unique name of this document type
}
// Unexported type, only for convenience methods.
type _DocTypes struct{}
// DocTypes provides a resource-like interface to document types in
// the system.
var DocTypes _DocTypes
// docStorName answers the appropriate table name for the given
// document type.
func (_DocTypes) docStorName(dtid DocTypeID) string {
return fmt.Sprintf("wf_documents_%03d", dtid)
}
// New creates and registers a new document type in the system.
func (_DocTypes) New(otx *sql.Tx, name string) (DocTypeID, error) {
name = strings.TrimSpace(name)
if name == "" {
return 0, errors.New("name cannot be empty")
}
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
}
res, err := tx.Exec("INSERT INTO wf_doctypes_master(name) VALUES(?)", name)
if err != nil {
return 0, err
}
var id int64
id, err = res.LastInsertId()
if err != nil {
return 0, err
}
tbl := DocTypes.docStorName(DocTypeID(id))
q := `DROP TABLE IF EXISTS ` + tbl
res, err = tx.Exec(q)
if err != nil {
return 0, err
}
q = `
CREATE TABLE ` + tbl + ` (
id INT NOT NULL AUTO_INCREMENT,
path VARCHAR(1000) NOT NULL,
ac_id INT NOT NULL,
docstate_id INT NOT NULL,
group_id INT NOT NULL,
ctime TIMESTAMP NOT NULL,
title VARCHAR(250) NULL,
data TEXT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (ac_id) REFERENCES wf_access_contexts(id),
FOREIGN KEY (docstate_id) REFERENCES wf_docstates_master(id),
FOREIGN KEY (group_id) REFERENCES wf_groups_master(id)
)
`
res, err = tx.Exec(q)
if err != nil {
return 0, err
}
if otx == nil {
err = tx.Commit()
if err != nil {
return 0, err
}
}
return DocTypeID(id), nil
}
// List answers a subset of the document types, based on the input
// specification.
//
// 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 (_DocTypes) List(offset, limit int64) ([]*DocType, error) {
if offset < 0 || limit < 0 {
return nil, errors.New("offset and limit must be non-negative integers")
}
if limit == 0 {
limit = math.MaxInt64
}
q := `
SELECT id, name
FROM wf_doctypes_master
ORDER BY id
LIMIT ? OFFSET ?
`
rows, err := db.Query(q, limit, offset)
if err != nil {
return nil, err
}
defer rows.Close()
ary := make([]*DocType, 0, 10)
for rows.Next() {
var elem DocType
err = rows.Scan(&elem.ID, &elem.Name)
if err != nil {
return nil, err
}
ary = append(ary, &elem)
}
if err = rows.Err(); err != nil {
return nil, err
}
return ary, nil
}
// Get retrieves the document type for the given ID.
func (_DocTypes) Get(id DocTypeID) (*DocType, error) {
if id <= 0 {
return nil, errors.New("ID should be a positive integer")
}
var elem DocType
row := db.QueryRow("SELECT id, name FROM wf_doctypes_master WHERE id = ?", id)
err := row.Scan(&elem.ID, &elem.Name)
if err != nil {
return nil, err
}
return &elem, nil
}
// GetByName answers the document type, if one with the given name is
// registered; `nil` and the error, otherwise.
func (_DocTypes) GetByName(name string) (*DocType, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, errors.New("document type cannot be empty")
}
var elem DocType
row := db.QueryRow("SELECT id, name FROM wf_doctypes_master WHERE name = ?", name)
err := row.Scan(&elem.ID, &elem.Name)
if err != nil {
return nil, err
}
return &elem, nil
}
// Rename renames the given document type.
func (_DocTypes) Rename(otx *sql.Tx, id DocTypeID, name string) error {
name = strings.TrimSpace(name)
if name == "" {
return errors.New("name cannot be empty")
}
var tx *sql.Tx
var err error
if otx == nil {
tx, err = db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
} else {
tx = otx
}
_, err = tx.Exec("UPDATE wf_doctypes_master SET name = ? WHERE id = ?", name, id)
if err != nil {
return err
}
if otx == nil {
err = tx.Commit()
if err != nil {
return err
}
}
return nil
}
// Transition holds the information of which action results in which
// state.
type Transition struct {
Upon DocAction // If user/system has performed this action
To DocState // Document transitions into this state
}
// TransitionMap holds the state transitions defined for this document
// type. It lays out which actions result in which target states,
// given current states.
type TransitionMap struct {
From DocState // When document is in this state
Transitions map[DocActionID]Transition
}
// Transitions answers the possible document states into which a
// document currently in the given state can transition.
func (_DocTypes) Transitions(dtype DocTypeID, from DocStateID) (map[DocStateID]*TransitionMap, error) {
q := `
SELECT dst.from_state_id, dsm1.name, dst.docaction_id, dam.name, dam.reconfirm, dst.to_state_id, dsm2.name
FROM wf_docstate_transitions dst
JOIN wf_docstates_master dsm1 ON dsm1.id = dst.from_state_id
JOIN wf_docstates_master dsm2 ON dsm2.id = dst.to_state_id
JOIN wf_docactions_master dam ON dam.id = dst.docaction_id
WHERE dst.doctype_id = ?
`
var rows *sql.Rows
var err error
if from > 0 {
q += `AND dst.from_state_id = ?
`
rows, err = db.Query(q, dtype, from)
} else {
rows, err = db.Query(q, dtype)
}
if err != nil {
return nil, err
}
defer rows.Close()
res := map[DocStateID]*TransitionMap{}
for rows.Next() {
var dsfrom DocState
var t Transition
err := rows.Scan(&dsfrom.ID, &dsfrom.Name, &t.Upon.ID, &t.Upon.Name, &t.Upon.Reconfirm, &t.To.ID, &t.To.Name)
if err != nil {
return nil, err
}
var elem *TransitionMap
ok := false
if elem, ok = res[dsfrom.ID]; !ok {
elem = &TransitionMap{}
elem.From = dsfrom
elem.Transitions = map[DocActionID]Transition{}
}
elem.Transitions[t.Upon.ID] = t
res[dsfrom.ID] = elem
}
if err = rows.Err(); err != nil {
return nil, err
}
return res, nil
}
// _Transitions answers the possible document states into which a
// document currently in the given state can transition. Only
// identifiers are answered in the map.
func (_DocTypes) _Transitions(dtype DocTypeID, state DocStateID) (map[DocActionID]DocStateID, error) {
q := `
SELECT docaction_id, to_state_id
FROM wf_docstate_transitions
WHERE doctype_id = ?
AND from_state_id = ?
`
rows, err := db.Query(q, dtype, state)
if err != nil {
return nil, err
}
defer rows.Close()
hash := make(map[DocActionID]DocStateID)
for rows.Next() {
var da DocActionID
var ds DocStateID
err := rows.Scan(&da, &ds)
if err != nil {
return nil, err
}
hash[da] = ds
}
if err = rows.Err(); err != nil {
return nil, err
}
return hash, nil
}
// AddTransition associates a target document state with a document
// action performed on documents in the given current state.
func (_DocTypes) AddTransition(otx *sql.Tx, dtype DocTypeID, state DocStateID,
action DocActionID, toState DocStateID) error {
var tx *sql.Tx
var err error
if otx == nil {
tx, err = db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
} else {
tx = otx
}
q := `
INSERT INTO wf_docstate_transitions(doctype_id, from_state_id, docaction_id, to_state_id)
VALUES(?, ?, ?, ?)
`
_, err = tx.Exec(q, dtype, state, action, toState)
if err != nil {
return err
}
if otx == nil {
err = tx.Commit()
if err != nil {
return err
}
}
return nil
}
// RemoveTransition disassociates a target document state with a
// document action performed on documents in the given current state.
func (_DocTypes) RemoveTransition(otx *sql.Tx, dtype DocTypeID, state DocStateID, action DocActionID) error {
var tx *sql.Tx
var err error
if otx == nil {
tx, err = db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
} else {
tx = otx
}
q := `
DELETE FROM wf_docstate_transitions
WHERE doctype_id = ?
AND from_state_id =?
AND docaction_id = ?
`
_, err = tx.Exec(q, dtype, state, action)
if err != nil {
return err
}
if otx == nil {
err = tx.Commit()
if err != nil {
return err
}
}
return nil
}