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.

87 lines
2.6 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. ];
  35. if ($key && isset($values, $key)) {
  36. return $values[$key];
  37. }
  38. return $values;
  39. }
  40. public function updateRelations()
  41. {
  42. $old_statuses_name = isset(\request('_business_info')['workflows'][$this->id]['statuses']) ?
  43. array_keys(collect(\request('_business_info')['workflows'][$this->id]['statuses'])->toArray()) :
  44. [];
  45. $new_statuses_name = array_keys(collect($this->filled_relations['statuses'])->keyBy('id')->toArray());
  46. $removed_statuses_name = array_diff(array_merge($old_statuses_name, $new_statuses_name), $new_statuses_name);
  47. foreach ($removed_statuses_name as $status_name) {
  48. //delete all statuses that removed name's from request->statuses
  49. $this->statuses()->where('id', $status_name)->first()->delete();
  50. }
  51. foreach (request('statuses') as $status) {
  52. //sync another statuses
  53. $this->statuses()
  54. ->updateOrCreate(
  55. ['id' => $status['id'] ?? null, 'business_id' => $this->business_id, 'workflow_id' => $this->id],
  56. ['name' => $status['name'], 'state' => $status['state'], 'order' => $status['order']]
  57. );
  58. }
  59. }
  60. public function business()
  61. {
  62. return $this->belongsTo(Business::class, 'business_id');
  63. }
  64. public function statuses()
  65. {
  66. return $this->hasMany(Status::class, 'workflow_id', 'id');
  67. }
  68. public function tasks()
  69. {
  70. return $this->hasMany(Task::class, 'workflow_id', 'id');
  71. }
  72. }