where('id', (int)$goods['template_id'])->find(); if (!$source) { throw new Exception('商品模板已失效'); } if ($licenseType === 'buyout') { $dup = (new Template())->where('source_template_id', $source['id']) ->where('license_type', 'market_buyout') ->find(); if ($dup) { throw new Exception('本厂已买断该模板,无需重复购买'); } } $marketCfg = Config::get('ps.market') ?: []; $commission = isset($marketCfg['commission_percent']) ? (int)$marketCfg['commission_percent'] : 0; if ($commission < 0) { $commission = 0; } if ($commission > 100) { $commission = 100; } Db::startTrans(); try { if ($price > 0) { Factory::changeScore($factoryId, -$price, 'market_buy', $goodsId, '购买模板:' . $goods['title'], $userId); $sellerId = (int)$goods['factory_id']; if ($sellerId > 0) { $sellerGain = (int)floor($price * (100 - $commission) / 100); if ($sellerGain > 0) { Factory::changeScore($sellerId, $sellerGain, 'market_sell', $goodsId, '模板售出:' . $goods['title'], 0); } } } $copy = self::importCopy($source, $goods, $licenseType, $userId, $factoryId); $order = new MarketOrder(); $order->allowField(true)->save([ 'order_no' => 'M' . date('YmdHis') . Random::numeric(4), 'goods_id' => $goods['id'], 'license_type' => $licenseType, 'score' => $price, 'buyer_factory_id' => $factoryId, 'buyer_user_id' => $userId, 'seller_factory_id' => (int)$goods['factory_id'], 'copy_template_id' => $copy['id'], 'status' => 'paid', ]); $license = new MarketLicense(); $license->allowField(true)->save([ 'order_id' => $order->id, 'template_id' => $copy['id'], 'license_type' => $licenseType, 'remain_times' => $licenseType === 'buyout' ? -1 : 1, 'locked' => 0, ]); Db::commit(); } catch (\Exception $e) { Db::rollback(); throw $e; } return [ 'order_no' => $order['order_no'], 'template_id' => (int)$copy['id'], 'score' => $price, 'license' => $licenseType, ]; } /** * @param array $source * @param MarketGoods $goods * @param string $licenseType * @param int $userId * @param int $factoryId * @return Template */ protected static function importCopy(array $source, $goods, $licenseType, $userId, $factoryId) { $versionId = (int)$goods['template_version_id'] ?: (int)$source['current_version_id']; $schema = ''; if ($versionId) { $ver = Db::name('ps_template_version')->where('id', $versionId)->find(); $schema = $ver ? (string)$ver['schema_json'] : ''; } $tpl = new Template(); $tpl->allowField(true)->save([ 'creator_user_id' => $userId, 'name' => $goods['title'] ?: $source['name'], 'cover' => $goods['cover'] ?: $source['cover'], 'source' => 'market', 'license_type' => $licenseType === 'buyout' ? 'market_buyout' : 'market_single', 'locked' => 0, 'source_template_id' => (int)$source['id'], 'source_version_id' => $versionId, 'is_system' => 0, 'status' => 'normal', ]); $verRow = new TemplateVersion(); $verRow->allowField(true)->save([ 'template_id' => $tpl->id, 'version' => 1, 'schema_json' => $schema, 'remark' => '商城导入', ]); $tpl->save(['current_version_id' => $verRow->id]); return $tpl; } }