123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- <?php
- namespace App\Import;
- use App\Model\Finance;
- use App\Model\FinanceDetail;
- use App\Model\Settings;
- use Illuminate\Support\Facades\DB;
- use Maatwebsite\Excel\Concerns\ToArray;
- class Import implements ToArray {
- private $msg = '';
- public $crt_id = 0;
- public function array (array $array){
- $this->handleData($array);
- }
- public function setCrt($crt_id){
- $this->crt_id = $crt_id;
- }
- public function getMsg(){
- return $this->msg;
- }
- public function setMsg($msg){
- $this->msg = $msg;
- }
- function splitAmount($amount, $defaultAmount) {
- $result = array();
- while ($amount > $defaultAmount) {
- $result[] = $defaultAmount;
- $amount -= $defaultAmount;
- }
- if ($amount > 0) {
- $result[] = $amount;
- }
- return $result;
- }
- public function handleData (array $array) {
- // 去除表头
- unset($array[0]);
- if(empty($array)) {
- $this->setMsg('数据不能为空!');
- return ;
- }
- //第一次表格数据校验 非空 已经过滤数据
- foreach ($array as $key => $value){
- if(empty($value[0]) && empty($value[1]) && empty($value[2]) && empty($value[3])) {
- unset($array[$key]);
- }elseif(empty($value[0]) || empty($value[1]) || empty($value[2]) || empty($value[3])) {
- $this->setMsg('数据必须完整填写!');
- return ;
- }else{
- $value[3] = trim($value[3]);
- if(! is_numeric($value[3])){
- $this->setMsg('请输入正确的金额!');
- return ;
- }
- }
- }
- if(empty($array)) {
- $this->setMsg('数据不能为空!');
- return ;
- }
- $array = array_values($array);
- //默认拆分金额
- $setting = Settings::where('name','defaultAmount')->first();
- if(empty($setting) || ! is_numeric($setting->value) || $setting->value <= 0) {
- $this->setMsg('请确认默认拆分金额是否正确!');
- return ;
- }
- $defaultAmount = (float)$setting->value;
- //生成时间
- $crt_time = time();
- //出账主表和子表数据
- $main = $sub = [];
- foreach ($array as $key => $value){
- //主表数据
- $main[] = [
- 'finance_account_name' => $value[0],
- 'account' => $value[1],
- 'ifsc' => $value[2],
- 'amount' => trim($value[3]),
- 'crt_id' => $this->crt_id,
- 'crt_time' => $crt_time
- ];
- $totalAmount = (float)$value[3];
- $return = $this->splitAmount($totalAmount,$defaultAmount);
- $sub[$key] = $return;
- }
- try{
- DB::beginTransaction();
- Finance::insert($main);
- //获取上一次插入的所有id
- $last_insert_id = Finance::where('crt_time',$crt_time)->select('id')->get()->toArray();
- $last_insert_id = array_column($last_insert_id,'id');
- $insert_sub = [];
- foreach ($sub as $key => $value){
- foreach ($value as $v){
- $insert_sub[] = [
- 'amount' => $v,
- 'finance_id' => $last_insert_id[$key],
- 'crt_time' => $crt_time
- ];
- }
- }unset($main);unset($sub);
- FinanceDetail::insert($insert_sub);
- DB::commit();
- }catch (\Exception $e){
- DB::rollBack();
- $this->setMsg($e->getMessage());
- }
- }
- }
|