You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.7 KiB

  1. <?php
  2. namespace App;
  3. use App\HiLib\Models\Model;
  4. use App\Scopes\BusinessScope;
  5. class Workflow extends Model
  6. {
  7. protected $fillable = ['business_id', 'name', 'desc', 'statuses'];
  8. protected $reportable = [
  9. 'name'
  10. ];
  11. protected $fillable_relations = ['statuses'];
  12. public function rules()
  13. {
  14. return [
  15. 'name' => 'required|string|min:3|max:225',
  16. 'desc' => 'nullable|string|min:3|max:225',
  17. 'statuses' => 'required|array|min:2',
  18. 'statuses.*' => 'required|array|min:2',
  19. 'statuses.*.id' => 'nullable|numeric',
  20. 'statuses.*.name' => 'required|string|min:3',
  21. 'statuses.*.state' => 'required|numeric|between:0,3',
  22. 'statuses.*.order' => 'nullable|numeric',
  23. ];
  24. }
  25. public function getValueOf(?string $key)
  26. {
  27. $values = [
  28. 'business_id' => $this->business_id,
  29. 'project_id' => null,
  30. 'sprint_id' => null,
  31. 'workflow_id' => $this->id,
  32. 'status_id' => null,
  33. 'system_id' => null,
  34. 'user_id' => null,
  35. ];
  36. if ($key && isset($values, $key)) {
  37. return $values[$key];
  38. }
  39. return $values;
  40. }
  41. public function updateRelations()
  42. {
  43. $old_statuses_name = isset(\request('_business_info')['workflows'][$this->id]['statuses']) ?
  44. array_keys(collect(\request('_business_info')['workflows'][$this->id]['statuses'])->toArray()) :
  45. [];
  46. $new_statuses_name = array_keys(collect($this->filled_relations['statuses'])->keyBy('id')->toArray());
  47. $removed_statuses_name = array_diff(array_merge($old_statuses_name, $new_statuses_name), $new_statuses_name);
  48. foreach ($removed_statuses_name as $status_name) {
  49. //delete all statuses that removed name's from request->statuses
  50. $this->statuses()->where('id', $status_name)->first()->delete();
  51. }
  52. foreach (request('statuses') as $status) {
  53. //sync another statuses
  54. $this->statuses()
  55. ->updateOrCreate(
  56. ['id' => $status['id'] ?? null, 'business_id' => $this->business_id, 'workflow_id' => $this->id],
  57. ['name' => $status['name'], 'state' => $status['state'], 'order' => $status['order']]
  58. );
  59. }
  60. }
  61. public function business()
  62. {
  63. return $this->belongsTo(Business::class, 'business_id');
  64. }
  65. public function statuses()
  66. {
  67. return $this->hasMany(Status::class, 'workflow_id', 'id');
  68. }
  69. public function tasks()
  70. {
  71. return $this->hasMany(Task::class, 'workflow_id', 'id');
  72. }
  73. }