1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-10 05:02:36 +01:00
invoiceninja/app/Services/ImportService.php

607 lines
18 KiB
PHP
Raw Normal View History

2016-02-27 21:41:23 +01:00
<?php namespace App\Services;
2015-11-18 15:40:50 +01:00
2015-11-24 20:45:38 +01:00
use stdClass;
2015-11-18 15:40:50 +01:00
use Excel;
use Cache;
use Exception;
2015-11-18 17:08:37 +01:00
use Auth;
2015-11-18 18:16:23 +01:00
use parsecsv;
use Session;
use Validator;
2015-11-18 15:40:50 +01:00
use League\Fractal\Manager;
use App\Ninja\Repositories\ContactRepository;
2015-11-18 15:40:50 +01:00
use App\Ninja\Repositories\ClientRepository;
use App\Ninja\Repositories\InvoiceRepository;
use App\Ninja\Repositories\PaymentRepository;
2016-05-31 22:15:55 +02:00
use App\Ninja\Repositories\ProductRepository;
2015-11-18 15:40:50 +01:00
use App\Ninja\Serializers\ArraySerializer;
2015-11-18 17:08:37 +01:00
use App\Models\Client;
2015-11-24 20:45:38 +01:00
use App\Models\Invoice;
2016-06-02 21:03:59 +02:00
use App\Models\EntityModel;
2015-11-18 15:40:50 +01:00
class ImportService
{
protected $transformer;
protected $invoiceRepo;
protected $clientRepo;
protected $contactRepo;
2016-05-31 22:15:55 +02:00
protected $productRepo;
2016-06-02 21:03:59 +02:00
protected $processedRows = [];
private $maps = [];
public $results = [];
2015-11-18 15:40:50 +01:00
public static $entityTypes = [
2016-06-02 21:03:59 +02:00
IMPORT_JSON,
2015-11-18 15:40:50 +01:00
ENTITY_CLIENT,
ENTITY_CONTACT,
2015-11-18 15:40:50 +01:00
ENTITY_INVOICE,
ENTITY_PAYMENT,
2015-11-18 15:40:50 +01:00
ENTITY_TASK,
2016-05-31 22:15:55 +02:00
ENTITY_PRODUCT,
ENTITY_EXPENSE,
2015-11-18 15:40:50 +01:00
];
public static $sources = [
IMPORT_CSV,
2016-06-02 21:03:59 +02:00
IMPORT_JSON,
2015-11-18 15:40:50 +01:00
IMPORT_FRESHBOOKS,
2015-12-17 09:19:56 +01:00
//IMPORT_HARVEST,
2015-12-08 11:10:20 +01:00
IMPORT_HIVEAGE,
2015-12-10 11:57:51 +01:00
IMPORT_INVOICEABLE,
2015-12-14 21:07:48 +01:00
IMPORT_NUTCACHE,
2015-12-10 14:35:40 +01:00
IMPORT_RONIN,
2015-12-13 21:12:54 +01:00
IMPORT_WAVE,
IMPORT_ZOHO,
2015-11-18 15:40:50 +01:00
];
2016-05-31 22:15:55 +02:00
public function __construct(
Manager $manager,
ClientRepository $clientRepo,
InvoiceRepository $invoiceRepo,
PaymentRepository $paymentRepo,
ContactRepository $contactRepo,
ProductRepository $productRepo
)
2015-11-18 15:40:50 +01:00
{
$this->fractal = $manager;
$this->fractal->setSerializer(new ArraySerializer());
$this->clientRepo = $clientRepo;
$this->invoiceRepo = $invoiceRepo;
$this->paymentRepo = $paymentRepo;
$this->contactRepo = $contactRepo;
2016-05-31 22:15:55 +02:00
$this->productRepo = $productRepo;
2015-11-18 15:40:50 +01:00
}
2016-06-02 21:03:59 +02:00
public function importJSON($file)
{
$this->init();
$file = file_get_contents($file);
$json = json_decode($file, true);
$json = $this->removeIdFields($json);
$this->checkClientCount(count($json['clients']));
foreach ($json['clients'] as $jsonClient) {
if ($this->validate($jsonClient, ENTITY_CLIENT) === true) {
$client = $this->clientRepo->save($jsonClient);
$this->addSuccess($client);
} else {
$this->addFailure(ENTITY_CLIENT, $jsonClient);
continue;
}
foreach ($jsonClient['invoices'] as $jsonInvoice) {
$jsonInvoice['client_id'] = $client->id;
if ($this->validate($jsonInvoice, ENTITY_INVOICE) === true) {
$invoice = $this->invoiceRepo->save($jsonInvoice);
$this->addSuccess($invoice);
} else {
$this->addFailure(ENTITY_INVOICE, $jsonInvoice);
continue;
}
foreach ($jsonInvoice['payments'] as $jsonPayment) {
$jsonPayment['client_id'] = $jsonPayment['client'] = $client->id; // TODO: change to client_id once views are updated
$jsonPayment['invoice_id'] = $jsonPayment['invoice'] = $invoice->id; // TODO: change to invoice_id once views are updated
if ($this->validate($jsonPayment, ENTITY_PAYMENT) === true) {
$payment = $this->paymentRepo->save($jsonPayment);
$this->addSuccess($payment);
} else {
$this->addFailure(ENTITY_PAYMENT, $jsonPayment);
continue;
}
}
}
}
return $this->results;
}
public function removeIdFields($array)
{
foreach ($array as $key => $val) {
if (is_array($val)) {
$array[$key] = $this->removeIdFields($val);
} elseif ($key === 'id') {
unset($array[$key]);
}
}
return $array;
}
public function importFiles($source, $files)
2015-11-18 15:40:50 +01:00
{
2015-12-21 20:57:55 +01:00
$results = [];
2015-11-18 15:40:50 +01:00
$imported_files = null;
2016-06-02 21:03:59 +02:00
$this->initMaps();
2015-11-24 20:45:38 +01:00
2015-11-18 15:40:50 +01:00
foreach ($files as $entityType => $file) {
2015-12-21 20:57:55 +01:00
$results[$entityType] = $this->execute($source, $entityType, $file);
2015-11-18 15:40:50 +01:00
}
2015-12-31 16:09:45 +01:00
2015-12-21 20:57:55 +01:00
return $results;
2015-11-18 15:40:50 +01:00
}
private function execute($source, $entityType, $file)
{
2015-12-21 20:57:55 +01:00
$results = [
RESULT_SUCCESS => [],
RESULT_FAILURE => [],
];
2015-11-24 20:45:38 +01:00
// Convert the data
2015-12-31 16:09:45 +01:00
$row_list = array();
2016-06-02 21:03:59 +02:00
Excel::load($file, function ($reader) use ($source, $entityType, &$row_list, &$results) {
2015-11-24 20:45:38 +01:00
$this->checkData($entityType, count($reader->all()));
2016-06-02 21:03:59 +02:00
$reader->each(function ($row) use ($source, $entityType, &$row_list, &$results) {
$data_index = $this->transformRow($source, $entityType, $row);
2015-12-31 16:09:45 +01:00
if ($data_index !== false) {
if ($data_index !== true) {
// Wasn't merged with another row
$row_list[] = array('row' => $row, 'data_index' => $data_index);
}
2015-12-21 20:57:55 +01:00
} else {
$results[RESULT_FAILURE][] = $row;
2015-11-25 10:35:24 +01:00
}
2015-11-24 20:45:38 +01:00
});
});
2015-12-31 16:09:45 +01:00
// Save the data
2015-12-31 16:09:45 +01:00
foreach ($row_list as $row_data) {
2016-06-02 21:03:59 +02:00
$result = $this->saveData($source, $entityType, $row_data['row'], $row_data['data_index']);
if ($result) {
$results[RESULT_SUCCESS][] = $result;
} else {
$results[RESULT_FAILURE][] = $row_data['row'];
}
}
2015-11-18 17:08:37 +01:00
2015-12-21 20:57:55 +01:00
return $results;
2015-11-24 20:45:38 +01:00
}
2015-11-18 18:16:23 +01:00
2016-06-02 21:03:59 +02:00
private function transformRow($source, $entityType, $row)
2015-11-24 20:45:38 +01:00
{
2016-06-02 21:03:59 +02:00
$transformer = $this->getTransformer($source, $entityType, $this->maps);
$resource = $transformer->transform($row);
2015-11-24 20:45:38 +01:00
if (!$resource) {
return false;
2015-11-24 20:45:38 +01:00
}
$data = $this->fractal->createData($resource)->toArray();
2015-11-25 10:35:24 +01:00
// if the invoice number is blank we'll assign it
2015-11-24 21:54:04 +01:00
if ($entityType == ENTITY_INVOICE && !$data['invoice_number']) {
2015-11-24 21:41:08 +01:00
$account = Auth::user()->account;
$invoice = Invoice::createNew();
$data['invoice_number'] = $account->getNextInvoiceNumber($invoice);
}
2015-12-31 16:09:45 +01:00
2016-06-02 21:03:59 +02:00
if ($this->validate($data, $entityType) !== true) {
return false;
}
2015-12-31 16:09:45 +01:00
if ($entityType == ENTITY_INVOICE) {
if (empty($this->processedRows[$data['invoice_number']])) {
$this->processedRows[$data['invoice_number']] = $data;
2015-12-31 16:09:45 +01:00
} else {
// Merge invoice items
$this->processedRows[$data['invoice_number']]['invoice_items'] = array_merge($this->processedRows[$data['invoice_number']]['invoice_items'], $data['invoice_items']);
2015-12-31 16:09:45 +01:00
return true;
}
2015-12-31 16:09:45 +01:00
} else {
$this->processedRows[] = $data;
}
2015-12-31 16:09:45 +01:00
end($this->processedRows);
2015-12-31 16:09:45 +01:00
return key($this->processedRows);
}
2015-12-31 16:09:45 +01:00
2016-06-02 21:03:59 +02:00
private function saveData($source, $entityType, $row, $data_index)
{
$data = $this->processedRows[$data_index];
2015-11-24 20:45:38 +01:00
$entity = $this->{"{$entityType}Repo"}->save($data);
2015-11-25 10:35:24 +01:00
2016-06-02 21:03:59 +02:00
// update the entity maps
$mapFunction = 'add' . ucwords($entity->getEntityType()) . 'ToMaps';
$this->$mapFunction($entity);
2015-11-24 20:45:38 +01:00
// if the invoice is paid we'll also create a payment record
2015-12-10 14:35:40 +01:00
if ($entityType === ENTITY_INVOICE && isset($data['paid']) && $data['paid'] > 0) {
2016-06-02 21:03:59 +02:00
$this->createPayment($source, $row, $data['client_id'], $entity->id);
2015-11-24 20:45:38 +01:00
}
return $entity;
2015-11-24 20:45:38 +01:00
}
private function checkData($entityType, $count)
{
if ($entityType === ENTITY_CLIENT) {
$this->checkClientCount($count);
}
}
2015-11-25 10:35:24 +01:00
private function checkClientCount($count)
{
$totalClients = $count + Client::scope()->withTrashed()->count();
if ($totalClients > Auth::user()->getMaxNumClients()) {
throw new Exception(trans('texts.limit_clients', ['count' => Auth::user()->getMaxNumClients()]));
}
}
2015-11-24 20:45:38 +01:00
public static function getTransformerClassName($source, $entityType)
{
return 'App\\Ninja\\Import\\'.$source.'\\'.ucwords($entityType).'Transformer';
}
2015-12-08 11:10:20 +01:00
public static function getTransformer($source, $entityType, $maps)
2015-11-24 20:45:38 +01:00
{
$className = self::getTransformerClassName($source, $entityType);
2015-12-08 11:10:20 +01:00
return new $className($maps);
2015-11-24 20:45:38 +01:00
}
2016-06-02 21:03:59 +02:00
private function createPayment($source, $data, $clientId, $invoiceId)
2015-11-24 20:45:38 +01:00
{
2016-06-02 21:03:59 +02:00
$paymentTransformer = $this->getTransformer($source, ENTITY_PAYMENT, $this->maps);
2015-11-24 20:45:38 +01:00
2015-11-24 22:10:09 +01:00
$data->client_id = $clientId;
$data->invoice_id = $invoiceId;
2015-11-24 20:45:38 +01:00
2016-06-02 21:03:59 +02:00
if ($resource = $paymentTransformer->transform($data)) {
2015-11-24 20:45:38 +01:00
$data = $this->fractal->createData($resource)->toArray();
$this->paymentRepo->save($data);
}
2015-11-18 15:40:50 +01:00
}
2016-06-02 21:03:59 +02:00
private function validate($data, $entityType)
2015-11-18 18:16:23 +01:00
{
2016-06-02 21:03:59 +02:00
/*
// Harvest's contacts are listed separately
if ($entityType === ENTITY_CLIENT && $source != IMPORT_HARVEST) {
2015-11-18 18:16:23 +01:00
$rules = [
'contacts' => 'valid_contacts',
];
2015-11-25 10:35:24 +01:00
}
if ($entityType === ENTITY_INVOICE) {
2015-11-18 18:16:23 +01:00
$rules = [
'client.contacts' => 'valid_contacts',
'invoice_items' => 'valid_invoice_items',
'invoice_number' => 'required|unique:invoices,invoice_number,,id,account_id,'.Auth::user()->account_id,
'discount' => 'positive',
];
2016-05-31 22:15:55 +02:00
}
if ($entityType === ENTITY_PRODUCT) {
$rules = [
'product_key' => 'required',
];
2015-11-18 18:16:23 +01:00
}
2016-06-02 21:03:59 +02:00
*/
$requestClass = 'App\\Http\\Requests\\Create' . ucwords($entityType) . 'Request';
$request = new $requestClass();
$request->setUserResolver(function() { return Auth::user(); });
$request->replace($data);
2015-11-18 18:16:23 +01:00
2016-06-02 21:03:59 +02:00
$validator = Validator::make($data, $request->rules());
2015-11-18 18:16:23 +01:00
if ($validator->fails()) {
2016-06-02 21:03:59 +02:00
return $validator->messages()->first();
2015-11-18 18:16:23 +01:00
} else {
return true;
}
}
2015-11-24 20:45:38 +01:00
public function mapCSV($files)
2015-11-18 15:40:50 +01:00
{
2015-11-24 20:45:38 +01:00
$data = [];
foreach ($files as $entityType => $filename) {
2016-05-31 22:15:55 +02:00
$class = "App\\Models\\" . ucwords($entityType);
$columns = $class::getImportColumns();
$map = $class::getImportMap();
2015-11-24 20:45:38 +01:00
// Lookup field translations
foreach ($columns as $key => $value) {
unset($columns[$key]);
$columns[$value] = trans("texts.{$value}");
}
array_unshift($columns, ' ');
$data[$entityType] = $this->mapFile($entityType, $filename, $columns, $map);
if ($entityType === ENTITY_CLIENT) {
if (count($data[$entityType]['data']) + Client::scope()->count() > Auth::user()->getMaxNumClients()) {
throw new Exception(trans('texts.limit_clients', ['count' => Auth::user()->getMaxNumClients()]));
}
}
}
return $data;
2015-11-18 15:40:50 +01:00
}
2015-11-18 18:16:23 +01:00
2015-11-24 20:45:38 +01:00
public function mapFile($entityType, $filename, $columns, $map)
2015-11-18 18:16:23 +01:00
{
require_once app_path().'/Includes/parsecsv.lib.php';
$csv = new parseCSV();
$csv->heading = false;
$csv->auto($filename);
2015-11-24 20:45:38 +01:00
Session::put("{$entityType}-data", $csv->data);
2015-11-18 18:16:23 +01:00
$headers = false;
$hasHeaders = false;
$mapped = array();
if (count($csv->data) > 0) {
$headers = $csv->data[0];
foreach ($headers as $title) {
if (strpos(strtolower($title), 'name') > 0) {
$hasHeaders = true;
break;
}
}
for ($i = 0; $i<count($headers); $i++) {
$title = strtolower($headers[$i]);
$mapped[$i] = '';
if ($hasHeaders) {
foreach ($map as $search => $column) {
2015-11-25 10:35:24 +01:00
if ($this->checkForMatch($title, $search)) {
$mapped[$i] = $column;
break;
2015-11-18 18:16:23 +01:00
}
}
}
}
}
$data = array(
2015-11-24 20:45:38 +01:00
'entityType' => $entityType,
2015-11-18 18:16:23 +01:00
'data' => $csv->data,
'headers' => $headers,
'hasHeaders' => $hasHeaders,
'columns' => $columns,
'mapped' => $mapped,
);
return $data;
}
2015-11-25 10:35:24 +01:00
private function checkForMatch($column, $pattern)
{
if (strpos($column, 'sec') === 0) {
return false;
}
if (strpos($pattern, '^')) {
list($include, $exclude) = explode('^', $pattern);
$includes = explode('|', $include);
$excludes = explode('|', $exclude);
} else {
$includes = explode('|', $pattern);
$excludes = [];
}
foreach ($includes as $string) {
if (strpos($column, $string) !== false) {
$excluded = false;
foreach ($excludes as $exclude) {
if (strpos($column, $exclude) !== false) {
$excluded = true;
break;
}
}
if (!$excluded) {
return true;
}
}
}
return false;
}
2015-11-24 20:45:38 +01:00
public function importCSV($maps, $headers)
2015-11-18 18:16:23 +01:00
{
2015-12-21 20:57:55 +01:00
$results = [];
2015-11-25 10:35:24 +01:00
2015-11-24 20:45:38 +01:00
foreach ($maps as $entityType => $map) {
2015-12-24 12:17:11 +01:00
$results[$entityType] = $this->executeCSV($entityType, $map, $headers[$entityType]);
2015-11-25 10:35:24 +01:00
}
2015-12-21 20:57:55 +01:00
return $results;
2015-11-25 10:35:24 +01:00
}
private function executeCSV($entityType, $map, $hasHeaders)
{
2015-12-21 20:57:55 +01:00
$results = [
RESULT_SUCCESS => [],
RESULT_FAILURE => [],
];
2015-11-25 10:35:24 +01:00
$source = IMPORT_CSV;
$data = Session::get("{$entityType}-data");
$this->checkData($entityType, count($data));
2016-06-02 21:03:59 +02:00
$this->initMaps();
2015-11-25 10:35:24 +01:00
// Convert the data
$row_list = array();
2015-11-25 10:35:24 +01:00
foreach ($data as $row) {
if ($hasHeaders) {
$hasHeaders = false;
continue;
}
$row = $this->convertToObject($entityType, $row, $map);
2016-06-02 21:03:59 +02:00
$data_index = $this->transformRow($source, $entityType, $row);
2015-12-31 16:09:45 +01:00
if ($data_index !== false) {
2015-12-31 16:09:45 +01:00
if ($data_index !== true) {
// Wasn't merged with another row
$row_list[] = array('row' => $row, 'data_index' => $data_index);
}
} else {
$results[RESULT_FAILURE][] = $row;
}
}
2015-12-31 16:09:45 +01:00
// Save the data
2015-12-31 16:09:45 +01:00
foreach ($row_list as $row_data) {
2016-06-02 21:03:59 +02:00
$result = $this->saveData($source, $entityType, $row_data['row'], $row_data['data_index']);
2015-12-31 16:09:45 +01:00
2015-12-21 20:57:55 +01:00
if ($result) {
$results[RESULT_SUCCESS][] = $result;
} else {
$results[RESULT_FAILURE][] = $row;
2015-11-25 10:35:24 +01:00
}
2015-11-18 18:16:23 +01:00
}
2015-11-25 10:35:24 +01:00
Session::forget("{$entityType}-data");
2015-12-21 20:57:55 +01:00
return $results;
2015-11-24 20:45:38 +01:00
}
2015-11-18 18:16:23 +01:00
2015-11-24 20:45:38 +01:00
private function convertToObject($entityType, $data, $map)
{
$obj = new stdClass();
2016-05-31 22:15:55 +02:00
$class = "App\\Models\\" . ucwords($entityType);
$columns = $class::getImportColumns();
2015-11-18 18:16:23 +01:00
2015-11-24 20:45:38 +01:00
foreach ($columns as $column) {
$obj->$column = false;
}
2015-11-18 18:16:23 +01:00
2015-11-24 20:45:38 +01:00
foreach ($map as $index => $field) {
if (! $field) {
2015-11-18 18:16:23 +01:00
continue;
}
2015-11-25 10:35:24 +01:00
if (isset($obj->$field) && $obj->$field) {
continue;
}
2015-11-24 20:45:38 +01:00
$obj->$field = $data[$index];
2015-11-18 18:16:23 +01:00
}
2015-11-24 20:45:38 +01:00
return $obj;
2015-11-18 18:16:23 +01:00
}
2016-06-02 21:03:59 +02:00
private function addSuccess($entity)
{
$this->results[$entity->getEntityType()][RESULT_SUCCESS][] = $entity;
}
private function addFailure($entityType, $data)
{
$this->results[$entityType][RESULT_FAILURE][] = $data;
}
private function init()
{
EntityModel::$notifySubscriptions = false;
foreach ([ENTITY_CLIENT, ENTITY_INVOICE, ENTITY_PAYMENT] as $entityType) {
$this->results[$entityType] = [
RESULT_SUCCESS => [],
RESULT_FAILURE => [],
];
}
}
private function initMaps()
{
$this->init();
$this->maps = [
'client' => [],
'invoice' => [],
'invoice_client' => [],
'product' => [],
'countries' => [],
'countries2' => [],
'currencies' => [],
'client_ids' => [],
'invoice_ids' => [],
];
$clients = $this->clientRepo->all();
foreach ($clients as $client) {
$this->addClientToMaps($client);
}
$invoices = $this->invoiceRepo->all();
foreach ($invoices as $invoice) {
$this->addInvoiceToMaps($invoice);
}
$products = $this->productRepo->all();
foreach ($products as $product) {
$this->addProductToMaps($product);
}
$countries = Cache::get('countries');
foreach ($countries as $country) {
$this->maps['countries'][strtolower($country->name)] = $country->id;
$this->maps['countries2'][strtolower($country->iso_3166_2)] = $country->id;
}
$currencies = Cache::get('currencies');
foreach ($currencies as $currency) {
$this->maps['currencies'][strtolower($currency->code)] = $currency->id;
}
}
private function addInvoiceToMaps($invoice)
{
if ($number = strtolower(trim($invoice->invoice_number))) {
$this->maps['invoice'][$number] = $invoice->id;
$this->maps['invoice_client'][$number] = $invoice->client_id;
$this->maps['invoice_ids'][$invoice->public_id] = $invoice->id;
}
}
private function addClientToMaps($client)
{
if ($name = strtolower(trim($client->name))) {
$this->maps['client'][$name] = $client->id;
$this->maps['client_ids'][$client->public_id] = $client->id;
}
}
private function addProductToMaps($product)
{
if ($key = strtolower(trim($product->product_key))) {
$this->maps['product'][$key] = $product->id;
}
}
2015-11-18 15:40:50 +01:00
}