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.

89 lines
2.7 KiB

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