All files / src/apis/wallet wallet.compat.ts

47.05% Statements 24/51
36.36% Branches 4/11
37.83% Functions 14/37
46% Lines 23/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 4834x 4x                     4x 4x 4x               2x 2x                                                                                   1x                                       1x                           1x               1x                         1x                                               1x                           1x                                                       1x               1x                                                                                                                                     4x                                                                                         1x                                                                         1x 1x 1x   1x                         1x                                                                                                                                                                                                                                                    
import { Wallet } from "./wallet";
import * as types from "./wallet.types";
 
/**
 *
 * @deprecated Используйте класс `Wallet` и новые сигнатуры
 * методов
 *
 * @export
 * @class WalletCompat
 * @extends {Wallet}
 */
export class WalletCompat extends Wallet {
  static readonly IdentificationLevel = types.PersonIdentificationLevel;
  static readonly ReceiptFormat = types.ChequeFormat;
 
  /**
   * Creates an instance of WalletCompat.
   * @param {string} token
   * @param {string} [walletId=""]
   * @memberof WalletCompat
   */
  constructor(public readonly token: string, public readonly walletId = "") {
    super({
      http: WalletCompat.httpClientFactory(token),
      token,
      walletId
    });
  }
 
  /**
   *
   *
   * @readonly
   * @memberof WalletCompat
   */
  get API_TOKEN() {
    return this.token;
  }
 
  /**
   *
   *
   * @readonly
   * @memberof WalletCompat
   */
  get webhookKey() {
    return this.webhooks.keys;
  }
 
  /**
   *
   *
   * @readonly
   * @memberof WalletCompat
   */
  get hookId() {
    return this.webhooks.activeId;
  }
 
  /**
   * Запрос возвращает информацию о вашем профиле - наборе
   * пользовательских данных и настроек вашего QIWI кошелька.
   */
  async getPersonProfile(): Promise<types.PersonProfile> {
    return await this.personProfile.getCurrent();
  }
 
  /**
   * Данный запрос позволяет отправить данные для идентификации
   * вашего QIWI кошелька.
   *
   * @param {types.IdentificationBase} data
   */
  async setIdentification(
    data: types.IdentificationBase
  ): Promise<types.IdentificationResponse> {
    return await this.identification.set(data);
  }
 
  /**
   * Данный запрос позволяет выгрузить маскированные данные и
   * статус идентификации своего QIWI кошелька.
   */
  async getIdentification(): Promise<types.IdentificationResponse> {
    return await this.identification.get();
  }
 
  /**
   * Запрос возвращает текущие уровни лимитов по операциям в вашем
   * QIWI кошельке. Лимиты действуют как ограничения на сумму
   * определенных операций.
   *
   * @template Limits
   * @param {Limits} limits
   */
  async getLimits<Limits extends types.LimitTypeAny[] = types.LimitTypeAny[]>(
    limits: Limits
  ): Promise<types.LimitsResponse<Limits[number]>> {
    return await this.limits.get<Limits>(limits);
  }
 
  /**
   * Запрос проверяет, есть ли ограничение на исходящие платежи с
   * QIWI Кошелька.
   */
  async getRestrictions(): Promise<types.Restrictions> {
    return await this.restrictions.get();
  }
 
  /**
   * Запрос выгружает список платежей и пополнений вашего кошелька.
   * Можно использовать фильтр по количеству, ID и дате
   * (интервалу дат) транзакций.
   *
   * @param {types.GetPaymentHistoryParams} parameters Тело запроса
   */
  async getPaymentHistory(
    parameters: types.GetPaymentHistoryParams
  ): Promise<types.GetTransactionsHistoryResponse> {
    return await this.paymentHistory.getHistory(parameters);
  }
  /**
   * Данный запрос используется для получения сводной статистики
   * по суммам платежей за заданный период.
   *
   * @param {types.GetPaymentHistoryTotalParams} parameters
   */
  async getPaymentHistoryTotal(
    parameters: types.GetPaymentHistoryTotalParams
  ): Promise<types.GetPaymentHistoryTotalResponse> {
    return await this.paymentHistory.getTotal(parameters);
  }
  /**
   * Запрос используется для получения информации по определенной
   * транзакции из вашей истории платежей.
   *
   * @param {number} transactionId Номер транзакции
   * @param {types.TransactionType} [type] Тип транзакции
   */
  async getTransaction(
    transactionId: number,
    type?: types.TransactionType
  ): Promise<types.Transaction> {
    return await this.paymentHistory.getTransaction(transactionId, type);
  }
 
  /**
   *
   * @param {types.StringOrNumber} transactionId  номер транзакции из {@link https://developer.qiwi.com/ru/qiwi-wallet-personal/#history_data|истории платежей} (параметр data[].txnId в ответе)
   * @param {types.TransactionType} type тип транзакции из {@link https://developer.qiwi.com/ru/qiwi-wallet-personal/#history_data|истории платежей} (параметр data[].type в ответе)
   * @param {types.ChequeFormat} format тип файла, в который сохраняется квитанция. Допустимые значения: `JPEG`, `PDF`
   */
  async getTransactionCheque(
    transactionId: types.StringOrNumber,
    type: types.TransactionType,
    format: types.ChequeFormat = types.ChequeFormat.JPEG
  ): Promise<Buffer> {
    return await this.paymentHistory.getTransactionCheque(
      transactionId,
      type,
      format
    );
  }
 
  /**
   *
   * @param {types.StringOrNumber} transactionId  номер транзакции из {@link https://developer.qiwi.com/ru/qiwi-wallet-personal/#history_data|истории платежей} (параметр data[].txnId в ответе)
   * @param {types.TransactionType} type тип транзакции из {@link https://developer.qiwi.com/ru/qiwi-wallet-personal/#history_data|истории платежей} (параметр data[].type в ответе)
   * @param {string} email Адрес для отправки электронной квитанции
   */
  async sendTransactionCheque(
    transactionId: types.StringOrNumber,
    type: types.TransactionType,
    email: string
  ): Promise<""> {
    await this.paymentHistory.sendTransactionCheque(transactionId, type, email);
 
    return "";
  }
 
  /**
   * Успешный ответ содержит JSON-массив счетов вашего QIWI
   * Кошелька для фондирования платежей и текущие балансы счетов
   */
  async getAccounts(): Promise<types.GetAccountsResponse["accounts"]> {
    return await this.fundingSources.getAccounts();
  }
 
  /**
   * Успешный JSON-ответ содержит данные о счетах, которые можно
   * создать
   */
  async getAccountOffers(): Promise<types.GetAccountOffersResponse> {
    return await this.fundingSources.getAccountOffers();
  }
 
  /**
   * Создаёт новый счёт по параметру `alias`
   * Успешный ответ возвращает пустую строку
   * @param {string} alias Псевдоним нового счета (см. {@link https://developer.qiwi.com/ru/qiwi-wallet-personal/?http#funding_offer|запрос доступных счетов})
   * @param {StringOrNumber} wallet Номер кошелька
   */
  async createAccount(alias: string): Promise<""> {
    await this.fundingSources.createAccount(alias);
    return "";
  }
 
  /**
   * Устанавливает счёт по умолчанию
   * Успешный ответ возвращает пустую строку
   * @param {string} alias Псевдоним счета (см. {@link https://developer.qiwi.com/ru/qiwi-wallet-personal/?http#funding_offer|запрос доступных счетов})
   * @param {StringOrNumber} wallet Номер кошелька
   */
  async setDefaultAccount(alias: string): Promise<""> {
    await this.fundingSources.setDefaultAccount(alias);
    return "";
  }
 
  /**
   *
   * Получает сумму комиссии по заданным реквизитам
   *
   * @param {number} provider ID Провайдера у QIWI
   * @param {string} account ID получателя у провайдера
   * @param {number} amount Сумма
   * @return {Promise<number>}
   */
  async getCommission(
    provider: number,
    account: string,
    amount: number
  ): Promise<number> {
    return await this.payments.getCommission(provider, account, amount);
  }
 
  /**
   * Данный метод создаёт ссылку на предзаполненную форму
   *
   * @param {number} provider ID провайдера
   * @param {types.FormUrlOptions} options
   * @return {string}
   */
  static createFormUrl(
    provider: number | types.Recipients,
    options: types.FormUrlOptions = {}
  ): string {
    return WalletCompat.PaymentsApi.createFormUrl(provider, options);
  }
 
  /**
   * Данный метод создаёт ссылку на предзаполненную форму
   *
   * @param {number} provider ID провайдера
   * @param {types.FormUrlOptions} options
   * @return {string}
   */
  createFormUrl(
    provider: number | types.Recipients,
    options: types.FormUrlOptions = {}
  ): string {
    return this.payments.createFormUrl(provider, options);
  }
 
  /**
   * Перевод с кошелька
   *
   * [Документация QIWI по методу оплаты](https://developer.qiwi.com/ru/qiwi-wallet-personal/#payments)
   *
   * @param {number | types.Recipients} provider Ака ID, в доках, номер провайдера у QIWI
   * @param {string} account Номер кошелька или карты или типа того
   * @param {number} amount Сумма платежа
   * @param {types.Currency=} currency Валюта платежа, по умолчанию = рубли
   * @param {Object=} fields Доп. поля, их невозможно типизировать, просто читайте доки
   * @param {string=} comment Комментарий к платежу, необязательный
   *
   * @deprecated Используйте {@link pay2}, так-как он более читаемый
   * @return {Promise<types.PaymentResponse>}
   */
  async pay(
    provider: types.PayParameters["provider"],
    account: types.PayParameters["account"],
    amount: types.PayParameters["amount"],
    currency: types.PayParameters["currency"] = WalletCompat.Currency.RUB,
    fields: types.PayParameters["fields"] = {},
    comment: types.PayParameters["comment"] = ""
  ): Promise<types.PaymentResponse> {
    return await this.pay2({ provider, account, amount, currency, fields, comment });
  }
 
  /**
   * Более читаемая версия метода {@link pay}
   *
   * [Документация QIWI по методу оплаты](https://developer.qiwi.com/ru/qiwi-wallet-personal/#payments)
   *
   * @param {types.Pay2Params} params Параметры платежа
   * @return {Promise<types.PaymentResponse>}
   */
  async pay2({
    account,
    amount,
    provider = WalletCompat.Recipients.QIWI,
    comment = "",
    currency = WalletCompat.Currency.RUB,
    fields = {}
  }: types.PayParameters): Promise<types.PaymentResponse> {
    return await this.payments.pay({
      account,
      amount,
      provider,
      comment,
      currency,
      fields
    });
  }
 
  /**
   * Создаёт пару ключей для взаимодействия с P2P BILLS API
   *
   * @param {string} name Название связки ключей
   * @param {string=} server URL сервера для отправки уведомлений
   *
   * @return {string[]} Массив, где - [0=Публичный ключ, 1=Секретный ключ]
   *
   * @example
   *
   * const [PublicKey, SecretKey] = await createP2PKeyPair('my-key-pair');
   */
  async createP2PKeyPair(
    name: string,
    server?: string
  ): Promise<[PublicKey: string, SecretKey: string]> {
    const { publicKey, secretKey } = await this.bills.createP2PKeyPair(name, server);
 
    return [publicKey, secretKey];
  }
 
  /**
   * Создаёт токен с увеличенным сроком действия (10 лет)
   *
   * @see {@link https://developer.qiwi.com/ru/qiwi-wallet-personal-advanced/?http#intro|Документация}
   */
  async createOauthToken(): Promise<types.PrettyTokenResponse<WalletCompat>> {
    const { token, expiry } = await super.createOauthToken();
    const client = new WalletCompat(token, this.options.walletId);
    Object.assign(client.options, { http: this.options.http });
 
    return {
      token,
      expiry,
      client
    };
  }
 
  /**
   * Возвращает список карт
   *
   * @return {Promise<types.CardResponse>}
   */
  async getCards(): Promise<types.CardResponse[]> {
    return await this.cards.get();
  }
 
  /**
   * Блокирует карту
   *
   * @param {types.StringOrNumber} cardId
   *
   * @return {Promise<*>}
   */
  async blockCard(cardId: types.StringOrNumber): Promise<any> {
    return await this.cards.block(cardId);
  }
 
  /**
   * Разблокирует карту
   *
   * @param {types.CardUnblockResponse} cardId
   * @param {types.CardUnblockResponse} wallet
   * @return {Promise<types.CardUnblockResponse>}
   */
  async unblockCard(
    cardId: types.StringOrNumber
  ): Promise<types.CardUnblockResponse> {
    return await this.cards.unblock(cardId);
  }
 
  /**
   * Получает реквизиты карты
   *
   * @param {types.StringOrNumber} cardId
   * @return {Promise<types.CardRequisitesResponse>}
   */
  async getCardRequisites(
    cardId: types.StringOrNumber
  ): Promise<types.CardRequisitesResponse> {
    return await this.cards.getRequisites(cardId);
  }
 
  /**
   *
   * @param {types.StringOrNumber} cardId
   * @param {string} alias
   * @return {Promise<types.CardRenameResponse>}
   */
  async renameCard(
    cardId: types.StringOrNumber,
    alias: string
  ): Promise<types.CardRenameResponse> {
    // eslint-disable-next-line security/detect-non-literal-fs-filename
    return await this.cards.rename(cardId, alias);
  }
 
  /**
   * Регистрирует обработчик вебхука
   * @param {string} parameter Адрес сервера обработки вебхуков. **Внимание! Длина исходного (не URL-encoded) адреса сервиса обработчика не должна превышать 100 символов.**
   * @param {number} txnType Тип транзакций, по которым будут включены уведомления.. 0 - "входящие", 1 - "исходящие". 2 - "все"
   * @return {Promise<types.WebHookInfo>}
   */
  async addWebHook(
    parameter: string,
    txnType: 0 | 1 | 2
  ): Promise<types.WebHookInfo> {
    return await this.webhooks.add(parameter, txnType);
  }
 
  /**
   * Удаляет обработчик вебхука
   * @param {string} [hookId] UUID вебхука
   * @return {Promise<*>}
   */
  async removeWebHook(hookId?: string): Promise<any> {
    return await this.webhooks.remove(hookId);
  }
 
  /**
   * Получает секретный ключ вебхука
   * @param {string} [hookId] UUID вебхука
   * @return {Promise<string>}
   */
  async getWebHookSecret(hookId?: string): Promise<string> {
    return await this.webhooks.getSecret(hookId);
  }
 
  /**
   * Измененяет секретный ключ вебхука
   * @param {string} hookId UUID вебхука
   * @return {Promise<string>}
   */
  async getNewWebHookSecret(hookId?: string): Promise<string> {
    return await this.webhooks.updateSecret(hookId);
  }
 
  /**
   *
   * @return {Promise<types.WebHookInfo>}
   */
  async getActiveWebHook(): Promise<types.WebHookInfo> {
    return await this.webhooks.getActiveWebhook();
  }
 
  /**
   * Отправляет тестовое уведомление
   * @link https://developer.qiwi.com/ru/qiwi-wallet-personal/#hook_test
   *
   * @return {Promise<*>}
   */
  async testActiveWebHook(): Promise<any> {
    return await this.webhooks.testActiveWebhook();
  }
 
  /**
   * Проверяет подпись уведомления вебхука
   * @param {types.WebhookTransaction} transaction Объект уведомления транзакции вебхука
   * @return {Promise<boolean | undefined>}
   */
  async checkWebHookSign(
    transaction: types.WebhookTransaction
  ): Promise<boolean | undefined> {
    return await this.webhooks.checkSign(transaction);
  }
}