Реализация мультипоставщикового дропшиппинга
Работа с несколькими поставщиками решает две задачи: расширение ассортимента и страховочная резервация — когда у основного поставщика кончился товар, заказ уходит к резервному. Технически это значительно сложнее одиночного поставщика: нужно управлять конкурирующими ценами на один артикул, приоритетами, правилами маршрутизации заказов и консолидацией остатков.
Ключевые концепции
Supplier routing — логика выбора поставщика для конкретного заказа. Может учитывать: наличие товара, цену, приоритет, регион доставки, скорость обработки.
Product mapping — один товар в каталоге магазина может соответствовать артикулам нескольких поставщиков. Нужна таблица соответствий.
Price aggregation — если несколько поставщиков предлагают один товар, цена в каталоге формируется на основе лучшей закупочной цены.
Stock consolidation — агрегированный остаток по всем поставщикам или только по приоритетному.
Схема данных
// Один товар → несколько поставщиков
Schema::create('product_supplier_mappings', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained();
$table->foreignId('supplier_id')->constrained('dropship_suppliers');
$table->string('supplier_sku');
$table->integer('priority')->default(10); // меньше = выше приоритет
$table->decimal('supplier_price', 10, 2)->nullable();
$table->integer('supplier_stock')->default(0);
$table->boolean('is_active')->default(true);
$table->timestamp('price_synced_at')->nullable();
$table->timestamp('stock_synced_at')->nullable();
$table->unique(['product_id', 'supplier_id']);
$table->index(['product_id', 'is_active', 'priority']);
});
Маршрутизатор поставщика
class SupplierRouter
{
/**
* Выбрать оптимального поставщика для позиции заказа
*/
public function route(OrderItem $item, RoutingStrategy $strategy): ?ProductSupplierMapping
{
$candidates = ProductSupplierMapping::where('product_id', $item->product_id)
->where('is_active', true)
->where('supplier_stock', '>=', $item->quantity)
->with('supplier')
->orderBy('priority')
->get();
if ($candidates->isEmpty()) {
return null; // нет доступных поставщиков
}
return $strategy->select($candidates, $item);
}
}
// Стратегия: минимальная закупочная цена
class CheapestSupplierStrategy implements RoutingStrategy
{
public function select(Collection $candidates, OrderItem $item): ProductSupplierMapping
{
return $candidates->sortBy('supplier_price')->first();
}
}
// Стратегия: максимальный приоритет (настраивается вручную)
class PrioritySupplierStrategy implements RoutingStrategy
{
public function select(Collection $candidates, OrderItem $item): ProductSupplierMapping
{
return $candidates->sortBy('priority')->first();
}
}
// Стратегия: ближайший склад к адресу доставки (нужны координаты складов)
class NearestWarehouseStrategy implements RoutingStrategy
{
public function select(Collection $candidates, OrderItem $item): ProductSupplierMapping
{
$deliveryCoords = $this->geocode($item->order->delivery_address);
return $candidates->sortBy(function ($mapping) use ($deliveryCoords) {
$warehouse = $mapping->supplier->primaryWarehouse;
return $this->haversineDistance($deliveryCoords, $warehouse->coordinates);
})->first();
}
}
Агрегация цен
class MultiSupplierPriceAggregator
{
/**
* Вычислить розничную цену на основе лучшей закупочной цены среди поставщиков
*/
public function aggregate(Product $product): float
{
$bestMapping = ProductSupplierMapping::where('product_id', $product->id)
->where('is_active', true)
->where('supplier_stock', '>', 0)
->whereNotNull('supplier_price')
->orderBy('supplier_price')
->first();
if (!$bestMapping) {
// Все поставщики не имеют товара — оставляем текущую цену
return $product->price;
}
return $this->calculator->calculate(
supplierPrice: $bestMapping->supplier_price,
marginRule: $this->resolveMarginRule($product, $bestMapping->supplier),
);
}
}
Консолидация остатков
class StockConsolidator
{
public function getDisplayStock(Product $product, string $mode = 'sum'): int
{
$mappings = ProductSupplierMapping::where('product_id', $product->id)
->where('is_active', true)
->get();
return match($mode) {
// Сумма всех поставщиков (показываем 999+, если > 100)
'sum' => min($mappings->sum('supplier_stock'), 9999),
// Только приоритетный поставщик
'priority' => $mappings->sortBy('priority')->first()?->supplier_stock ?? 0,
// Максимум среди поставщиков
'max' => $mappings->max('supplier_stock') ?? 0,
// Булево: есть/нет у хотя бы одного поставщика
'any' => $mappings->where('supplier_stock', '>', 0)->isNotEmpty() ? 1 : 0,
};
}
}
Распределение позиций заказа по поставщикам
Один заказ с несколькими позициями может уходить к разным поставщикам:
class OrderSplitter
{
public function split(Order $order): Collection
{
$groups = collect();
foreach ($order->items as $item) {
$mapping = $this->router->route($item, new PrioritySupplierStrategy());
if (!$mapping) {
throw new NoSupplierAvailableException($item->product);
}
$supplierId = $mapping->supplier_id;
if (!$groups->has($supplierId)) {
$groups->put($supplierId, [
'supplier' => $mapping->supplier,
'items' => collect(),
]);
}
$groups[$supplierId]['items']->push([
'item' => $item,
'supplier_sku' => $mapping->supplier_sku,
]);
}
return $groups;
}
}
Fallback при нехватке товара
Если приоритетный поставщик не может выполнить заказ полностью:
public function routeWithFallback(OrderItem $item): array
{
$remaining = $item->quantity;
$allocations = [];
$mappings = ProductSupplierMapping::where('product_id', $item->product_id)
->where('is_active', true)
->where('supplier_stock', '>', 0)
->orderBy('priority')
->get();
foreach ($mappings as $mapping) {
if ($remaining <= 0) break;
$take = min($remaining, $mapping->supplier_stock);
$allocations[] = ['mapping' => $mapping, 'quantity' => $take];
$remaining -= $take;
}
if ($remaining > 0) {
throw new InsufficientMultiSupplierStockException($item, $remaining);
}
return $allocations;
}
Отчётность по поставщикам
В административной панели отображается:
- Оборот по каждому поставщику
- Среднее время выполнения заказов
- Процент отказов (товара не оказалось после приёма заказа)
- Динамика закупочных цен
Сроки реализации
| Компонент | Срок |
|---|---|
| Схема данных, маппинг поставщиков | 2 дня |
| SupplierRouter + 2–3 стратегии | 3 дня |
| Агрегация цен и консолидация остатков | 2 дня |
| Сплит заказов + fallback | 3 дня |
| Отчётность в админке | 2 дня |
| Тестирование сценариев | 3 дня |
Итого: 15–20 рабочих дней в зависимости от количества поставщиков и сложности правил маршрутизации.







