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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { findCAS } from '@/helpers/cas';
import { parsePrice } from '@/helpers/currency';
import { parseQuantity } from '@/helpers/quantity';
import { firstMap } from '@/helpers/utils';
import { isQuantityObject } from '@/utils/typeGuards/common';
import { ProductBuilder } from '@/utils/ProductBuilder';
import {
isATGResponse,
isResponseOk,
isSearchResultItem,
isValidProductResponse,
isValidSearchResponse,
} from '@/utils/typeGuards/carolina';
import { SupplierBase } from './SupplierBase';
import { getErrorMessage } from '@/helpers/exceptions';
/**
* Implementation of the Carolina Biological Supply Company supplier.
* Provides product search and data extraction functionality for Carolina.com.
*
* @remarks
* Carolina.com uses Oracle ATG Commerce as their ecommerce platform which has a predictable
* output format, though very bulky. But very parseable.
*
* Product search uses the following endpoints:
* - Product Search: `/browse/product-search-results?tab=p&q=acid`
* - Product Search JSON: `/browse/product-search-results?tab=p&format=json&ajax=true&q=acid`
* - Product Details: `/:category/:productName/:productId.pr`
* - Product Details JSON: `/:category/:productName/:productId.pr?format=json&ajax=true`
*
* API Documentation:
* - Swagger UI: `https://www.carolina.com/swagger-ui/`
* - OpenAPI Spec: `https://www.carolina.com/api/rest/openapi.json`
* - WADL: `https://www.carolina.com/api/rest/application.wadl`
*
* Common API Endpoints:
* - Product Quick View: `/api/rest/cb/product/product-quick-view/:id`
* - Product Details: `/api/rest/cb/product/product-details/:id`
* - Search Suggestions: `/api/rest/cb/static/fetch-suggestions-for-global-search/:term`
*
* JSON Format:
* Append `&format=json&ajax=true` to any URL to get JSON response
*
* @category Suppliers
* @source
*/
export class SupplierCarolina
extends SupplierBase<CarolinaSearchResult, Product>
implements ISupplier
{
/** Display name of the supplier */
public static readonly supplierName: string = 'Carolina';
/** Base URL for all API requests */
public static readonly baseURL: string = 'https://www.carolina.com';
// Shipping scope for Carolina
public static readonly shipping: ShippingRange = 'domestic';
// The country code of the supplier.
public static readonly country: CountryCode = 'US';
// The payment methods accepted by the supplier.
public static readonly paymentMethods: PaymentMethod[] = ['mastercard', 'visa'];
/** Cached search results from the last query */
protected queryResults: Array<CarolinaSearchResult> = [];
/** Maximum number of HTTP requests allowed per query */
protected httpRequestHardLimit: number = 50;
/** Counter for HTTP requests made during current query */
protected httpRequstCount: number = 0;
/** Number of requests to process in parallel */
protected maxConcurrentRequests: number = 5;
/** Default headers sent with every request */
protected headers: HeadersInit = {
accept: [
'text/html',
'application/xhtml+xml',
'application/xml;q=0.9',
'image/avif',
'image/webp',
'image/apng',
'*/*;q=0.8',
].join(','),
'accept-language': 'en-US,en;q=0.6',
'cache-control': 'no-cache',
pragma: 'no-cache',
'sec-ch-ua': '"Brave";v="135\', "Not-A.Brand";v="8\', "Chromium";v="135"',
'sec-ch-ua-arch': '"arm"',
'sec-ch-ua-full-version-list':
'"Brave";v="135.0.0.0\', "Not-A.Brand";v="8.0.0.0\', "Chromium";v="135.0.0.0"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-model': '""',
'sec-ch-ua-platform': '"macOS"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'sec-gpc': '1',
'x-requested-with': 'XMLHttpRequest',
};
/**
* Constructs the query parameters for a product search request
* @param query - Search term to look for
* @returns Object containing all required search parameters
* @source
*/
protected makeQueryParams(query: string): CarolinaSearchParams {
return {
tab: 'p',
'product.type': 'Product',
'product.productTypes': 'chemicals',
facetFields: 'product.productTypes',
format: 'json',
ajax: true,
viewSize: 300,
q: query,
} satisfies CarolinaSearchParams;
}
/**
* Executes a product search query and stores results
* Fetches products matching the current search query and updates internal results cache
* @source
*/
protected async queryProducts(
query: string,
limit: number = this.limit,
): Promise<ProductBuilder<Product>[] | void> {
const params = this.makeQueryParams(query);
const searchRequest: unknown = await this.httpGetJson({
path: '/browse/product-search-results',
params,
});
if (!isResponseOk(searchRequest)) {
this.logger.warn('Search response was not OK', { searchRequest });
return;
}
const results = await this.extractSearchResults(searchRequest);
const fuzzResults = this.fuzzyFilterAst<CarolinaSearchResult>(results);
this.logger.debug('Applied fuzzy filter to search results', {
query,
searchRequest,
results,
fuzzResults,
});
return this.initProductBuilders(fuzzResults.slice(0, limit));
}
/**
* Initialize product builders from Carolina search response data.
* Transforms product listings into ProductBuilder instances, handling:
* - Basic product information (title, URL, supplier)
* - Product descriptions and specifications
* - Product IDs and SKUs
* - Pricing information with currency details
* - CAS number extraction from product text
* - Quantity parsing from product names and descriptions
* - Grade/purity level extraction
* - Product categories and classifications
*
* @param data - Array of product listings from search results
* @returns Array of ProductBuilder instances initialized with product data
* @example
* ```typescript
* const results = await this.queryProducts("sodium chloride");
* if (results) {
* const builders = this.initProductBuilders(results);
* // Each builder contains parsed product data
* for (const builder of builders) {
* const product = await builder.build();
* console.log(product.title, product.price, product.grade);
* }
* }
* ```
* @source
*/
protected initProductBuilders(data: CarolinaSearchResult[]): ProductBuilder<Product>[] {
return data.map((result) => {
const builder = new ProductBuilder(this.baseURL).setBasicInfo(
result.productName,
result.productUrl,
this.supplierName,
);
const parsedPrice = parsePrice(result.itemPrice);
if (parsedPrice) builder.setPricing(parsedPrice);
builder.setCAS(findCAS(result['product.shortDescription']));
// Carolina's search response carries a stable per-row id (product.productId,
// e.g. "FAM_889460") — capture it and freeze it as the cache/exclusion key.
builder.setID(result['product.productId']);
builder.setCacheKey(this.getUniqueProductKey(result));
builder.setMatchPercentage(this.matchScoreOf(result));
return builder;
//.setQuantity(result.qtyDiscountAvailable, "1")
//.setDescription(result.shortDescription)
//.setCAS(result.casNumber)
});
}
/**
* Derives the unique product key from a Carolina search result: its
* `product.productId` (e.g. `"FAM_889460"`), which is unique per result row
* and present at query time — unlike the product URL's SKU, which differs.
* @param data - The raw Carolina search result
* @returns The product's `product.productId`
* @example
* ```typescript
* this.getUniqueProductKey(result); // "FAM_889460"
* ```
* @source
*/
protected getUniqueProductKey(data: CarolinaSearchResult): string {
return String(data['product.productId']);
}
/**
* Extracts product search results from a response object
* Navigates through nested response structure to find product listings
* @param response - Raw response object from search request
* @returns Array of validated search result items
* @source
*/
protected extractSearchResults(response: unknown): CarolinaSearchResult[] {
try {
if (!isValidSearchResponse(response)) {
this.logger.warn('Invalid response structure');
return [];
}
const contentFolder = response.contents.ContentFolderZone[0];
if (!contentFolder?.childRules?.[0]?.ContentRuleZone) {
this.logger.warn('No content rules found');
return [];
}
const pageContent = contentFolder.childRules[0].ContentRuleZone[0];
if (!pageContent?.contents?.MainContent) {
this.logger.warn('No MainContent found');
return [];
}
const mainContentItems = pageContent.contents.MainContent;
const pluginSlotContainer = mainContentItems.find((item: MainContentItem) =>
item.contents?.ContentFolderZone?.some(
(folder: ContentFolder) => folder.folderPath === 'Products - Search',
),
);
if (!pluginSlotContainer?.contents?.ContentFolderZone) {
this.logger.warn('No Products - Search folder found');
return [];
}
const productsFolder = pluginSlotContainer.contents.ContentFolderZone.find(
(folder: ContentFolder) => folder.folderPath === 'Products - Search',
);
if (!productsFolder?.childRules?.[0]?.ContentRuleZone) {
this.logger.warn('No content rules in Products folder');
return [];
}
const resultsContainer = productsFolder.childRules[0].ContentRuleZone.find(
(zone: ContentRuleZoneItem): zone is ResultsContainer => {
return (
zone['@type'] === 'ResultsContainer' && 'results' in zone && Array.isArray(zone.results)
);
},
);
if (!resultsContainer) {
this.logger.warn('No results container found');
return [];
}
return resultsContainer.results.filter(isSearchResultItem);
} catch (error) {
this.logger.error(`Error extracting search results: ${getErrorMessage(error)}`, { error });
return [];
}
}
/**
* Extracts the relevant product data from an ATG response object
* Navigates through the nested response structure to find product information
* @param productResponse - Raw ATG response object
* @returns Product data from response or null if invalid/not found
* @example
* ```typescript
* const response = await this.httpGetJson({
* path: `/api/rest/cb/product/product-quick-view/${productId}`
* });
* const productData = this.extractATGResponse(response);
* if (productData) {
* console.log(productData.products[0]);
* }
* ```
* @source
*/
protected extractATGResponse(productResponse: unknown): ATGResponse['response'] | null {
if (!isValidProductResponse(productResponse)) {
return null;
}
try {
const atgResponse = productResponse.contents.MainContent[0].atgResponse;
if (!isATGResponse(atgResponse)) {
return null;
}
return atgResponse.response.response;
} catch (error) {
this.logger.warn(`Error extracting ATG response: ${getErrorMessage(error)}`, { error });
return null;
}
}
/**
* Transforms a Carolina search result into the common Product type
* Makes additional API calls if needed to get complete product details
* @param product - Carolina search result to transform
* @returns Promise resolving to a partial Product object or void if invalid
* @todo Look to see if the response header is 302 and if its sending us to
* https://www.carolina.com/CB_500, if so, stop sending requests to them
* for this search.
* @example
* ```typescript
* const searchResults = await this.queryProducts("acid");
* if (searchResults) {
* const product = await this.getProductData(searchResults[0]);
* if (product) {
* console.log(product.title, product.price);
* }
* }
* ```
* @source
*/
protected async getProductData(
product: ProductBuilder<Product>,
): Promise<ProductBuilder<Product> | void> {
const params = { format: 'json', ajax: 'true' };
return this.getProductDataWithCache(product, async (builder) => {
if (builder instanceof ProductBuilder === false) {
this.logger.warn('Invalid product object - Expected ProductBuilder instance', {
builder,
product,
});
return;
}
const productResponse = await this.httpGetJson({
path: builder.get('url'),
params,
});
if (!isResponseOk(productResponse)) {
this.logger.warn('Product Response status NOT OK', {
productResponse,
builder,
product,
});
return;
}
const atgResponse = this.extractATGResponse(productResponse);
if (!atgResponse) {
this.logger.warn('No ATG response found', {
productResponse,
atgResponse,
builder,
product,
});
return;
}
this.logger.debug('Received ATG product response', {
atgResponse,
productResponse,
builder,
product,
});
const productId = atgResponse.dataLayer.productDetail.productId;
if (!productId) {
this.logger.warn('No product ID found', {
atgResponse,
productResponse,
builder,
product,
});
return;
}
builder.setID(productId);
let productPrice;
if (atgResponse?.dataLayer?.productPrice?.[0]) {
productPrice = parsePrice(atgResponse.dataLayer.productPrice?.[0]);
} else if (
atgResponse?.familyVariyantProductDetails?.schemaJson?.schemaJson?.offers?.length > 0
) {
const productVariantEntry =
atgResponse.familyVariyantProductDetails.schemaJson.schemaJson.offers.find(
(offer) => offer.sku === productId,
);
if (productVariantEntry) {
productPrice = {
currencyCode: productVariantEntry.priceCurrency,
price: productVariantEntry.price,
currencySymbol: '$',
};
}
} else {
this.logger.warn(
'Unable to find the product price in the main product or any variants. contents.MainContent[0].atgResponse.response.response contents',
{ atgResponse, productResponse, builder, product },
);
return;
}
if (!productPrice) {
this.logger.warn('No product price found', {
atgResponse,
product,
builder,
});
return;
}
builder.setPricing(productPrice);
const quantity = firstMap(parseQuantity, [
atgResponse.displayName,
atgResponse.shortDescription,
]);
if (!isQuantityObject(quantity)) {
this.logger.warn('No quantity object found', {
quantity,
builder,
product,
parsedValues: [atgResponse.displayName, atgResponse.shortDescription],
atgResponse,
});
return;
}
builder.setQuantity(quantity);
builder.setCAS(
firstMap(findCAS, [
atgResponse.displayName,
atgResponse.shortDescription,
atgResponse.longDescription,
]),
);
builder.setDescription(atgResponse.shortDescription);
return builder;
});
}
/**
* Selects the title of a product from the search response
* @param data - Product object from search response
* @returns - The title of the product
* @source
*/
protected titleSelector(data: CarolinaSearchResult): string {
return data.productName;
}
}
|