API-Octopart

 view release on metacpan or  search on metacpan

lib/API/Octopart.pm  view on Meta::CPAN

	if ($self->{include_specs})
	{
		$specs = q(
				specs {
				  units
				  value
				  display_value
				  attribute {
				    id
				    name
				    shortname
				    group
				  }
				}
			);
	}

	return $self->octo_query( qq(
		query {
		  search(q: "$part", limit: 3) {
		    results {
		      part {
			manufacturer {
			  name
			}
			mpn
			$specs
			# Brokers are non-authorized dealers. See: https://octopart.com/authorized
			sellers(include_brokers: false) {
			  company {
			    name
			  }
			  offers {
			    click_url
			    inventory_level
			    prices {
			      price
			      currency
			      quantity
			    }
			  }
			}
		      }
		    }
		  }
		}
	));
}

our %_valid_filter_opts = ( map { $_ => 1 } (qw/currency max_moq min_qty max_price mfg seller/) );
sub _parse_part_stock
{
	my ($self, $resp, %opts) = @_;

	foreach my $o (keys %opts)
	{
		die "invalid filter option: '$o'" if (!$_valid_filter_opts{$o});
	}

	my @results;
	foreach my $r (@{ $resp->{data}{search}{results} })
	{
		$r = $r->{part};
		my %part;

		$part{mfg} = $r->{manufacturer}{name};

		if (defined $r->{specs})
		{
			$part{specs} = {
				# Try to map first by shortname, then by unit, then by value if
				# the former are undefined:
				map { 
					defined($_->{attribute}{shortname}) 
						? ($_->{attribute}{shortname} => $_->{value} . "$_->{units}")
						: (
							$_->{units} 
								? ($_->{units} => $_->{value})
								: ($_->{value} => 'true')
						)
				} @{ $r->{specs} }
			},
		}

		# Seller stock and MOQ pricing:
		my %ss;
		foreach my $s (@{ $r->{sellers} })
		{
			foreach my $o (@{ $s->{offers} })
			{
				$ss{$s->{company}{name}}{stock} = $o->{inventory_level};
				foreach my $p (@{ $o->{prices} })
				{
					next if (defined($opts{currency}) && $p->{currency} ne $opts{currency});

					my $moq = $p->{quantity};
					my $price = $p->{price};

					$ss{$s->{company}{name}}{price_tier}{$p->{quantity}} = $price;

					# Find the minimum order quantity and the MOQ price:
					if (!defined($ss{$s->{company}{name}}{moq}) ||
						$ss{$s->{company}{name}}{moq} > $moq)
					{
						$ss{$s->{company}{name}}{moq} = $moq;
						$ss{$s->{company}{name}}{moq_price} = $price;
					}
				}
			}
		}

		$part{sellers} = \%ss;

		push @results, \%part;
	}

	# Delete sellers that do not meet the constraints and
	# add matching results to @ret:
	my @ret;
	foreach my $r (@results)
	{



( run in 0.625 second using v1.01-cache-2.11-cpan-1edf4fed603 )