All files / src bol-client.ts

39% Statements 126/323
33.33% Branches 73/219
29.68% Functions 38/128
41.49% Lines 122/294

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 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109                                                                                                                                                              26x 26x   26x                             5x   5x 2x                   42x 42x                 42x 42x 42x 42x 42x 42x       40x 5x     35x   35x                   35x 1x             34x 34x   34x   34x       29x   25x 25x   24x 21x 21x                         14x 14x 1x   14x 1x   14x     14x     14x     14x     13x         3x     3x                               3x     3x         2x       2x 2x       1x             1x 1x       2x       2x 2x       1x             1x 1x       2x             2x 2x                                                           1x 1x 1x   1x 1x   1x     1x         1x     1x         2x       2x 2x                                                             1x 1x 1x   1x 1x   1x     1x         1x     1x         1x             1x 1x                             3x 3x 2x   3x 1x   3x 3x 3x     3x         1x     1x                                   1x       1x     1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1x       1x                                                                 39x 39x           39x       40x 39x 40x 40x 40x 9x     39x   39x   39x 41x   41x 37x 1x   36x     4x 2x 2x     2x 2x     2x                      
import { TtlCache } from "./cache.js";
import type {
  Order,
  OrdersResponse,
  CancellationRequest,
  Offer,
  CreateOfferRequest,
  UpdateOfferRequest,
  UpdateOfferPriceRequest,
  UpdateOfferStockRequest,
  CreateOfferExportRequest,
  CreateUnpublishedOfferReportRequest,
  Shipment,
  ShipmentsResponse,
  CreateShipmentRequest,
  InvoiceRequestsResponse,
  Return,
  ReturnsResponse,
  HandleReturnRequest,
  CreateReturnRequest,
  InvoicesResponse,
  InvoiceSpecificationResponse,
  Commission,
  BulkCommissionRequest,
  BulkCommissionResponse,
  CommissionProductsRequest,
  BulkCommissionRatesResponse,
  ProcessStatus,
  ProcessStatusResponse,
  BulkProcessStatusRequest,
  ProcessStatusEventType,
  ProductCategoriesResponse,
  ProductListRequest,
  ProductListResponse,
  ProductListFiltersResponse,
  ProductAssetsResponse,
  CompetingOffersResponse,
  ProductPlacementResponse,
  PriceStarBoundaries,
  ProductIdsResponse,
  ProductRatingsResponse,
  CatalogProduct,
  CreateProductContentRequest,
  UploadReportResponse,
  ChunkRecommendationsRequest,
  ChunkRecommendationsResponse,
  OfferInsightsResponse,
  PerformanceIndicatorsResponse,
  ProductRanksResponse,
  SalesForecastResponse,
  SearchTermsResponse,
  InventoryResponse,
  PromotionsResponse,
  PromotionResponse,
  PromotionProductsResponse,
  ReplenishmentsResponse,
  ReplenishmentResponse,
  CreateReplenishmentRequest,
  UpdateReplenishmentRequest,
  DeliveryDatesResponse,
  PickupTimeSlotsRequest,
  PickupTimeSlotsResponse,
  RequestProductDestinationsRequest,
  ProductDestinationsResponse,
  ProductLabelsRequest,
  RetailerInformationResponse,
  ShippingLabelRequest,
  DeliveryOptionsRequest,
  DeliveryOptionsResponse,
  SubscriptionsResponse,
  SubscriptionResponse,
  SubscriptionRequest,
  KeySetResponse,
  ChangeTransportRequest,
} from "./types.js";
 
export class BolApiError extends Error {
  constructor(
    message: string,
    readonly status: number,
    readonly details?: unknown,
  ) {
    super(message);
  }
}
 
export interface RetryOptions {
  maxRetries: number;
}
 
interface TokenResponse {
  access_token: string;
  token_type: string;
  expires_in: number;
  scope: string;
}
 
const DEFAULT_RETRY: RetryOptions = { maxRetries: 3 };
 
const sleep = (ms: number): Promise<void> =>
  new Promise((resolve) => setTimeout(resolve, ms));
 
export class BolClient {
  private readonly baseUrl: string;
  private readonly clientId: string;
  private readonly clientSecret: string;
  private readonly retry: RetryOptions;
  private readonly cache: TtlCache;
  private readonly cachingEnabled: boolean;
 
  private accessToken: string | null = null;
  private tokenExpiresAt = 0;
 
  constructor(
    clientId: string,
    clientSecret: string,
    baseUrl = "https://api.bol.com/retailer",
    cacheTtlMs?: number,
    retry: RetryOptions = DEFAULT_RETRY,
  ) {
    this.baseUrl = baseUrl.replace(/\/$/, "");
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.retry = retry;
    this.cachingEnabled = cacheTtlMs !== 0;
    this.cache = new TtlCache(cacheTtlMs ?? 120_000);
  }
 
  private async authenticate(): Promise<string> {
    if (this.accessToken && Date.now() < this.tokenExpiresAt) {
      return this.accessToken;
    }
 
    const credentials = Buffer.from(`${this.clientId}:${this.clientSecret}`).toString("base64");
 
    const response = await fetch("https://login.bol.com/token", {
      method: "POST",
      headers: {
        "Authorization": `Basic ${credentials}`,
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/json",
      },
      body: "grant_type=client_credentials",
    });
 
    if (!response.ok) {
      throw new BolApiError(
        `Authentication failed: ${response.status} ${response.statusText}`,
        response.status,
        await BolClient.parseBody(response),
      );
    }
 
    const data = (await response.json()) as TokenResponse;
    this.accessToken = data.access_token;
    // Refresh 60 seconds before actual expiry
    this.tokenExpiresAt = Date.now() + (data.expires_in - 60) * 1000;
 
    return this.accessToken;
  }
 
  private async cachedRequest<T>(cacheKey: string, ttlMs: number, fetcher: () => Promise<T>): Promise<T> {
    if (!this.cachingEnabled || ttlMs <= 0) return fetcher();
 
    const cached = this.cache.get<T>(cacheKey);
    if (cached !== undefined) return cached;
 
    const result = await fetcher();
    this.cache.set(cacheKey, result, ttlMs);
    return result;
  }
 
  // --- Orders ---
 
  async getOrders(
    page = 1,
    fulfilmentMethod?: string,
    status?: string,
    changeIntervalMinute?: number,
    latestChangeDate?: string,
    vvbOnly?: boolean,
  ): Promise<OrdersResponse> {
    const query = new URLSearchParams({ page: String(page) });
    if (fulfilmentMethod) {
      query.set("fulfilment-method", fulfilmentMethod);
    }
    if (status) {
      query.set("status", status);
    }
    Iif (changeIntervalMinute !== undefined) {
      query.set("change-interval-minute", String(changeIntervalMinute));
    }
    Iif (latestChangeDate) {
      query.set("latest-change-date", latestChangeDate);
    }
    Iif (vvbOnly !== undefined) {
      query.set("vvb-only", String(vvbOnly));
    }
    return this.cachedRequest(
      `orders:${page}:${fulfilmentMethod ?? ""}:${status ?? ""}:${changeIntervalMinute ?? ""}:${latestChangeDate ?? ""}:${vvbOnly ?? ""}`,
      60_000,
      () => this.request<OrdersResponse>(`/orders?${query.toString()}`),
    );
  }
 
  async getOrder(orderId: string): Promise<Order> {
    return this.cachedRequest(
      `order:${orderId}`,
      60_000,
      () => this.request<Order>(`/orders/${encodeURIComponent(orderId)}`),
    );
  }
 
  async cancelOrderItems(data: CancellationRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>("/orders/cancellation", {
      method: "PUT",
      body: JSON.stringify(data),
    });
    this.cache.invalidate("order:");
    return result;
  }
 
  // --- Offers ---
 
  async getOffer(offerId: string): Promise<Offer> {
    return this.cachedRequest(
      `offer:${offerId}`,
      120_000,
      () => this.request<Offer>(`/offers/${encodeURIComponent(offerId)}`),
    );
  }
 
  async createOffer(data: CreateOfferRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>("/offers", {
      method: "POST",
      body: JSON.stringify(data),
    });
    this.cache.invalidate("offer:");
    return result;
  }
 
  async updateOffer(offerId: string, data: UpdateOfferRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>(
      `/offers/${encodeURIComponent(offerId)}`,
      {
        method: "PUT",
        body: JSON.stringify(data),
      },
    );
    this.cache.invalidate(`offer:${offerId}`);
    return result;
  }
 
  async deleteOffer(offerId: string): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>(
      `/offers/${encodeURIComponent(offerId)}`,
      { method: "DELETE" },
    );
    this.cache.invalidate(`offer:${offerId}`);
    return result;
  }
 
  async updateOfferPrice(offerId: string, data: UpdateOfferPriceRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>(
      `/offers/${encodeURIComponent(offerId)}/price`,
      {
        method: "PUT",
        body: JSON.stringify(data),
      },
    );
    this.cache.invalidate(`offer:${offerId}`);
    return result;
  }
 
  async updateOfferStock(offerId: string, data: UpdateOfferStockRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>(
      `/offers/${encodeURIComponent(offerId)}/stock`,
      {
        method: "PUT",
        body: JSON.stringify(data),
      },
    );
    this.cache.invalidate(`offer:${offerId}`);
    return result;
  }
 
  async requestOfferExport(data?: CreateOfferExportRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>("/offers/export", {
      method: "POST",
      body: JSON.stringify(data ?? { format: "CSV" }),
    });
    return result;
  }
 
  async getOfferExport(reportId: string): Promise<string> {
    return this.request<string>(`/offers/export/${encodeURIComponent(reportId)}`);
  }
 
  async requestUnpublishedOfferReport(): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>("/offers/unpublished", {
      method: "POST",
      body: JSON.stringify({ format: "CSV" } satisfies CreateUnpublishedOfferReportRequest),
    });
    return result;
  }
 
  async getUnpublishedOfferReport(reportId: string): Promise<string> {
    return this.request<string>(`/offers/unpublished/${encodeURIComponent(reportId)}`);
  }
 
  // --- Shipments ---
 
  async getShipments(page = 1, orderId?: string, fulfilmentMethod?: string): Promise<ShipmentsResponse> {
    const query = new URLSearchParams({ page: String(page) });
    Eif (orderId) {
      query.set("order-id", orderId);
    }
    Eif (fulfilmentMethod) {
      query.set("fulfilment-method", fulfilmentMethod);
    }
    return this.cachedRequest(
      `shipments:${page}:${orderId ?? ""}:${fulfilmentMethod ?? ""}`,
      60_000,
      () => this.request<ShipmentsResponse>(`/shipments?${query.toString()}`),
    );
  }
 
  async getShipment(shipmentId: string): Promise<Shipment> {
    return this.cachedRequest(
      `shipment:${shipmentId}`,
      120_000,
      () => this.request<Shipment>(`/shipments/${encodeURIComponent(shipmentId)}`),
    );
  }
 
  async createShipment(data: CreateShipmentRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>("/shipments", {
      method: "POST",
      body: JSON.stringify(data),
    });
    this.cache.invalidate("shipment");
    return result;
  }
 
  async getShipmentInvoiceRequests(page = 1, shipmentId?: string, state?: string): Promise<InvoiceRequestsResponse> {
    const query = new URLSearchParams({ page: String(page) });
    if (shipmentId) {
      query.set("shipment-id", shipmentId);
    }
    if (state) {
      query.set("state", state);
    }
    return this.cachedRequest(
      `shipment-invoices:${page}:${shipmentId ?? ""}:${state ?? ""}`,
      60_000,
      () => this.request<InvoiceRequestsResponse>(`/shipments/invoices/requests?${query.toString()}`),
    );
  }
 
  async uploadShipmentInvoice(shipmentId: string, invoice: string): Promise<ProcessStatus> {
    return this.request<ProcessStatus>(
      `/shipments/invoices/${encodeURIComponent(shipmentId)}`,
      {
        method: "POST",
        body: invoice,
      },
    );
  }
 
  // --- Returns ---
 
  async getReturns(page = 1, handled?: boolean, fulfilmentMethod?: string): Promise<ReturnsResponse> {
    const query = new URLSearchParams({ page: String(page) });
    Eif (handled !== undefined) {
      query.set("handled", String(handled));
    }
    Eif (fulfilmentMethod) {
      query.set("fulfilment-method", fulfilmentMethod);
    }
    return this.cachedRequest(
      `returns:${page}:${handled ?? ""}:${fulfilmentMethod ?? ""}`,
      60_000,
      () => this.request<ReturnsResponse>(`/returns?${query.toString()}`),
    );
  }
 
  async getReturn(returnId: string): Promise<Return> {
    return this.cachedRequest(
      `return:${returnId}`,
      60_000,
      () => this.request<Return>(`/returns/${encodeURIComponent(returnId)}`),
    );
  }
 
  async handleReturn(rmaId: string, data: HandleReturnRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>(
      `/returns/${encodeURIComponent(rmaId)}`,
      {
        method: "PUT",
        body: JSON.stringify(data),
      },
    );
    this.cache.invalidate("return:");
    return result;
  }
 
  async createReturn(data: CreateReturnRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>("/returns", {
      method: "POST",
      body: JSON.stringify(data),
    });
    this.cache.invalidate("return:");
    return result;
  }
 
  // --- Invoices ---
 
  async getInvoices(periodStartDate?: string, periodEndDate?: string): Promise<InvoicesResponse> {
    const query = new URLSearchParams();
    if (periodStartDate) {
      query.set("period-start-date", periodStartDate);
    }
    if (periodEndDate) {
      query.set("period-end-date", periodEndDate);
    }
    const qs = query.toString();
    const path = qs ? `/invoices?${qs}` : "/invoices";
    return this.cachedRequest(
      `invoices:${periodStartDate ?? ""}:${periodEndDate ?? ""}`,
      300_000,
      () => this.request<InvoicesResponse>(path),
    );
  }
 
  async getInvoice(invoiceId: string): Promise<Record<string, unknown>> {
    return this.cachedRequest(
      `invoice:${invoiceId}`,
      300_000,
      () => this.request<Record<string, unknown>>(`/invoices/${encodeURIComponent(invoiceId)}`),
    );
  }
 
  async getInvoiceSpecification(invoiceId: string, page = 1): Promise<InvoiceSpecificationResponse> {
    const query = new URLSearchParams({ page: String(page) });
    return this.cachedRequest(
      `invoice-spec:${invoiceId}:${page}`,
      300_000,
      () => this.request<InvoiceSpecificationResponse>(
        `/invoices/${encodeURIComponent(invoiceId)}/specification?${query.toString()}`,
      ),
    );
  }
 
  // --- Commissions ---
 
  async getCommission(ean: string, condition: string, unitPrice: number): Promise<Commission> {
    const query = new URLSearchParams({
      condition,
      "unit-price": String(unitPrice),
    });
    return this.cachedRequest(
      `commission:${ean}:${condition}:${unitPrice}`,
      300_000,
      () => this.request<Commission>(`/commission/${encodeURIComponent(ean)}?${query.toString()}`),
    );
  }
 
  async getBulkCommissions(data: BulkCommissionRequest): Promise<BulkCommissionResponse> {
    return this.request<BulkCommissionResponse>("/commission", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }
 
  async getCommissionRates(data: CommissionProductsRequest): Promise<BulkCommissionRatesResponse> {
    return this.request<BulkCommissionRatesResponse>("/commissions", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }
 
  // --- Products ---
 
  async getProductCategories(language?: string): Promise<ProductCategoriesResponse> {
    return this.cachedRequest(
      `product-categories:${language ?? ""}`,
      600_000,
      () => this.request<ProductCategoriesResponse>(
        "/products/categories",
        language ? { headers: { "Accept-Language": language } } : undefined,
      ),
    );
  }
 
  async getProductList(data: ProductListRequest): Promise<ProductListResponse> {
    const { language, ...body } = data;
    const headers: Record<string, string> = {};
    if (language) {
      headers["Accept-Language"] = language;
    }
    return this.request<ProductListResponse>("/products/list", {
      method: "POST",
      body: JSON.stringify(body),
      headers,
    });
  }
 
  async getProductListFilters(
    countryCode?: string,
    searchTerm?: string,
    categoryId?: string,
    language?: string,
  ): Promise<ProductListFiltersResponse> {
    const query = new URLSearchParams();
    if (countryCode) query.set("country-code", countryCode);
    if (searchTerm) query.set("search-term", searchTerm);
    if (categoryId) query.set("category-id", categoryId);
    const headers: Record<string, string> = {};
    if (language) headers["Accept-Language"] = language;
    return this.cachedRequest(
      `product-list-filters:${countryCode ?? ""}:${searchTerm ?? ""}:${categoryId ?? ""}`,
      300_000,
      () => this.request<ProductListFiltersResponse>(
        `/products/list-filters?${query.toString()}`,
        Object.keys(headers).length > 0 ? { headers } : undefined,
      ),
    );
  }
 
  async getProductAssets(ean: string, usage?: string): Promise<ProductAssetsResponse> {
    const query = new URLSearchParams();
    if (usage) query.set("usage", usage);
    const qs = query.toString();
    return this.cachedRequest(
      `product-assets:${ean}:${usage ?? ""}`,
      300_000,
      () => this.request<ProductAssetsResponse>(
        `/products/${encodeURIComponent(ean)}/assets${qs ? `?${qs}` : ""}`,
      ),
    );
  }
 
  async getCompetingOffers(
    ean: string,
    page = 1,
    countryCode?: string,
    bestOfferOnly?: boolean,
    condition?: string,
    includeRefurbishedConditions?: boolean,
  ): Promise<CompetingOffersResponse> {
    const query = new URLSearchParams({ page: String(page) });
    if (countryCode) query.set("country-code", countryCode);
    if (bestOfferOnly !== undefined) query.set("best-offer-only", String(bestOfferOnly));
    if (condition) query.set("condition", condition);
    if (includeRefurbishedConditions !== undefined) query.set("include-refurbished-conditions", String(includeRefurbishedConditions));
    return this.cachedRequest(
      `competing-offers:${ean}:${page}:${countryCode ?? ""}:${bestOfferOnly ?? ""}:${condition ?? ""}:${includeRefurbishedConditions ?? ""}`,
      120_000,
      () => this.request<CompetingOffersResponse>(
        `/products/${encodeURIComponent(ean)}/offers?${query.toString()}`,
      ),
    );
  }
 
  async getProductPlacement(ean: string, countryCode?: string, language?: string): Promise<ProductPlacementResponse> {
    const query = new URLSearchParams();
    if (countryCode) query.set("country-code", countryCode);
    const headers: Record<string, string> = {};
    if (language) headers["Accept-Language"] = language;
    const qs = query.toString();
    return this.cachedRequest(
      `product-placement:${ean}:${countryCode ?? ""}`,
      300_000,
      () => this.request<ProductPlacementResponse>(
        `/products/${encodeURIComponent(ean)}/placement${qs ? `?${qs}` : ""}`,
        Object.keys(headers).length > 0 ? { headers } : undefined,
      ),
    );
  }
 
  async getPriceStarBoundaries(ean: string): Promise<PriceStarBoundaries> {
    return this.cachedRequest(
      `price-star-boundaries:${ean}`,
      300_000,
      () => this.request<PriceStarBoundaries>(
        `/products/${encodeURIComponent(ean)}/price-star-boundaries`,
      ),
    );
  }
 
  async getProductIds(ean: string): Promise<ProductIdsResponse> {
    return this.cachedRequest(
      `product-ids:${ean}`,
      600_000,
      () => this.request<ProductIdsResponse>(
        `/products/${encodeURIComponent(ean)}/product-ids`,
      ),
    );
  }
 
  async getProductRatings(ean: string): Promise<ProductRatingsResponse> {
    return this.cachedRequest(
      `product-ratings:${ean}`,
      300_000,
      () => this.request<ProductRatingsResponse>(
        `/products/${encodeURIComponent(ean)}/ratings`,
      ),
    );
  }
 
  // --- Product Content ---
 
  async getCatalogProduct(ean: string, language?: string): Promise<CatalogProduct> {
    const headers: Record<string, string> = {};
    if (language) headers["Accept-Language"] = language;
    return this.cachedRequest(
      `catalog-product:${ean}:${language ?? ""}`,
      300_000,
      () => this.request<CatalogProduct>(
        `/content/catalog-products/${encodeURIComponent(ean)}`,
        Object.keys(headers).length > 0 ? { headers } : undefined,
      ),
    );
  }
 
  async createProductContent(data: CreateProductContentRequest): Promise<ProcessStatus> {
    return this.request<ProcessStatus>("/content/products", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }
 
  async getUploadReport(uploadId: string): Promise<UploadReportResponse> {
    return this.cachedRequest(
      `upload-report:${uploadId}`,
      120_000,
      () => this.request<UploadReportResponse>(
        `/content/upload-report/${encodeURIComponent(uploadId)}`,
      ),
    );
  }
 
  async getChunkRecommendations(data: ChunkRecommendationsRequest): Promise<ChunkRecommendationsResponse> {
    return this.request<ChunkRecommendationsResponse>("/content/chunk-recommendations", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }
 
  // --- Insights ---
 
  async getOfferInsights(
    offerId: string,
    period: string,
    numberOfPeriods: number,
    name: string,
  ): Promise<OfferInsightsResponse> {
    const query = new URLSearchParams({
      "offer-id": offerId,
      period,
      "number-of-periods": String(numberOfPeriods),
      name,
    });
    return this.cachedRequest(
      `offer-insights:${offerId}:${period}:${numberOfPeriods}:${name}`,
      120_000,
      () => this.request<OfferInsightsResponse>(`/insights/offer?${query.toString()}`),
    );
  }
 
  async getPerformanceIndicators(
    name: string,
    year: string,
    week: string,
  ): Promise<PerformanceIndicatorsResponse> {
    const query = new URLSearchParams({ name, year, week });
    return this.cachedRequest(
      `performance-indicators:${name}:${year}:${week}`,
      300_000,
      () => this.request<PerformanceIndicatorsResponse>(
        `/insights/performance/indicator?${query.toString()}`,
      ),
    );
  }
 
  async getProductRanks(
    ean: string,
    date: string,
    type?: string,
    page = 1,
    language?: string,
  ): Promise<ProductRanksResponse> {
    const query = new URLSearchParams({ ean, date, page: String(page) });
    if (type) query.set("type", type);
    const headers: Record<string, string> = {};
    if (language) headers["Accept-Language"] = language;
    return this.cachedRequest(
      `product-ranks:${ean}:${date}:${type ?? ""}:${page}`,
      300_000,
      () => this.request<ProductRanksResponse>(
        `/insights/product-ranks?${query.toString()}`,
        Object.keys(headers).length > 0 ? { headers } : undefined,
      ),
    );
  }
 
  async getSalesForecast(offerId: string, weeksAhead: number): Promise<SalesForecastResponse> {
    const query = new URLSearchParams({
      "offer-id": offerId,
      "weeks-ahead": String(weeksAhead),
    });
    return this.cachedRequest(
      `sales-forecast:${offerId}:${weeksAhead}`,
      300_000,
      () => this.request<SalesForecastResponse>(`/insights/sales-forecast?${query.toString()}`),
    );
  }
 
  async getSearchTerms(
    searchTerm: string,
    period: string,
    numberOfPeriods: number,
    relatedSearchTerms?: boolean,
  ): Promise<SearchTermsResponse> {
    const query = new URLSearchParams({
      "search-term": searchTerm,
      period,
      "number-of-periods": String(numberOfPeriods),
    });
    if (relatedSearchTerms !== undefined) {
      query.set("related-search-terms", String(relatedSearchTerms));
    }
    return this.cachedRequest(
      `search-terms:${searchTerm}:${period}:${numberOfPeriods}:${relatedSearchTerms ?? ""}`,
      300_000,
      () => this.request<SearchTermsResponse>(`/insights/search-terms?${query.toString()}`),
    );
  }
 
  // --- Inventory ---
 
  async getInventory(
    page = 1,
    quantity?: string,
    stock?: string,
    state?: string,
    query?: string,
  ): Promise<InventoryResponse> {
    const params = new URLSearchParams({ page: String(page) });
    if (quantity) params.set("quantity", quantity);
    if (stock) params.set("stock", stock);
    if (state) params.set("state", state);
    if (query) params.set("query", query);
    return this.cachedRequest(
      `inventory:${page}:${quantity ?? ""}:${stock ?? ""}:${state ?? ""}:${query ?? ""}`,
      120_000,
      () => this.request<InventoryResponse>(`/inventory?${params.toString()}`),
    );
  }
 
  // --- Promotions ---
 
  async getPromotions(promotionType: string, page = 1): Promise<PromotionsResponse> {
    const query = new URLSearchParams({
      "promotion-type": promotionType,
      page: String(page),
    });
    return this.cachedRequest(
      `promotions:${promotionType}:${page}`,
      120_000,
      () => this.request<PromotionsResponse>(`/promotions?${query.toString()}`),
    );
  }
 
  async getPromotion(promotionId: string): Promise<PromotionResponse> {
    return this.cachedRequest(
      `promotion:${promotionId}`,
      120_000,
      () => this.request<PromotionResponse>(`/promotions/${encodeURIComponent(promotionId)}`),
    );
  }
 
  async getPromotionProducts(promotionId: string, page = 1): Promise<PromotionProductsResponse> {
    const query = new URLSearchParams({ page: String(page) });
    return this.cachedRequest(
      `promotion-products:${promotionId}:${page}`,
      120_000,
      () => this.request<PromotionProductsResponse>(
        `/promotions/${encodeURIComponent(promotionId)}/products?${query.toString()}`,
      ),
    );
  }
 
  // --- Replenishments ---
 
  async getReplenishments(
    page = 1,
    reference?: string,
    ean?: string,
    startDate?: string,
    endDate?: string,
    states?: string[],
  ): Promise<ReplenishmentsResponse> {
    const query = new URLSearchParams({ page: String(page) });
    if (reference) query.set("reference", reference);
    if (ean) query.set("ean", ean);
    if (startDate) query.set("start-date", startDate);
    if (endDate) query.set("end-date", endDate);
    if (states) {
      for (const s of states) query.append("state", s);
    }
    return this.cachedRequest(
      `replenishments:${page}:${reference ?? ""}:${ean ?? ""}:${startDate ?? ""}:${endDate ?? ""}:${states?.join(",") ?? ""}`,
      120_000,
      () => this.request<ReplenishmentsResponse>(`/replenishments?${query.toString()}`),
    );
  }
 
  async getReplenishment(replenishmentId: string): Promise<ReplenishmentResponse> {
    return this.cachedRequest(
      `replenishment:${replenishmentId}`,
      120_000,
      () => this.request<ReplenishmentResponse>(
        `/replenishments/${encodeURIComponent(replenishmentId)}`,
      ),
    );
  }
 
  async createReplenishment(data: CreateReplenishmentRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>("/replenishments", {
      method: "POST",
      body: JSON.stringify(data),
    });
    this.cache.invalidate("replenishment");
    return result;
  }
 
  async updateReplenishment(replenishmentId: string, data: UpdateReplenishmentRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>(
      `/replenishments/${encodeURIComponent(replenishmentId)}`,
      {
        method: "PUT",
        body: JSON.stringify(data),
      },
    );
    this.cache.invalidate(`replenishment:${replenishmentId}`);
    return result;
  }
 
  async getDeliveryDates(): Promise<DeliveryDatesResponse> {
    return this.cachedRequest(
      "delivery-dates",
      300_000,
      () => this.request<DeliveryDatesResponse>("/replenishments/delivery-dates"),
    );
  }
 
  async getPickupTimeSlots(data: PickupTimeSlotsRequest): Promise<PickupTimeSlotsResponse> {
    return this.request<PickupTimeSlotsResponse>("/replenishments/pickup-time-slots", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }
 
  async requestProductDestinations(data: RequestProductDestinationsRequest): Promise<ProcessStatus> {
    return this.request<ProcessStatus>("/replenishments/product-destinations", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }
 
  async getProductDestinations(productDestinationsId: string): Promise<ProductDestinationsResponse> {
    return this.cachedRequest(
      `product-destinations:${productDestinationsId}`,
      120_000,
      () => this.request<ProductDestinationsResponse>(
        `/replenishments/product-destinations/${encodeURIComponent(productDestinationsId)}`,
      ),
    );
  }
 
  async requestProductLabels(data: ProductLabelsRequest): Promise<string> {
    return this.request<string>("/replenishments/product-labels", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }
 
  async getLoadCarrierLabels(replenishmentId: string, labelType?: string): Promise<string> {
    const query = new URLSearchParams();
    if (labelType) query.set("label-type", labelType);
    const qs = query.toString();
    return this.request<string>(
      `/replenishments/${encodeURIComponent(replenishmentId)}/load-carrier-labels${qs ? `?${qs}` : ""}`,
    );
  }
 
  async getPickList(replenishmentId: string): Promise<string> {
    return this.request<string>(
      `/replenishments/${encodeURIComponent(replenishmentId)}/pick-list`,
    );
  }
 
  // --- Retailers ---
 
  async getRetailerInformation(retailerId = "current"): Promise<RetailerInformationResponse> {
    return this.cachedRequest(
      `retailer:${retailerId}`,
      600_000,
      () => this.request<RetailerInformationResponse>(
        `/retailers/${encodeURIComponent(retailerId)}`,
      ),
    );
  }
 
  // --- Shipping Labels ---
 
  async createShippingLabel(data: ShippingLabelRequest): Promise<ProcessStatus> {
    return this.request<ProcessStatus>("/shipping-labels", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }
 
  async getDeliveryOptions(data: DeliveryOptionsRequest): Promise<DeliveryOptionsResponse> {
    return this.request<DeliveryOptionsResponse>("/shipping-labels/delivery-options", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }
 
  async getShippingLabel(shippingLabelId: string): Promise<string> {
    return this.request<string>(
      `/shipping-labels/${encodeURIComponent(shippingLabelId)}`,
    );
  }
 
  // --- Subscriptions ---
 
  async getSubscriptions(): Promise<SubscriptionsResponse> {
    return this.cachedRequest(
      "subscriptions",
      120_000,
      () => this.request<SubscriptionsResponse>("/subscriptions"),
    );
  }
 
  async createSubscription(data: SubscriptionRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>("/subscriptions", {
      method: "POST",
      body: JSON.stringify(data),
    });
    this.cache.invalidate("subscription");
    return result;
  }
 
  async getSubscription(subscriptionId: string): Promise<SubscriptionResponse> {
    return this.cachedRequest(
      `subscription:${subscriptionId}`,
      120_000,
      () => this.request<SubscriptionResponse>(
        `/subscriptions/${encodeURIComponent(subscriptionId)}`,
      ),
    );
  }
 
  async updateSubscription(subscriptionId: string, data: SubscriptionRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>(
      `/subscriptions/${encodeURIComponent(subscriptionId)}`,
      {
        method: "PUT",
        body: JSON.stringify(data),
      },
    );
    this.cache.invalidate(`subscription:${subscriptionId}`);
    return result;
  }
 
  async deleteSubscription(subscriptionId: string): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>(
      `/subscriptions/${encodeURIComponent(subscriptionId)}`,
      { method: "DELETE" },
    );
    this.cache.invalidate(`subscription:${subscriptionId}`);
    return result;
  }
 
  async getSignatureKeys(): Promise<KeySetResponse> {
    return this.cachedRequest(
      "signature-keys",
      600_000,
      () => this.request<KeySetResponse>("/subscriptions/signature-keys"),
    );
  }
 
  async testSubscription(subscriptionId: string): Promise<ProcessStatus> {
    return this.request<ProcessStatus>(
      `/subscriptions/test/${encodeURIComponent(subscriptionId)}`,
      { method: "POST" },
    );
  }
 
  // --- Transports ---
 
  async updateTransport(transportId: string, data: ChangeTransportRequest): Promise<ProcessStatus> {
    const result = await this.request<ProcessStatus>(
      `/transports/${encodeURIComponent(transportId)}`,
      {
        method: "PUT",
        body: JSON.stringify(data),
      },
    );
    return result;
  }
 
  // --- Process Status ---
 
  private get sharedBaseUrl(): string {
    return this.baseUrl.replace(/\/retailer$/, "/shared");
  }
 
  async getProcessStatus(processStatusId: string): Promise<ProcessStatus> {
    return this.requestUrl<ProcessStatus>(
      `${this.sharedBaseUrl}/process-status/${encodeURIComponent(processStatusId)}`,
    );
  }
 
  async getProcessStatusByEntityId(
    entityId: string,
    eventType: ProcessStatusEventType,
    page?: number,
  ): Promise<ProcessStatusResponse> {
    const params = new URLSearchParams({
      "entity-id": entityId,
      "event-type": eventType,
    });
    if (page) params.set("page", String(page));
    return this.requestUrl<ProcessStatusResponse>(
      `${this.sharedBaseUrl}/process-status?${params.toString()}`,
    );
  }
 
  async getProcessStatusBulk(processStatusIds: string[]): Promise<ProcessStatusResponse> {
    const body: BulkProcessStatusRequest = {
      processStatusQueries: processStatusIds.map((id) => ({ processStatusId: id })),
    };
    return this.requestUrl<ProcessStatusResponse>(
      `${this.sharedBaseUrl}/process-status`,
      { method: "POST", body: JSON.stringify(body) },
    );
  }
 
  // --- Private ---
 
  private static async parseBody(response: Response): Promise<unknown> {
    const contentType = response.headers.get("content-type") ?? "";
    return contentType.includes("application/json") || contentType.includes("application/vnd.retailer")
      ? response.json().catch(() => null)
      : response.text().catch(() => "");
  }
 
  private async request<T>(path: string, init?: RequestInit): Promise<T> {
    return this.requestUrl<T>(`${this.baseUrl}${path}`, init);
  }
 
  private async requestUrl<T>(url: string, init?: RequestInit): Promise<T> {
    const token = await this.authenticate();
    const headers = new Headers(init?.headers);
    headers.set("Authorization", `Bearer ${token}`);
    headers.set("Accept", "application/vnd.retailer.v10+json");
    if (init?.body) {
      headers.set("Content-Type", "application/vnd.retailer.v10+json");
    }
 
    const requestInit: RequestInit = { ...init, headers };
 
    const maxRetries = Math.max(0, this.retry.maxRetries);
 
    for (let attempt = 0; attempt <= maxRetries; attempt++) {
      const response = await fetch(url, requestInit);
 
      if (response.ok || response.status === 204 || response.status === 202) {
        if (response.status === 204) {
          return null as T;
        }
        return await BolClient.parseBody(response) as T;
      }
 
      if (response.status === 429 && attempt < maxRetries) {
        const retryAfter = response.headers.get("retry-after");
        const delayMs = retryAfter
          ? parseInt(retryAfter, 10) * 1000
          : Math.pow(2, attempt) * 1000;
        await sleep(delayMs);
        continue;
      }
 
      throw new BolApiError(
        `Bol.com API request failed: ${response.status} ${response.statusText}`,
        response.status,
        await BolClient.parseBody(response),
      );
    }
 
    /* v8 ignore next */
    throw new Error("Retry loop exited unexpectedly");
  }
}