handler method

  1. @override
FutureOr<Response> handler()
override

Must be implemented

Implementation

@override
FutureOr<Response> handler() => checkApiSecret(request).fold(
      (errorResponse) => errorResponse,
      (_) async {
        final authorizationHeader = request.headers['authorization'] ??
            request.headers['Authorization'];
        final adminSecretHeader = request.headers['x-hasura-admin-secret'] ??
            request.headers['X-Hasura-Admin-Secret'];

        if (authorizationHeader == null &&
            adminSecretHeader != ADMIN_SECRET) {
          return HasuraError('Authorization header or admin secret required.')
              .response();
        }

        final bodyJson = await requestAsJson();
        final role = bodyJson['session_variables']['x-hasura-role'] as String;

        /// Если действие выполняется от админа, берём репозиторий из сервис
        /// локатора с ключом авторизации сервера.
        /// Иначе создаём новый репозиторий с передачей токена в GraphQLClient,
        /// чтобы все запросы происходили от имени пользователя, а не сервера.
        final paymentRepository = adminSecretHeader == ADMIN_SECRET
            ? sl<PaymentRepository>()
            : PaymentRepositoryImpl(
                dataSource: PaymentDataSourceImpl(
                  graphQLClient:
                      createGraphQLClient(authorizationHeader!, role),
                ),
              );

        final action = HasuraAction.fromJson(bodyJson);
        final importPaymentRequest =
            ImportPaymentsRequest.fromJson(action.input);

        final failureOrReceipts =
            await paymentRepository.getReceiptsByPaymentList(
          importPaymentRequest.payments,
          importPaymentRequest.departmentId,
        );

        return failureOrReceipts.fold(
          (failure) {
            print(failure.message);
            print(failure.stackTrace);
            return HasuraError('$failure').response();
          },
          (receipts) async {
            final newReceipts = <Receipt>[];

            for (final receipt in receipts) {
              var correspondingPayment;

              if (receipt.bank != 'Yape') {
                correspondingPayment = importPaymentRequest.payments
                    .firstWhere((p) => p.id == receipt.paymentId);
              } else {
                correspondingPayment = importPaymentRequest.payments
                    .firstWhere((p) => p.date == receipt.date);
              }

              if (receipt.amount == correspondingPayment.amount) {
                newReceipts.add(receipt.copyWith(status: 'accepted'));
              } else {
                newReceipts.add(
                  receipt.copyWith(
                    importComment: 'amount differs: bank bill - '
                        '${correspondingPayment.amount}',
                    status: 'errorImport',
                  ),
                );
              }
            }

            final failureOrReceipt = await paymentRepository
                .setReceiptsCommentAndStatus(newReceipts);

            return failureOrReceipt.fold(
              (failure) {
                print(failure.message);
                print(failure.stackTrace);
                return HasuraError('$failure').response();
              },
              (_) => Response.ok(
                json.encode({'imported': true}),
              ),
            );
          },
        );
      },
    );