You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
2.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services\SupplyDemand;
use App\Models\SupplyDemand;
use Illuminate\Support\Facades\Validator;
class ImportRows
{
public const HEADERS = ['供需类型','标题','详细内容','行业标签','发布人姓名','公司','手机号','有效期','微信','邮箱'];
public const KEYS = ['type','title','content','tag','publisher_name','publisher_company','publisher_mobile','expire_time','wechat','email'];
public static function validate(array $rows) {
if (!$rows || count($rows) > 1000) throw new \InvalidArgumentException('每次导入1至1000条需求');
$valid = []; $errors = []; $seen = [];
foreach (array_values($rows) as $i => $r) {
if (!is_array($r)) { $errors[] = ['row' => $i + 2, 'message' => '行数据格式错误']; continue; }
$data = array_intersect_key($r, array_flip(self::KEYS));
foreach ($data as $key => $v) $data[$key] = is_scalar($v) ? trim((string) $v) : '';
$data['type'] = ['供应'=>1,'需求'=>2,'投融资'=>3][$data['type'] ?? '需求'] ?? ($data['type'] ?? 2);
$data['tag'] = implode(',', array_unique(array_filter(array_map('trim', preg_split('/[、,,]+/u', $data['tag'] ?? '')), 'strlen')));
if (empty($data['expire_time'])) $data['expire_time'] = null;
$v = Validator::make($data, ['type'=>'required|integer|in:1,2,3','wechat'=>'nullable|string|max:100','email'=>'nullable|email|max:255','title'=>'required|string|max:100','content'=>'required|string|max:10000',
'tag'=>'nullable|string|max:255','publisher_name'=>'required|string|max:100', 'publisher_company'=>'required|string|max:255',
'publisher_mobile'=>['required','regex:/^1\d{10}$/'],'expire_time'=>'nullable|date_format:Y-m-d']);
if ($v->fails()) { $errors[] = ['row' => $i + 2, 'message' => implode(';', $v->errors()->all())]; continue; }
$key = hash('sha256', $data['publisher_mobile'] . '|' . $data['title'] . '|' . $data['content']);
if (isset($seen[$key]) || SupplyDemand::withTrashed()->where('import_key', $key)->exists()) { $errors[] = ['row' => $i + 2, 'message' => '重复需求,请核实后移除该行']; continue; }
$seen[$key] = true; $data['import_key'] = $key;
if ($data['expire_time']) $data['expire_time'] .= ' 23:59:59';
$valid[] = $data;
}
return ['rows' => $valid, 'errors' => $errors, 'total' => count($rows)];
}
}