領収証発行サービス
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.

435 lines
12KB

  1. <?php
  2. namespace App\Http\Controllers\Web;
  3. use App\Codes\HTTPResultCode as ResultCode;
  4. use App\Codes\UserRole;
  5. use App\Exceptions\AppCommonException;
  6. use App\Exceptions\ExclusiveException;
  7. use App\Exceptions\GeneralErrorMessageException;
  8. use App\Util\DBUtil;
  9. use Exception;
  10. use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
  11. use Illuminate\Foundation\Bus\DispatchesJobs;
  12. use Illuminate\Foundation\Validation\ValidatesRequests;
  13. use Illuminate\Http\JsonResponse;
  14. use Illuminate\Http\Request;
  15. use Illuminate\Http\Response;
  16. use Illuminate\Routing\Controller as BaseController;
  17. use Illuminate\Support\Arr;
  18. use Illuminate\Support\Facades\Auth;
  19. use Illuminate\Support\Facades\Log;
  20. use Illuminate\Support\Facades\Validator;
  21. use Illuminate\Support\Str;
  22. use Illuminate\Validation\ValidationException;
  23. use LogicException;
  24. use Slack;
  25. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  26. use Symfony\Component\HttpKernel\Exception\HttpException;
  27. abstract class WebController extends BaseController
  28. {
  29. use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
  30. const COL_NAME_CREATED_AT = 'created_at';
  31. const COL_NAME_UPDATED_AT = 'updated_at';
  32. const COL_NAME_RESULT_CODE = 'result';
  33. const COL_NAME_DATA = 'data';
  34. const COL_NAME_MESSAGES = 'messages';
  35. const COL_NAME_GENERAL_MESSAGE = 'general';
  36. const COL_NAME_EMAIL_ID = 'email_id';
  37. const COL_NAME_ERRORS = 'errors';
  38. /**
  39. * バリデートした結果を格納
  40. *
  41. * @var array
  42. */
  43. protected $validated = [];
  44. /**
  45. * 画面へ返却するメールID
  46. *
  47. * @var integer|null
  48. */
  49. private int|null $emailId = null;
  50. /**
  51. * 返却するメッセージ
  52. *
  53. * @var array|null
  54. */
  55. private array|null $messages = null;
  56. /**
  57. * 返却するメッセージ
  58. *
  59. * @var string|null
  60. */
  61. private string|null $generalMessage = null;
  62. /**
  63. * 返却するデータ
  64. *
  65. * @var mixed|null
  66. */
  67. private $data = null;
  68. protected DBUtil $transaction;
  69. /**
  70. * 返却する結果コード
  71. *
  72. * @var ResultCode|null
  73. */
  74. private ResultCode|null $resultCode = ResultCode::SECCESS;
  75. public function __construct()
  76. {
  77. $this->transaction = DBUtil::instance();
  78. }
  79. /**
  80. * パラメータオブジェクト
  81. */
  82. protected function getParam(): IParam
  83. {
  84. if (!property_exists(static::class, 'param')) {
  85. throw new LogicException("param未定義");
  86. }
  87. $param = $this->param;
  88. if (!is_subclass_of($param, IParam::class)) {
  89. throw new LogicException("param型不正");
  90. }
  91. return $this->param;
  92. }
  93. /**
  94. * コントローラーの名前
  95. * オーバーライドされることを想定
  96. * 主に、Routeのドキュメント作成用
  97. *
  98. * @return string
  99. */
  100. public function name(): string
  101. {
  102. return "---未設定---";
  103. }
  104. /**
  105. * コントローラーの説明
  106. * オーバーライドされることを想定
  107. * 主に、Routeのドキュメント作成用
  108. *
  109. * @return string
  110. */
  111. public function description(): string
  112. {
  113. return "---未設定---";
  114. }
  115. /**
  116. * オーバーライド必要
  117. * メインロジック
  118. *
  119. * @param Request $request
  120. * @return Response|JsonResponse|string
  121. */
  122. protected function run(Request $request): Response|JsonResponse|BinaryFileResponse|string
  123. {
  124. return $this->successResponse();
  125. }
  126. private function getRules()
  127. {
  128. return $this->getParam()->rules();
  129. }
  130. public function entry(Request $request)
  131. {
  132. $this->setLogContext($request);
  133. try {
  134. $validator = Validator::make($request->all(), $this->getRules());
  135. $validator->validate();
  136. } catch (ValidationException $e) {
  137. logger("validate error", ['errors' => $e->errors(), 'request' => $request->all(), 'path' => $request->path()]);
  138. return $this->validateErrorResponse($e);
  139. }
  140. try {
  141. $this->validated = $validator->validated();
  142. $this->getParam()->setData($this->validated);
  143. $this->authorize();
  144. $this->transaction->beginTransaction();
  145. $ret = $this->run($request);
  146. $this->transaction->commit();
  147. Slack::commit();
  148. return $ret;
  149. } catch (GeneralErrorMessageException $e) {
  150. $this->transaction->rollBack();
  151. Slack::commit();
  152. return $this->failedResponse([], $e->getMessage());
  153. } catch (AppCommonException $e) {
  154. $this->transaction->rollBack();
  155. Slack::commit();
  156. logs()->error(sprintf("Appエラー:%s File:%s Line:%d", $e->getMessage(), $e->getFile(), $e->getLine()));
  157. return $this->failedResponse();
  158. } catch (ExclusiveException $e) {
  159. $this->transaction->rollBack();
  160. Slack::commit();
  161. logs()->error(sprintf("排他エラー:%s", $e->getMessage()));
  162. return $this->exclusiveErrorResponse();
  163. } catch (LogicException $e) {
  164. $this->transaction->rollBack();
  165. Slack::commit();
  166. logs()->error([
  167. sprintf("実装エラー:%s", $e->getMessage()),
  168. get_class($e),
  169. $e->getFile(),
  170. $e->getLine(),
  171. $request->all(),
  172. ]);
  173. logger(array_filter($e->getTrace(), function ($val, $key) {
  174. return $key <= 5;
  175. }, ARRAY_FILTER_USE_BOTH));
  176. return $this->failedResponse();
  177. } catch (ValidationException $e) {
  178. $this->transaction->rollBack();
  179. Slack::commit();
  180. return $this->validateErrorResponse($e);
  181. } catch (HttpException $e) {
  182. $this->transaction->rollBack();
  183. Slack::commit();
  184. if ($e->getStatusCode() === 401) {
  185. return $this->unAuthorizedResponse();
  186. }
  187. throw $e;
  188. } catch (Exception $e) {
  189. $this->transaction->rollBack();
  190. Slack::commit();
  191. logs()->error([
  192. sprintf("例外エラー:%s", $e->getMessage()),
  193. get_class($e),
  194. $e->getFile(),
  195. $e->getLine(),
  196. $request->all(),
  197. ]);
  198. logger(array_filter($e->getTrace(), function ($val, $key) {
  199. return $key <= 5;
  200. }, ARRAY_FILTER_USE_BOTH));
  201. return $this->failedResponse();
  202. }
  203. }
  204. protected function successResponse(array|object $data = [], array|string $messages = [])
  205. {
  206. return $this->setData($data)
  207. ->setMessages($messages)
  208. ->setResultCode(ResultCode::SECCESS)
  209. ->makeResponse();
  210. }
  211. protected function failedResponse(array|object $data = [], array|string $messages = [])
  212. {
  213. return $this->setData($data)
  214. ->setMessages($messages)
  215. ->setResultCode(ResultCode::FAILED)
  216. ->makeResponse();
  217. }
  218. protected function unAuthorizedResponse(array|object $data = [], array|string $messages = [])
  219. {
  220. return $this->setData($data)
  221. ->setMessages($messages)
  222. ->setResultCode(ResultCode::UNAUTHORIZED)
  223. ->makeResponse();
  224. }
  225. protected function exclusiveErrorResponse(array|object $data = [], array|string $messages = [])
  226. {
  227. return $this->setData($data)
  228. ->setMessages($messages)
  229. ->setResultCode(ResultCode::EXCLUSIVE_ERROR)
  230. ->makeResponse();
  231. }
  232. protected function validateErrorResponse(ValidationException|array $exception, string|null $generalMessage = null)
  233. {
  234. $errorMessages = [];
  235. $general = null;
  236. if ($exception instanceof ValidationException) {
  237. foreach ($exception->errors() as $key => $m) {
  238. $errorMessages[$key] = $m[0];
  239. }
  240. }
  241. if (is_array($exception)) {
  242. $errorMessages = $exception;
  243. }
  244. $general = $generalMessage ?? data_get($errorMessages, self::COL_NAME_GENERAL_MESSAGE);
  245. return $this->setData([])
  246. ->setMessages($errorMessages)
  247. ->setGeneralMessage($general)
  248. ->setResultCode(ResultCode::FAILED)
  249. ->makeResponse();
  250. }
  251. private function makeResponse()
  252. {
  253. if ($this->resultCode === null) {
  254. abort(403);
  255. }
  256. $ret = [];
  257. Arr::set($ret, self::COL_NAME_RESULT_CODE, $this->resultCode->value);
  258. if ($this->data !== null) {
  259. Arr::set($ret, self::COL_NAME_DATA, $this->data);
  260. }
  261. if ($this->messages !== null) {
  262. Arr::set($ret, self::COL_NAME_MESSAGES . "." . self::COL_NAME_ERRORS, $this->messages);
  263. }
  264. if ($this->generalMessage !== null) {
  265. Arr::set($ret, self::COL_NAME_MESSAGES . "." . self::COL_NAME_GENERAL_MESSAGE, $this->generalMessage);
  266. }
  267. if ($this->emailId !== null) {
  268. Arr::set($ret, self::COL_NAME_MESSAGES . "." . self::COL_NAME_EMAIL_ID, $this->emailId);
  269. }
  270. if (request()->wantsJson()) {
  271. return response()
  272. ->json($ret)
  273. ->withHeaders($this->makeHeader());
  274. } else {
  275. abort(500);
  276. }
  277. }
  278. private function makeHeader(): array
  279. {
  280. $header = [];
  281. $user = Auth::user();
  282. if ($user) {
  283. $header["App-User-Auth"] = sprintf("%d,%d", $user->id, $user->role->value);
  284. } else {
  285. $header["App-User-Auth"] = 'none';
  286. }
  287. return $header;
  288. }
  289. // 以下 認可関係
  290. protected array|null $roleAllow = null;
  291. protected array|null $roleDisallow = null;
  292. protected array|null $customAllow = null;
  293. protected function roleAllow(UserRole $role)
  294. {
  295. $this->roleAllow = [];
  296. foreach (UserRole::cases() as $ele) {
  297. if ($role->value <= $ele->value) {
  298. $this->roleAllow[] = $ele;
  299. }
  300. }
  301. }
  302. private function authorize()
  303. {
  304. if (!Auth::check()) {
  305. return;
  306. }
  307. $role = Auth::user()->role;
  308. if (!$this->canAccess($role)) {
  309. abort(401);
  310. }
  311. }
  312. public function canAccess(UserRole $role)
  313. {
  314. if (is_array($this->roleAllow) && !in_array($role, $this->roleAllow)) {
  315. return false;
  316. }
  317. if (is_array($this->roleDisallow) && in_array($role, $this->roleDisallow)) {
  318. return false;
  319. }
  320. return $this->canCustomAccess();
  321. }
  322. public function canCustomAccess(): bool
  323. {
  324. if (Auth::user()->role === UserRole::SUPER_ADMIN) {
  325. return true;
  326. }
  327. if ($this->customAllow === null) {
  328. return true;
  329. }
  330. $myCustoms = Auth::user()->contract->custom();
  331. foreach ($this->customAllow as $targetCustom) {
  332. if (in_array($targetCustom, $myCustoms, true)) {
  333. return true;
  334. }
  335. }
  336. return false;
  337. }
  338. // 返却用データの登録
  339. protected function setEmailId(int $emailId)
  340. {
  341. $this->emailId = $emailId;
  342. return $this;
  343. }
  344. protected function setMessages(array|string $messages)
  345. {
  346. if (is_array($messages)) {
  347. $this->messages = $messages;
  348. } else {
  349. $this->setGeneralMessage($messages);
  350. }
  351. return $this;
  352. }
  353. protected function setGeneralMessage(string|null $generalMessage)
  354. {
  355. $this->generalMessage = $generalMessage;
  356. return $this;
  357. }
  358. protected function setData($data)
  359. {
  360. $this->data = $data;
  361. return $this;
  362. }
  363. protected function setResultCode(ResultCode $resultCode)
  364. {
  365. $this->resultCode = $resultCode;
  366. return $this;
  367. }
  368. protected function setLogContext(Request $request)
  369. {
  370. Log::withContext([
  371. '__requestUuid__' => strval(Str::uuid()),
  372. '__userId__' => Auth::id(),
  373. '__path__' => $request->path(),
  374. ]);
  375. }
  376. }