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.

488 lines
15 KiB

  1. <?php
  2. namespace App\Models;
  3. use App\Models\File;
  4. use App\Models\Model;
  5. use App\Models\SoftDeletes;
  6. use App\Models\ReportableRelation;
  7. use Illuminate\Validation\Rule;
  8. use Illuminate\Http\UploadedFile;
  9. use Spatie\MediaLibrary\HasMedia;
  10. use Illuminate\Support\Facades\Cache;
  11. use Spatie\MediaLibrary\InteractsWithMedia;
  12. use Spatie\MediaLibrary\MediaCollections\Models\Media;
  13. class Business extends Model implements HasMedia
  14. {
  15. use SoftDeletes,
  16. InteractsWithMedia;
  17. const CONVERSION_NAME = 'avatar';
  18. const COLLECTION_NAME = 'avatars';
  19. public static $permissions = ['level'];
  20. protected $table = 'businesses';
  21. protected $fillable = ['name', 'slug', 'wallet','files_volume','cache', 'color', 'description', 'has_avatar', 'calculated_at', 'users'];
  22. protected $fillable_relations = [
  23. 'users'
  24. ];
  25. protected $reportable = [
  26. 'name', 'slug', 'wallet', 'files_volume', 'cache', 'calculated_at', // fields
  27. ['users' => 'business_user'] // relations [ name => pivot ]
  28. ];
  29. public $detach_relation = false;
  30. protected $casts = [
  31. 'has_avatar' => 'boolean',
  32. 'calculated_at' => 'datetime',
  33. 'wallet' => 'integer',
  34. ];
  35. public function getValueOf(?string $key)
  36. {
  37. $values = [
  38. 'business_id' => $this->id,
  39. 'workflow_id' => null,
  40. 'project_id' => null,
  41. 'sprint_id' => null,
  42. 'status_id' => null,
  43. 'system_id' => null,
  44. 'user_id' => null,
  45. 'task_id' => null,
  46. 'subject_id' => $this->id,
  47. ];
  48. if ($key && isset($values, $key)) {
  49. return $values[$key];
  50. }
  51. return $values;
  52. }
  53. public function rules()
  54. {
  55. return [
  56. 'name' => 'bail|required|string|min:2|max:255',
  57. 'color' => 'nullable|string|min:2|max:255',
  58. 'slug' => ['bail', 'required', 'string', 'min:2', 'max:255', 'regex:/^[a-zA-Z]+[a-zA-Z\d-]*(.*[a-zA-Z\d])+$/',
  59. Rule::unique($this->table, 'slug')->ignore($this->id)],
  60. 'description' => 'nullable|string|min:2|max:1000',
  61. ];
  62. }
  63. public function cost()
  64. {
  65. return $this->hasMany(Cost::class, 'business_id','id');
  66. }
  67. public function owners()
  68. {
  69. return $this->users()->wherePivot('level', '=', enum('levels.owner.id'));
  70. }
  71. public function members()
  72. {
  73. return $this->users()->wherePivot('owner', '!=', enum('levels.owner.id'));
  74. }
  75. public function users()
  76. {
  77. return $this->belongsToMany(
  78. User::class, 'business_user', 'business_id', 'user_id',
  79. 'id', 'id', __FUNCTION__
  80. )
  81. ->using(ReportableRelation::class)
  82. ->withPivot(self::$permissions);
  83. }
  84. public function tags()
  85. {
  86. return $this->hasMany(Tag::class, 'business_id', 'id');
  87. }
  88. public function projects()
  89. {
  90. return $this->hasMany(Project::class, 'business_id', 'id');
  91. }
  92. public function systems()
  93. {
  94. return $this->hasMany(System::class, 'business_id', 'id');
  95. }
  96. public function workflows()
  97. {
  98. return $this->hasMany(Workflow::class, 'business_id', 'id');
  99. }
  100. public function sprints()
  101. {
  102. return $this->hasMany(Sprint::class, 'business_id', 'id');
  103. }
  104. public function statuses()
  105. {
  106. return $this->hasMany(Status::class, 'business_id', 'id');
  107. }
  108. public function files()
  109. {
  110. return $this->hasMany(File::class, 'user_id', 'id');
  111. }
  112. public function transactions()
  113. {
  114. return $this->hasMany(Transaction::class, 'business_id', 'id');
  115. }
  116. public function updateRelations()
  117. {
  118. // users relations
  119. if (!empty($this->filled_relations['users']) || $this->detach_relation) {
  120. $this->dirties['users'] = $this->users()->sync($this->filled_relations['users'], $this->detach_relation);
  121. }
  122. }
  123. public static function info($businessId, $fresh = false)
  124. {
  125. $info = [];
  126. $fresh = true;
  127. if ($fresh){
  128. Cache::forget('business_info'.$businessId);
  129. }
  130. if (Cache::has('business_info'.$businessId)) {
  131. return Cache::get('business_info'.$businessId);
  132. } else {
  133. $business = self::findOrFail($businessId);
  134. $tags = $business->tags()->select('id', 'label', 'color')->get()->keyBy('id');
  135. $info['tags'] = $tags->pluck('id');
  136. $workflows = $business->workflows()->select ('id', 'business_id', 'name','desc')->get()->keyBy('id')
  137. ->load(['statuses'=> fn($q) => $q->select('id', 'business_id', 'workflow_id', 'name', 'state', 'order')])
  138. ->map(fn($q) => [
  139. 'id' => $q->id,
  140. 'business_id' => $q->business_id,
  141. 'name' => $q->name,
  142. 'desc' => $q->desc,
  143. 'statuses' => $q['statuses']->keyBy('id'),
  144. ]);
  145. $info['workflows'] = $workflows->map(fn($q) => ['statuses' => $q['statuses']->pluck('id')]);
  146. $users = $business->users()->select('id', 'name', 'email', 'mobile', 'username')->with('media')->get()
  147. ->keyBy('id')
  148. ->map(fn($u) => [
  149. 'id' => $u->id,
  150. 'name' => $u->name,
  151. 'email' => $u->email,
  152. 'mobile' => $u->mobile,
  153. 'username' => $u->get,
  154. 'avatar' => $u->has_avatar,
  155. 'level' => $u->pivot['level'],
  156. ]);
  157. $info['users'] = $users->map(fn($u) => [
  158. 'level' => $u['level']
  159. ]);
  160. $projects = $business->projects()->get()->keyBy('id')->load([
  161. 'members' => fn($q) => $q->select('id', 'level'),
  162. 'systems' => fn($q) => $q->select('id', 'project_id', 'name'),
  163. 'sprints' => fn($q) => $q->select('id', 'project_id', 'name', 'description', 'started_at', 'ended_at', 'active'),
  164. 'media',
  165. ]);
  166. $info['projects'] = $projects->map(function($q) use($users){
  167. return [
  168. 'avatar' => $q->has_avatar,
  169. 'systems' => $q->systems->pluck('id'),
  170. 'sprints' => $q->sprints->pluck('id'),
  171. 'members' => $users->keyBy('id')->map(function($u, $uid) use ($q){
  172. $project_user = $q->members->firstWhere('id', $uid);
  173. return $project_user? ['level' => $project_user->pivot->level, 'is_direct' => true]:
  174. ['level' => $q->private && $u['level'] != enum('levels.owner.id') ? enum('levels.inactive.id') : $u['level'],
  175. 'is_direct'=> $project_user ? true : false];
  176. })
  177. ];
  178. });
  179. $business_info = array_merge(
  180. $business->only('id', 'name', 'slug', 'color','wallet', 'files_volume'),
  181. ['avatar' => $business->has_avatar],
  182. compact(
  183. 'info',
  184. 'tags',
  185. 'workflows',
  186. 'users',
  187. 'projects'
  188. )
  189. );
  190. Cache::put('business_info'.$businessId , $business_info, config('app.cache_ttl'));
  191. return $business_info;
  192. }
  193. }
  194. public static function stats()
  195. {
  196. return [
  197. 'users' => [
  198. 10 => [
  199. 'statuses' => [
  200. 10 => 20,
  201. 30 => 40
  202. ],
  203. 'workflows' => [
  204. 10 => 20,
  205. 30 => 40
  206. ],
  207. 'tags' => [
  208. 10 => 20,
  209. 30 => 40
  210. ],
  211. 'project' => [
  212. 10 => 20,
  213. 30 => 40
  214. ],
  215. 'sprints' => [
  216. 10 => 20,
  217. 30 => 40
  218. ],
  219. 'works' => [
  220. ],
  221. '__subsystems' => [
  222. 10 => 20,
  223. 30 => 40
  224. ],
  225. ]
  226. ],
  227. 'workflows' => [
  228. 50 => [
  229. 'statuses' => [
  230. 20 => 50
  231. ],
  232. ]
  233. ],
  234. 'statuses' => [
  235. 10 => [
  236. 'users' => [
  237. ],
  238. 'projects' => [
  239. ]
  240. ]
  241. ],
  242. 'sprints' => [
  243. 10 => [
  244. 'statuses' => [
  245. 10 => [
  246. 10 => 1
  247. ]
  248. ]
  249. ]
  250. ]
  251. ];
  252. }
  253. public function reportActivity()
  254. {
  255. }
  256. public static function nuxtInfo($businessId)
  257. {
  258. if (empty($businessId)){
  259. return null;
  260. }
  261. Cache::forget('business_nuxt_info' . $businessId);
  262. return Cache::rememberForever('business_nuxt_info' . $businessId, function () use ($businessId) {
  263. $business = self::with([
  264. 'projects.members' => fn($q) => $q->select('id', 'name'),
  265. 'projects',
  266. 'tags',
  267. 'workflows.statuses',
  268. 'workflows',
  269. 'statuses',
  270. 'users',
  271. ])->findOrFail($businessId);
  272. $globals = [];
  273. $business->users->each(function ($u) use (&$globals) {
  274. $globals[$u->id] = $u->pivot->owner == true ? ['owner' => true] : $u->pivot->only(self::$permissions);
  275. });
  276. $projects = [];
  277. $business->projects->each(function ($p) use (&$projects, &$globals) {
  278. });
  279. $business->setRelation('projects', collect($projects));
  280. $business->setRelation('users', collect($globals));
  281. return $business;
  282. });
  283. }
  284. public static function infoOld($businessId)
  285. {
  286. if (empty($businessId))
  287. return null;
  288. Cache::forget('business_info' . $businessId);
  289. return Cache::rememberForever('business_info' . $businessId, function () use ($businessId) {
  290. $ob = [];
  291. $business = self::with([
  292. 'projects.members' => fn($q) => $q->select('id', 'name'),
  293. 'projects' => fn($q) => $q->select('id', 'business_id', 'private'),
  294. 'tags' => fn($q) => $q->select('id', 'business_id', 'label'),
  295. 'sprints' => fn($q) => $q->select('id','business_id','name', 'active'),
  296. 'workflows.statuses' => fn($q) => $q->select('id', 'name'),
  297. 'workflows' => fn($q) => $q->select('id', 'business_id', 'name'),
  298. 'statuses' => fn($q) => $q->select('id', 'business_id', 'name', 'state'),
  299. 'users' => fn($q) => $q->select('id', 'name'),
  300. ])->findOrFail($businessId);
  301. // permissions in business
  302. $permissions = [];
  303. $business->users->each(function ($user) use (&$permissions) {
  304. $permissions[$user->id] = $user->pivot->only(['owner']);
  305. $permissions[$user->id]['global_PA'] = $permissions[$user->id]['owner'] == true ?
  306. enum('roles.manager.id') : $user->pivot->PA;
  307. $permissions[$user->id]['global_FA'] = $permissions[$user->id]['owner'] == true ?
  308. enum('roles.manager.id') : $user->pivot->FA;
  309. $permissions[$user->id]['PA'] = [];
  310. $permissions[$user->id]['FA'] = [];
  311. });
  312. //projects
  313. $projects = [];
  314. $business->projects->each(function ($p) use (&$permissions, $business, &$projects) {
  315. $business->users->each(function ($user) use (&$permissions, $p) {
  316. $PA = null;
  317. $FA = null;
  318. if ($permissions[$user->id]['owner'] == true) {
  319. $PA = enum('roles.manager.id');
  320. $FA = enum('roles.manager.id');
  321. } else if (!empty($project_user = $p->getPermissions($user->id))) {
  322. $PA = $project_user->pivot->PA;
  323. $FA = $project_user->pivot->FA;
  324. } else if (empty($p->getPermissions($user->id))) {
  325. $PA = $p->private == false ? $permissions[$user->id]['global_PA'] : enum('roles.hidden.id') ;
  326. $FA = $p->private == false ? $permissions[$user->id]['global_FA'] : enum('roles.hidden.id');
  327. }
  328. if ($PA !== null && $FA !== null) {
  329. $permissions[$user->id]['PA'][$p->id] = $PA;
  330. $permissions[$user->id]['FA'][$p->id] = $FA;
  331. }
  332. });
  333. $projects[$p->id] ='';
  334. });
  335. //workflow
  336. $workflows = [];
  337. $business->workflows->each(function ($w) use (&$workflows) {
  338. $workflows[$w->id] = $w->statuses->pluck('id');
  339. });
  340. $ob['tags'] = $business->tags->pluck('id');
  341. $ob['statuses'] = $business->statuses;
  342. $ob['sprints'] = $business->sprints;
  343. $ob['workflows'] = $workflows;
  344. $ob['users'] = $permissions;
  345. $ob['projects'] = $projects;
  346. return collect($ob);
  347. });
  348. }
  349. public function registerMediaCollections(): void
  350. {
  351. $this->addMediaCollection(static::COLLECTION_NAME)
  352. ->acceptsMimeTypes([
  353. 'image/jpeg',
  354. 'image/png',
  355. 'image/tiff',
  356. 'image/gif',
  357. ])
  358. ->useDisk('public')
  359. ->singleFile();
  360. }
  361. public function registerMediaConversions(Media $media = null): void
  362. {
  363. $this->addMediaConversion(static::CONVERSION_NAME)
  364. ->width(200)
  365. ->height(200)
  366. ->queued()
  367. ->nonOptimized()
  368. ->performOnCollections(static::COLLECTION_NAME);
  369. }
  370. public function saveAsAvatar(UploadedFile $avatar): void
  371. {
  372. $this->addMedia($avatar)->toMediaCollection(static::COLLECTION_NAME);
  373. $this->update([
  374. 'has_avatar' => true,
  375. ]);
  376. @unlink($this->getFirstMedia(static::COLLECTION_NAME)->getPath());
  377. }
  378. public function deleteAvatar(): void
  379. {
  380. $path = $this->getFirstMedia(static::COLLECTION_NAME)->getPath();
  381. $this->getFirstMedia(static::COLLECTION_NAME)->delete();
  382. $this->update([
  383. 'has_avatar' => false,
  384. ]);
  385. @unlink($path);
  386. }
  387. public function getAvatarUrl(): ?string
  388. {
  389. if ($url = $this->getFirstMediaUrl(static::COLLECTION_NAME, static::CONVERSION_NAME)) {
  390. return $url;
  391. }
  392. return null;
  393. }
  394. }