-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCircularNoticeTargetUser.php
More file actions
443 lines (396 loc) · 12.1 KB
/
CircularNoticeTargetUser.php
File metadata and controls
443 lines (396 loc) · 12.1 KB
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
<?php
/**
* CircularNoticeTargetUser Model
*
* @property User $User
*
* @author Noriko Arai <arai@nii.ac.jp>
* @author Hirohisa Kuwata <Kuwata.Hirohisa@withone.co.jp>
* @link http://www.netcommons.org NetCommons Project
* @license http://www.netcommons.org/license.txt NetCommons License
* @copyright Copyright 2014, NetCommons Project
*/
App::uses('CircularNoticesAppModel', 'CircularNotices.Model');
App::uses('CircularNoticeComponent', 'CircularNotices.Controller/Component');
/**
* CircularNoticeTargetUser Model
*
* @author Hirohisa Kuwata <Kuwata.Hirohisa@withone.co.jp>
* @package NetCommons\CircularNotices\Model
*/
class CircularNoticeTargetUser extends CircularNoticesAppModel {
/**
* Default display number
*
* @var int
*/
const DEFAULT_DISPLAY_NUMBER = 10;
/**
* Validation rules
*
* @var array
*/
public $validate = array();
/**
* Called during validation operations, before validation. Please note that custom
* validation rules can be defined in $validate.
*
* @param array $options Options passed from Model::save().
* @return bool True if validate operation should continue, false to abort
* @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate
* @see Model::save()
*/
public function beforeValidate($options = array()) {
return parent::beforeValidate($options);
}
/**
* Validate empty of reply value.
*
* @param array $check check fields.
* @return bool
*/
public function validateNotEmptyReplyValue($check) {
if (! $this->data['CircularNoticeTargetUser']['reply_text_value'] &&
! $this->data['CircularNoticeTargetUser']['reply_selection_value']
) {
return false;
}
return true;
}
/**
* Use behaviors
*
* @var array
*/
public $actsAs = array(
);
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'User' => array(
'className' => 'Users.User',
'foreignKey' => 'user_id',
'conditions' => ['status' => UserAttributeChoice::STATUS_CODE_ACTIVE],
'type' => 'inner',
'fields' => '',
'order' => ''
),
'CircularNoticeContent' => array(
'className' => 'CircularNotices.CircularNoticeContent',
'foreignKey' => 'circular_notice_content_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
);
/**
* Constructor. Binds the model's database table to the object.
*
* @param bool|int|string|array $id Set this ID for this model on startup,
* can also be an array of options, see above.
* @param string $table Name of database table to use.
* @param string $ds DataSource connection name.
* @see Model::__construct()
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
*/
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields['reply_status'] =
'CASE WHEN ' . $this->alias . '.is_read = 0 THEN ' .
'\'' . CircularNoticeComponent::CIRCULAR_NOTICE_CONTENT_STATUS_UNREAD . '\' ' .
'WHEN ' . $this->alias . '.is_read = 1 THEN ' .
'CASE WHEN ' . $this->alias . '.is_reply = 0 THEN ' .
'\'' . CircularNoticeComponent::CIRCULAR_NOTICE_CONTENT_STATUS_READ_YET . '\' ' .
'WHEN ' . $this->alias . '.is_reply = 1 THEN ' .
'\'' . CircularNoticeComponent::CIRCULAR_NOTICE_CONTENT_STATUS_REPLIED . '\' ' .
'ELSE ' .
'NULL ' .
'END ' .
'ELSE ' .
'NULL ' .
'END';
}
/**
* Validate if the user has been selected.
*
* @param array $userIdArr ユーザID配列
* @return bool
*/
public function isUserSelected($userIdArr) {
if (!isset($userIdArr) || count($userIdArr) === 0) {
return false;
}
return true;
}
/**
* Get count of circular notice target user
*
* @param int $contentId circular_notice_target_users.circular_notice_content_id
* @return array
*/
public function getCircularNoticeTargetUserCount($contentId) {
// 条件を設定
$conditions = array(
'CircularNoticeTargetUser.circular_notice_content_id' => $contentId,
);
// 回覧先件数を取得
$targetCount = $this->find('count', array(
'recursive' => 1,
'conditions' => $conditions,
));
// 閲覧済件数を取得するため条件を追加
$conditions += array(
'CircularNoticeTargetUser.is_read' => true
);
// 閲覧済件数を取得
$readCount = $this->find('count', array(
'recursive' => 1,
'conditions' => $conditions,
));
// 回答済件数を取得するため条件を追加
$conditions += array(
'CircularNoticeTargetUser.is_reply' => true
);
// 回答済件数を取得
$replyCount = $this->find('count', array(
'recursive' => 1,
'conditions' => $conditions,
));
// 配列に詰めて返す
return compact('targetCount', 'readCount', 'replyCount');
}
/**
* Get circular notice target users
*
* @param int $contentId circular_notice_target_users.circular_notice_content_id
* @param array $userIds ユーザID配列
* @return array
*/
public function getCircularNoticeTargetUsers($contentId, $userIds) {
$conditions = array(
'CircularNoticeTargetUser.circular_notice_content_id' => $contentId,
'CircularNoticeTargetUser.user_id' => $userIds,
);
return $this->find('all', array(
'conditions' => $conditions,
));
}
/**
* Get circular notice target user list for pagination
*
* @param int $contentId circular_notice_target_users.circular_notice_content_id
* @param array $paginatorParams paginator params
* @param int $userId user id
* @param int $limit limit
* @return array
*/
public function getCircularNoticeTargetUsersForPaginator($contentId, $paginatorParams, $userId,
$limit = self::DEFAULT_DISPLAY_NUMBER) {
$this->virtualFields['first_order'] =
'CASE WHEN CircularNoticeTargetUser.user_id = ' . $userId . ' THEN 1 ELSE 2 END';
$conditions = array(
'CircularNoticeTargetUser.circular_notice_content_id' => $contentId,
);
// 表示順
$order = array('User.username' => 'asc');
if (isset($paginatorParams['sort']) && isset($paginatorParams['direction'])) {
$order = array($paginatorParams['sort'] => $paginatorParams['direction']);
}
// 表示件数
if (isset($paginatorParams['limit'])) {
$limit = (int)$paginatorParams['limit'];
}
$result = array(
'recursive' => 0,
'conditions' => $conditions,
'order' => $order,
);
if ((int)$limit > 0) {
$result['limit'] = $limit;
}
return $result;
}
/**
* Hook for Paginator's paginate
*
* @param array $conditions conditions
* @param array $fields fields
* @param array $order order
* @param int $limit limit
* @param int $page page
* @param int $recursive recursive
* @param array $extra extra
* @return mixed
*/
public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null,
$extra = array()) {
// ログイン者を先頭に持ってくるためにorderをカスタム
$customOrder = array(array('CircularNoticeTargetUser.first_order' => 'asc'));
if (! empty($order)) {
$customOrder[] = $order;
}
$order = $customOrder;
return $this->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
}
/**
* Save for read
*
* @param int $contentId circular_notice_contents.id
* @param int $userId user id
* @return bool
* @throws InternalErrorException
*/
public function saveRead($contentId, $userId) {
$target = $this->find('first', array(
'conditions' => array(
'CircularNoticeTargetUser.circular_notice_content_id' => $contentId,
'CircularNoticeTargetUser.user_id' => $userId,
)
));
if ($target['CircularNoticeTargetUser']['reply_status'] ==
CircularNoticeComponent::CIRCULAR_NOTICE_CONTENT_STATUS_UNREAD) {
if ($target['CircularNoticeContent']['content_status'] ==
CircularNoticeComponent::CIRCULAR_NOTICE_CONTENT_STATUS_OPEN ||
$target['CircularNoticeContent']['content_status'] ==
CircularNoticeComponent::CIRCULAR_NOTICE_CONTENT_STATUS_FIXED
) {
$data = array(
'CircularNoticeTargetUser' => array(
'id' => $target['CircularNoticeTargetUser']['id'],
'user_id' => $target['CircularNoticeTargetUser']['user_id'],
'is_read' => true,
'read_datetime' => date('Y-m-d H:i:s'),
)
);
if (! $this->saveCircularNoticeTargetUser($data)) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
}
}
return true;
}
/**
* Save circular notice target user
*
* @param array $data input data
* @return bool
* @throws InternalErrorException
*/
public function saveCircularNoticeTargetUser($data) {
$this->begin();
try {
// データセット+検証
$this->validate['reply_text_value'] = array(
'notEmpty' => array(
'rule' => array('validateNotEmptyReplyValue'),
'last' => false,
'message' => sprintf(__d('net_commons', 'Please input %s.'),
__d('circular_notices', 'Answer Title')),
),
);
if (! $this->validateCircularNoticeTargetUser($data)) {
return false;
}
// CircularNoticeTargetUserを保存
if (! $this->save(null, false)) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
$this->commit();
} catch (Exception $ex) {
$this->rollback();
CakeLog::error($ex);
throw $ex;
}
return true;
}
/**
* Delete-insert circular notice target users
*
* @param array $data input data
* @return bool
* @throws InternalErrorException
*
* 速度改善の修正に伴って発生したため抑制
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function replaceCircularNoticeTargetUsers($data) {
$contentId = $data['CircularNoticeContent']['id'];
$oldContentId = isset($data['oldCircularNoticeContentId'])
? $data['oldCircularNoticeContentId']
: 0;
// 編集時に既に回答済みの情報を保持する
$existingTargetUsers = $this->find('all', array(
'recursive' => -1,
'fields' => array(
'user_id', 'is_read', 'read_datetime', 'is_reply',
'reply_datetime', 'reply_text_value', 'reply_selection_value'
),
'conditions' => array('circular_notice_content_id' => $oldContentId)
));
$tmp = [];
foreach ($existingTargetUsers as $existingTargetUser) {
$existingTargetUser = $existingTargetUser['CircularNoticeTargetUser'];
$tmp[$existingTargetUser['user_id']] = $existingTargetUser;
}
$existingTargetUsers = $tmp;
// 1件ずつ保存
if (isset($data['CircularNoticeTargetUsers']) && count($data['CircularNoticeTargetUsers']) > 0) {
foreach ($data['CircularNoticeTargetUsers'] as $targetUser) {
$targetUser['CircularNoticeTargetUser']['circular_notice_content_id'] = $contentId;
if (isset($existingTargetUsers[$targetUser['CircularNoticeTargetUser']['user_id']])
&& strtotime($data['CircularNoticeContent']['publish_start']) < strtotime('now')) {
$targetUser = array_merge($targetUser,
$existingTargetUsers[$targetUser['CircularNoticeTargetUser']['user_id']]);
$targetUser['CircularNoticeTargetUser']['reply_text_value'] = ''; // NC2の仕様を踏襲
$targetUser['CircularNoticeTargetUser']['reply_selection_value'] = ''; // NC2の仕様を踏襲
}
if (! $this->validateCircularNoticeTargetUser($targetUser)) {
return false;
}
if (! $this->save(null, false)) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
}
}
return true;
}
/**
* Validate this model
*
* @param array $data input data
* @return bool
*/
public function validateCircularNoticeTargetUser($data) {
$this->set($data);
$this->validates();
return $this->validationErrors ? false : true;
}
/**
* Get summary of answer.
*
* @param int $contentId circular_notice_content.id
* @param array $userIds ユーザID配列
* @return array
*/
public function getAnswerSummary($contentId, $userIds) {
$answerSummary = array();
$targetUsers = $this->getCircularNoticeTargetUsers($contentId, $userIds);
foreach ($targetUsers as $targetUser) {
$selectionValues = $targetUser['CircularNoticeTargetUser']['reply_selection_value'];
if ($selectionValues) {
$answers = explode(CircularNoticeComponent::SELECTION_VALUES_DELIMITER, $selectionValues);
foreach ($answers as $answer) {
if (! isset($answerSummary[$answer])) {
$answerSummary[$answer] = 1;
} else {
$answerSummary[$answer]++;
}
}
}
}
return $answerSummary;
}
}