This commit is contained in:
David Bomba 2022-02-03 10:14:54 +11:00
parent 8512b60c45
commit dfe34f6368
8 changed files with 793 additions and 503 deletions

View File

@ -30,8 +30,8 @@ use League\Csv\Reader;
use League\Csv\Statement;
use Symfony\Component\HttpFoundation\ParameterBag;
class BaseImport {
class BaseImport
{
use CleanLineItems;
public Company $company;
@ -50,25 +50,29 @@ class BaseImport {
public $transformer;
public function __construct( array $request, Company $company ) {
public function __construct(array $request, Company $company)
{
$this->company = $company;
$this->request = $request;
$this->hash = $request['hash'];
$this->import_type = $request['import_type'];
$this->skip_header = $request['skip_header'] ?? null;
$this->column_map =
! empty( $request['column_map'] ) ?
array_combine( array_keys( $request['column_map'] ), array_column( $request['column_map'], 'mapping' ) ) : null;
$this->column_map = !empty($request['column_map'])
? array_combine(
array_keys($request['column_map']),
array_column($request['column_map'], 'mapping')
)
: null;
auth()->login($this->company->owner(), true);
auth()->user()->setCompany($this->company);
auth()
->user()
->setCompany($this->company);
}
protected function getCsvData( $entity_type ) {
protected function getCsvData($entity_type)
{
$base64_encoded_csv = Cache::pull($this->hash . '-' . $entity_type);
if (empty($base64_encoded_csv)) {
return null;
@ -84,7 +88,11 @@ class BaseImport {
$headers = $data[0];
// Remove Invoice Ninja headers
if ( count( $headers ) && count( $data ) > 4 && $this->import_type === 'csv' ) {
if (
count($headers) &&
count($data) > 4 &&
$this->import_type === 'csv'
) {
$first_cell = $headers[0];
if (strstr($first_cell, config('ninja.app_name'))) {
array_shift($data); // Invoice Ninja...
@ -97,7 +105,8 @@ class BaseImport {
return $data;
}
public function mapCSVHeaderToKeys( $csvData ) {
public function mapCSVHeaderToKeys($csvData)
{
$keys = array_shift($csvData);
return array_map(function ($values) use ($keys) {
@ -105,13 +114,17 @@ class BaseImport {
}, $csvData);
}
private function groupInvoices( $csvData, $key ) {
private function groupInvoices($csvData, $key)
{
// Group by invoice.
$grouped = [];
foreach ($csvData as $line_item) {
if (empty($line_item[$key])) {
$this->error_array['invoice'][] = [ 'invoice' => $line_item, 'error' => 'No invoice number' ];
$this->error_array['invoice'][] = [
'invoice' => $line_item,
'error' => 'No invoice number',
];
} else {
$grouped[$line_item[$key]][] = $line_item;
}
@ -141,17 +154,21 @@ class BaseImport {
$validator = Validator::make($entity, $request->rules());
if ($validator->fails()) {
$this->error_array[ $entity_type ][] =
[ $entity_type => $record, 'error' => $validator->errors()->all() ];
$this->error_array[$entity_type][] = [
$entity_type => $record,
'error' => $validator->errors()->all(),
];
} else {
$entity =
$this->repository->save(
$entity = $this->repository->save(
array_diff_key($entity, ['user_id' => false]),
$this->factory_name::create( $this->company->id, $this->getUserIDForRecord( $entity ) ) );
$this->factory_name::create(
$this->company->id,
$this->getUserIDForRecord($entity)
)
);
$entity->saveQuietly();
$count++;
}
} catch (\Exception $ex) {
if ($ex instanceof ImportException) {
@ -161,14 +178,18 @@ class BaseImport {
$message = 'Unknown error';
}
$this->error_array[ $entity_type ][] = [ $entity_type => $record, 'error' => $message ];
$this->error_array[$entity_type][] = [
$entity_type => $record,
'error' => $message,
];
}
return $count;
}
}
public function ingestInvoices( $invoices , $invoice_number_key) {
public function ingestInvoices($invoices, $invoice_number_key)
{
$invoice_transformer = $this->transformer;
/** @var PaymentRepository $payment_repository */
@ -186,29 +207,46 @@ class BaseImport {
foreach ($invoices as $raw_invoice) {
try {
$invoice_data = $invoice_transformer->transform($raw_invoice);
$invoice_data['line_items'] = $this->cleanItems( $invoice_data['line_items'] ?? [] );
$invoice_data['line_items'] = $this->cleanItems(
$invoice_data['line_items'] ?? []
);
// If we don't have a client ID, but we do have client data, go ahead and create the client.
if ( empty( $invoice_data['client_id'] ) && ! empty( $invoice_data['client'] ) ) {
if (
empty($invoice_data['client_id']) &&
!empty($invoice_data['client'])
) {
$client_data = $invoice_data['client'];
$client_data['user_id'] = $this->getUserIDForRecord( $invoice_data );
$client_data['user_id'] = $this->getUserIDForRecord(
$invoice_data
);
$client_repository->save(
$client_data,
$client = ClientFactory::create( $this->company->id, $client_data['user_id'] )
$client = ClientFactory::create(
$this->company->id,
$client_data['user_id']
)
);
$invoice_data['client_id'] = $client->id;
unset($invoice_data['client']);
}
$validator = Validator::make( $invoice_data, ( new StoreInvoiceRequest() )->rules() );
$validator = Validator::make(
$invoice_data,
(new StoreInvoiceRequest())->rules()
);
if ($validator->fails()) {
$this->error_array['invoice'][] =
[ 'invoice' => $invoice_data, 'error' => $validator->errors()->all() ];
$this->error_array['invoice'][] = [
'invoice' => $invoice_data,
'error' => $validator->errors()->all(),
];
} else {
$invoice = InvoiceFactory::create( $this->company->id, $this->getUserIDForRecord( $invoice_data ) );
$invoice = InvoiceFactory::create(
$this->company->id,
$this->getUserIDForRecord($invoice_data)
);
if (!empty($invoice_data['status_id'])) {
$invoice->status_id = $invoice_data['status_id'];
}
@ -216,32 +254,47 @@ class BaseImport {
// If we're doing a generic CSV import, only import payment data if we're not importing a payment CSV.
// If we're doing a platform-specific import, trust the platform to only return payment info if there's not a separate payment CSV.
if ( $this->import_type !== 'csv' || empty( $this->column_map['payment'] ) ) {
if (
$this->import_type !== 'csv' ||
empty($this->column_map['payment'])
) {
// Check for payment columns
if (!empty($invoice_data['payments'])) {
foreach ( $invoice_data['payments'] as $payment_data ) {
foreach (
$invoice_data['payments']
as $payment_data
) {
$payment_data['user_id'] = $invoice->user_id;
$payment_data['client_id'] = $invoice->client_id;
$payment_data['client_id'] =
$invoice->client_id;
$payment_data['invoices'] = [
[
'invoice_id' => $invoice->id,
'amount' => $payment_data['amount'] ?? null,
'amount' =>
$payment_data['amount'] ?? null,
],
];
/* Make sure we don't apply any payments to invoices with a Zero Amount*/
if($invoice->amount > 0)
{
if ($invoice->amount > 0) {
$payment_repository->save(
$payment_data,
PaymentFactory::create( $this->company->id, $invoice->user_id, $invoice->client_id )
PaymentFactory::create(
$this->company->id,
$invoice->user_id,
$invoice->client_id
)
);
}
}
}
}
$this->actionInvoiceStatus( $invoice, $invoice_data, $invoice_repository );
$this->actionInvoiceStatus(
$invoice,
$invoice_data,
$invoice_repository
);
}
} catch (\Exception $ex) {
if ($ex instanceof ImportException) {
@ -251,69 +304,55 @@ class BaseImport {
$message = 'Unknown error';
}
$this->error_array['invoice'][] = [ 'invoice' => $raw_invoice, 'error' => $message ];
$this->error_array['invoice'][] = [
'invoice' => $raw_invoice,
'error' => $message,
];
}
}
}
private function actionInvoiceStatus( $invoice, $invoice_data, $invoice_repository ) {
private function actionInvoiceStatus(
$invoice,
$invoice_data,
$invoice_repository
) {
if (!empty($invoice_data['archived'])) {
$invoice_repository->archive($invoice);
$invoice->fresh();
}
if (!empty($invoice_data['viewed'])) {
$invoice = $invoice->service()->markViewed()->save();
$invoice = $invoice
->service()
->markViewed()
->save();
}
if ($invoice->status_id === Invoice::STATUS_DRAFT) {
}
elseif ( $invoice->status_id === Invoice::STATUS_SENT ) {
$invoice = $invoice->service()->markSent()->save();
}
elseif ( $invoice->status_id <= Invoice::STATUS_SENT && $invoice->amount > 0 ) {
} elseif ($invoice->status_id === Invoice::STATUS_SENT) {
$invoice = $invoice
->service()
->markSent()
->save();
} elseif (
$invoice->status_id <= Invoice::STATUS_SENT &&
$invoice->amount > 0
) {
if ($invoice->balance <= 0) {
$invoice->status_id = Invoice::STATUS_PAID;
$invoice->save();
}
elseif ( $invoice->balance != $invoice->amount ) {
} elseif ($invoice->balance != $invoice->amount) {
$invoice->status_id = Invoice::STATUS_PARTIAL;
$invoice->save();
}
}
return $invoice;
}
protected function getUserIDForRecord( $record ) {
protected function getUserIDForRecord($record)
{
if (!empty($record['user_id'])) {
return $this->findUser($record['user_id']);
} else {
@ -321,9 +360,14 @@ class BaseImport {
}
}
protected function findUser( $user_hash ) {
protected function findUser($user_hash)
{
$user = User::where('account_id', $this->company->account->id)
->where( \DB::raw( 'CONCAT_WS(" ", first_name, last_name)' ), 'like', '%' . $user_hash . '%' )
->where(
\DB::raw('CONCAT_WS(" ", first_name, last_name)'),
'like',
'%' . $user_hash . '%'
)
->first();
if ($user) {
@ -332,5 +376,4 @@ class BaseImport {
return $this->company->owner()->id;
}
}
}

View File

@ -30,21 +30,28 @@ use Symfony\Component\HttpFoundation\ParameterBag;
class Csv extends BaseImport implements ImportInterface
{
public array $entity_count = [];
public function import(string $entity)
{
if(in_array($entity, [ 'client', 'product', 'invoice', 'payment', 'vendor', 'expense' ]))
if (
in_array($entity, [
'client',
'product',
'invoice',
'payment',
'vendor',
'expense',
])
) {
$this->{$entity}();
}
//collate any errors
}
private function client()
{
$entity_type = 'client';
$data = $this->getCsvData($entity_type);
@ -52,7 +59,6 @@ class Csv extends BaseImport implements ImportInterface
$data = $this->preTransform($data, $entity_type);
if (empty($data)) {
$this->entity_count['clients'] = 0;
return;
}
@ -69,12 +75,10 @@ class Csv extends BaseImport implements ImportInterface
$client_count = $this->ingest($data, $entity_type);
$this->entity_count['clients'] = $client_count;
}
private function product()
{
$entity_type = 'product';
$data = $this->getCsvData($entity_type);
@ -82,7 +86,6 @@ class Csv extends BaseImport implements ImportInterface
$data = $this->preTransform($data, $entity_type);
if (empty($data)) {
$this->entity_count['products'] = 0;
return;
}
@ -99,12 +102,10 @@ class Csv extends BaseImport implements ImportInterface
$product_count = $this->ingest($data, $entity_type);
$this->entity_count['products'] = $product_count;
}
private function invoice()
{
$entity_type = 'invoice';
$data = $this->getCsvData($entity_type);
@ -112,7 +113,6 @@ class Csv extends BaseImport implements ImportInterface
$data = $this->preTransform($data, $entity_type);
if (empty($data)) {
$this->entity_count['invoices'] = 0;
return;
}
@ -126,17 +126,13 @@ class Csv extends BaseImport implements ImportInterface
$this->transformer = new InvoiceTransformer($this->company);
$invoice_count = $this->ingestInvoices($data, 'invoice.number');
$invoice_count = $this->ingestInvoices($data);
$this->entity_count['invoices'] = $invoice_count;
}
public function preTransform(array $data, $entity_type)
{
if (empty($this->column_map[$entity_type])) {
return false;
}
@ -153,15 +149,10 @@ class Csv extends BaseImport implements ImportInterface
return array_combine($keys, array_intersect_key($row, $keys));
}, $data);
return $data;
}
public function transform(array $data)
{
}
}

View File

@ -12,5 +12,4 @@ namespace App\Import\Providers;
class Freshbooks extends BaseImport
{
}

View File

@ -25,7 +25,6 @@ use Illuminate\Support\Facades\Cache;
*/
class BaseTransformer
{
protected $company;
public function __construct($company)
@ -35,37 +34,42 @@ class BaseTransformer
public function getString($data, $field)
{
return (isset($data[$field]) && $data[$field]) ? $data[$field] : '';
return isset($data[$field]) && $data[$field] ? $data[$field] : '';
}
public function getCurrencyByCode($data, $key = 'client.currency_id')
{
$code = array_key_exists($key, $data) ? $data[$key] : false;
$currencies = Cache::get('currencies');
$currency = $currencies->filter(function ($item) use($code) {
$currency = $currencies
->filter(function ($item) use ($code) {
return $item->code == $code;
})->first();
return $currency ? $currency->id : $this->company->settings->currency_id;
})
->first();
return $currency
? $currency->id
: $this->company->settings->currency_id;
}
public function getClient($client_name, $client_email)
{
// nlog("searching for {$client_name} with email {$client_email}");
$client_id_search = $this->company->clients()->where( 'id_number', $client_name );
$client_id_search = $this->company
->clients()
->where('id_number', $client_name);
if ($client_id_search->count() >= 1) {
// nlog("found via id number => {$client_id_search->first()->id}");
return $client_id_search->first()->id;
}
$client_name_search = $this->company->clients()->where( 'name', $client_name );
$client_name_search = $this->company
->clients()
->where('name', $client_name);
if ($client_name_search->count() >= 1) {
// nlog("found via name {$client_name_search->first()->id}");
@ -73,8 +77,10 @@ class BaseTransformer
}
if (!empty($client_email)) {
$contacts = ClientContact::where( 'company_id', $this->company->id )
->where( 'email', $client_email );
$contacts = ClientContact::where(
'company_id',
$this->company->id
)->where('email', $client_email);
if ($contacts->count() >= 1) {
// nlog("found via contact {$contacts->first()->client_id}");
@ -87,8 +93,6 @@ class BaseTransformer
return null;
}
///////////////////////////////////////////////////////////////////////////////////
/**
* @param $name
@ -97,7 +101,12 @@ class BaseTransformer
*/
public function hasClient($name)
{
return $this->company->clients()->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $name))])->exists();
return $this->company
->clients()
->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $name)),
])
->exists();
}
/**
@ -107,7 +116,12 @@ class BaseTransformer
*/
public function hasVendor($name)
{
return $this->company->vendors()->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $name))])->exists();
return $this->company
->vendors()
->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $name)),
])
->exists();
}
/**
@ -117,7 +131,12 @@ class BaseTransformer
*/
public function hasProduct($key)
{
return $this->company->products()->whereRaw("LOWER(REPLACE(`product_key`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $key))])->exists();
return $this->company
->products()
->whereRaw("LOWER(REPLACE(`product_key`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $key)),
])
->exists();
}
/**
@ -144,7 +163,12 @@ class BaseTransformer
*/
public function getClientId($name)
{
$client = $this->company->clients()->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $name))])->first();
$client = $this->company
->clients()
->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $name)),
])
->first();
return $client ? $client->id : null;
}
@ -156,14 +180,18 @@ class BaseTransformer
*/
public function getProduct($data, $key, $field, $default = false)
{
$product = $this->company
->products()
->whereRaw("LOWER(REPLACE(`product_key`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $data->{$key})),
])
->first();
$product = $this->company->products()->whereRaw("LOWER(REPLACE(`product_key`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $data->{$key}))])->first();
if($product)
if ($product) {
return $product->{$field} ?: $default;
}
return $default;
}
/**
@ -173,14 +201,18 @@ class BaseTransformer
*/
public function getContact($email)
{
$contact = $this->company
->client_contacts()
->whereRaw("LOWER(REPLACE(`email`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $email)),
])
->first();
$contact = $this->company->client_contacts()->whereRaw("LOWER(REPLACE(`email`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $email))])->first();
if(!$contact)
if (!$contact) {
return null;
}
return $contact;
}
/**
@ -190,10 +222,13 @@ class BaseTransformer
*/
public function getCountryId($name)
{
if(strlen($name) == 2)
if (strlen($name) == 2) {
return $this->getCountryIdBy2($name);
}
$country = Country::whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $name))])->first();
$country = Country::whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $name)),
])->first();
return $country ? $country->id : null;
}
@ -205,7 +240,9 @@ class BaseTransformer
*/
public function getCountryIdBy2($name)
{
return Country::where('iso_3166_2', $name)->exists() ? Country::where('iso_3166_2', $name)->first()->id : null;
return Country::where('iso_3166_2', $name)->exists()
? Country::where('iso_3166_2', $name)->first()->id
: null;
}
/**
@ -217,7 +254,12 @@ class BaseTransformer
{
$name = strtolower(trim($name));
$tax_rate = $this->company->tax_rates()->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $name))])->first();
$tax_rate = $this->company
->tax_rates()
->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $name)),
])
->first();
return $tax_rate ? $tax_rate->rate : 0;
}
@ -231,10 +273,14 @@ class BaseTransformer
{
$name = strtolower(trim($name));
$tax_rate = $this->company->tax_rates()->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $name))])->first();
$tax_rate = $this->company
->tax_rates()
->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $name)),
])
->first();
return $tax_rate ? $tax_rate->name : '';
}
/**
@ -276,7 +322,12 @@ class BaseTransformer
*/
public function getInvoiceId($invoice_number)
{
$invoice = $this->company->invoices()->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $invoice_number))])->first();
$invoice = $this->company
->invoices()
->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $invoice_number)),
])
->first();
return $invoice ? $invoice->id : null;
}
@ -288,9 +339,12 @@ class BaseTransformer
*/
public function hasInvoice($invoice_number)
{
return $this->company->invoices()->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $invoice_number))])->exists();
return $this->company
->invoices()
->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $invoice_number)),
])
->exists();
}
/**
@ -300,7 +354,12 @@ class BaseTransformer
*/
public function getInvoiceClientId($invoice_number)
{
$invoice = $this->company->invoices()->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $invoice_number))])->first();
$invoice = $this->company
->invoices()
->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $invoice_number)),
])
->first();
return $invoice ? $invoice->client_id : null;
}
@ -312,7 +371,12 @@ class BaseTransformer
*/
public function getVendorId($name)
{
$vendor = $this->company->vendors()->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $name))])->first();
$vendor = $this->company
->vendors()
->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $name)),
])
->first();
return $vendor ? $vendor->id : null;
}
@ -322,12 +386,16 @@ class BaseTransformer
*
* @return int|null
*/
public function getExpenseCategoryId( $name ) {
$ec = $this->company->expense_categories()->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $name))])->first();
public function getExpenseCategoryId($name)
{
$ec = $this->company
->expense_categories()
->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $name)),
])
->first();
return $ec ? $ec->id : null;
}
/**
@ -335,9 +403,14 @@ class BaseTransformer
*
* @return int|null
*/
public function getProjectId( $name ) {
$project = $this->company->projects()->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $name))])->first();
public function getProjectId($name)
{
$project = $this->company
->projects()
->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $name)),
])
->first();
return $project ? $project->id : null;
}
@ -347,12 +420,12 @@ class BaseTransformer
*
* @return int|null
*/
public function getPaymentTypeId( $name ) {
$pt = PaymentType::whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [strtolower(str_replace(' ', '', $name))])->first();
public function getPaymentTypeId($name)
{
$pt = PaymentType::whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
strtolower(str_replace(' ', '', $name)),
])->first();
return $pt ? $pt->id : null;
}
}

View File

@ -30,7 +30,7 @@ class ClientTransformer extends BaseTransformer
throw new ImportException('Client already exists');
}
$settings = new \stdClass;
$settings = new \stdClass();
$settings->currency_id = (string) $this->getCurrencyByCode($data);
return [
@ -42,11 +42,23 @@ class ClientTransformer extends BaseTransformer
'postal_code' => $this->getString($data, 'client.postal_code'),
'city' => $this->getString($data, 'client.city'),
'state' => $this->getString($data, 'client.state'),
'shipping_address1' => $this->getString( $data, 'client.shipping_address1' ),
'shipping_address2' => $this->getString( $data, 'client.shipping_address2' ),
'shipping_address1' => $this->getString(
$data,
'client.shipping_address1'
),
'shipping_address2' => $this->getString(
$data,
'client.shipping_address2'
),
'shipping_city' => $this->getString($data, 'client.shipping_city'),
'shipping_state' => $this->getString( $data, 'client.shipping_state' ),
'shipping_postal_code' => $this->getString( $data, 'client.shipping_postal_code' ),
'shipping_state' => $this->getString(
$data,
'client.shipping_state'
),
'shipping_postal_code' => $this->getString(
$data,
'client.shipping_postal_code'
),
'public_notes' => $this->getString($data, 'client.public_notes'),
'private_notes' => $this->getString($data, 'client.private_notes'),
'website' => $this->getString($data, 'client.website'),
@ -56,27 +68,52 @@ class ClientTransformer extends BaseTransformer
'custom_value2' => $this->getString($data, 'client.custom_value2'),
'custom_value3' => $this->getString($data, 'client.custom_value3'),
'custom_value4' => $this->getString($data, 'client.custom_value4'),
'balance' => preg_replace( '/[^0-9,.]+/', '', $this->getFloat( $data, 'client.balance' ) ),
'paid_to_date' => preg_replace( '/[^0-9,.]+/', '', $this->getFloat( $data, 'client.paid_to_date' ) ),
'balance' => preg_replace(
'/[^0-9,.]+/',
'',
$this->getFloat($data, 'client.balance')
),
'paid_to_date' => preg_replace(
'/[^0-9,.]+/',
'',
$this->getFloat($data, 'client.paid_to_date')
),
'credit_balance' => 0,
'settings' => $settings,
'client_hash' => Str::random(40),
'contacts' => [
[
'first_name' => $this->getString( $data, 'contact.first_name' ),
'first_name' => $this->getString(
$data,
'contact.first_name'
),
'last_name' => $this->getString($data, 'contact.last_name'),
'email' => $this->getString($data, 'contact.email'),
'phone' => $this->getString($data, 'contact.phone'),
'custom_value1' => $this->getString( $data, 'contact.custom_value1' ),
'custom_value2' => $this->getString( $data, 'contact.custom_value2' ),
'custom_value3' => $this->getString( $data, 'contact.custom_value3' ),
'custom_value4' => $this->getString( $data, 'contact.custom_value4' ),
'custom_value1' => $this->getString(
$data,
'contact.custom_value1'
),
'custom_value2' => $this->getString(
$data,
'contact.custom_value2'
),
'custom_value3' => $this->getString(
$data,
'contact.custom_value3'
),
'custom_value4' => $this->getString(
$data,
'contact.custom_value4'
),
],
],
'country_id' => isset( $data['client.country'] ) ? $this->getCountryId( $data['client.country']) : null,
'shipping_country_id' => isset($data['client.shipping_country'] ) ? $this->getCountryId( $data['client.shipping_country'] ) : null,
'country_id' => isset($data['client.country'])
? $this->getCountryId($data['client.country'])
: null,
'shipping_country_id' => isset($data['client.shipping_country'])
? $this->getCountryId($data['client.shipping_country'])
: null,
];
}
}

View File

@ -19,16 +19,15 @@ use App\Models\Invoice;
/**
* Class InvoiceTransformer.
*/
class InvoiceTransformer extends BaseTransformer {
class InvoiceTransformer extends BaseTransformer
{
/**
* @param $data
*
* @return bool|array
*/
public function transform( $line_items_data ) {
public function transform($line_items_data)
{
$invoice_data = reset($line_items_data);
if ($this->hasInvoice($invoice_data['invoice.number'])) {
@ -44,72 +43,157 @@ class InvoiceTransformer extends BaseTransformer {
'company_id' => $this->company->id,
'number' => $this->getString($invoice_data, 'invoice.number'),
'user_id' => $this->getString($invoice_data, 'invoice.user_id'),
'amount' => $amount = $this->getFloat( $invoice_data, 'invoice.amount' ),
'balance' => isset( $invoice_data['invoice.balance'] ) ? $this->getFloat( $invoice_data, 'invoice.balance' ) : $amount,
'client_id' => $this->getClient( $this->getString( $invoice_data, 'client.name' ), $this->getString( $invoice_data, 'client.email' ) ),
'amount' => ($amount = $this->getFloat(
$invoice_data,
'invoice.amount'
)),
'balance' => isset($invoice_data['invoice.balance'])
? $this->getFloat($invoice_data, 'invoice.balance')
: $amount,
'client_id' => $this->getClient(
$this->getString($invoice_data, 'client.name'),
$this->getString($invoice_data, 'client.email')
),
'discount' => $this->getFloat($invoice_data, 'invoice.discount'),
'po_number' => $this->getString($invoice_data, 'invoice.po_number'),
'date' => isset( $invoice_data['invoice.date'] ) ? date( 'Y-m-d', strtotime( $invoice_data['invoice.date'] ) ) : now()->format('Y-m-d'),
'due_date' => isset( $invoice_data['invoice.due_date'] ) ? date( 'Y-m-d', strtotime( $invoice_data['invoice.due_date'] ) ) : null,
'date' => isset($invoice_data['invoice.date'])
? date('Y-m-d', strtotime($invoice_data['invoice.date']))
: now()->format('Y-m-d'),
'due_date' => isset($invoice_data['invoice.due_date'])
? date('Y-m-d', strtotime($invoice_data['invoice.due_date']))
: null,
'terms' => $this->getString($invoice_data, 'invoice.terms'),
'public_notes' => $this->getString( $invoice_data, 'invoice.public_notes' ),
'private_notes' => $this->getString( $invoice_data, 'invoice.private_notes' ),
'public_notes' => $this->getString(
$invoice_data,
'invoice.public_notes'
),
'private_notes' => $this->getString(
$invoice_data,
'invoice.private_notes'
),
'tax_name1' => $this->getString($invoice_data, 'invoice.tax_name1'),
'tax_rate1' => $this->getFloat($invoice_data, 'invoice.tax_rate1'),
'tax_name2' => $this->getString($invoice_data, 'invoice.tax_name2'),
'tax_rate2' => $this->getFloat($invoice_data, 'invoice.tax_rate2'),
'tax_name3' => $this->getString($invoice_data, 'invoice.tax_name3'),
'tax_rate3' => $this->getFloat($invoice_data, 'invoice.tax_rate3'),
'custom_value1' => $this->getString( $invoice_data, 'invoice.custom_value1' ),
'custom_value2' => $this->getString( $invoice_data, 'invoice.custom_value2' ),
'custom_value3' => $this->getString( $invoice_data, 'invoice.custom_value3' ),
'custom_value4' => $this->getString( $invoice_data, 'invoice.custom_value4' ),
'custom_value1' => $this->getString(
$invoice_data,
'invoice.custom_value1'
),
'custom_value2' => $this->getString(
$invoice_data,
'invoice.custom_value2'
),
'custom_value3' => $this->getString(
$invoice_data,
'invoice.custom_value3'
),
'custom_value4' => $this->getString(
$invoice_data,
'invoice.custom_value4'
),
'footer' => $this->getString($invoice_data, 'invoice.footer'),
'partial' => $this->getFloat($invoice_data, 'invoice.partial'),
'partial_due_date' => $this->getString( $invoice_data, 'invoice.partial_due_date' ),
'custom_surcharge1' => $this->getString( $invoice_data, 'invoice.custom_surcharge1' ),
'custom_surcharge2' => $this->getString( $invoice_data, 'invoice.custom_surcharge2' ),
'custom_surcharge3' => $this->getString( $invoice_data, 'invoice.custom_surcharge3' ),
'custom_surcharge4' => $this->getString( $invoice_data, 'invoice.custom_surcharge4' ),
'exchange_rate' => $this->getString( $invoice_data, 'invoice.exchange_rate' ),
'status_id' => $invoiceStatusMap[ $status =
strtolower( $this->getString( $invoice_data, 'invoice.status' ) ) ] ??
Invoice::STATUS_SENT,
'partial_due_date' => $this->getString(
$invoice_data,
'invoice.partial_due_date'
),
'custom_surcharge1' => $this->getString(
$invoice_data,
'invoice.custom_surcharge1'
),
'custom_surcharge2' => $this->getString(
$invoice_data,
'invoice.custom_surcharge2'
),
'custom_surcharge3' => $this->getString(
$invoice_data,
'invoice.custom_surcharge3'
),
'custom_surcharge4' => $this->getString(
$invoice_data,
'invoice.custom_surcharge4'
),
'exchange_rate' => $this->getString(
$invoice_data,
'invoice.exchange_rate'
),
'status_id' =>
$invoiceStatusMap[
($status = strtolower(
$this->getString($invoice_data, 'invoice.status')
))
] ?? Invoice::STATUS_SENT,
'archived' => $status === 'archived',
];
/* If we can't find the client, then lets try and create a client */
if (!$transformed['client_id']) {
$client_transformer = new ClientTransformer($this->company);
$transformed['client'] = $client_transformer->transform($invoice_data);
$transformed['client'] = $client_transformer->transform(
$invoice_data
);
}
if (isset($invoice_data['payment.amount'])) {
$transformed['payments'] = [
[
'date' => isset( $invoice_data['payment.date'] ) ? date( 'Y-m-d', strtotime( $invoice_data['payment.date'] ) ) : date( 'y-m-d' ),
'transaction_reference' => $this->getString( $invoice_data, 'payment.transaction_reference' ),
'amount' => $this->getFloat( $invoice_data, 'payment.amount' ),
'date' => isset($invoice_data['payment.date'])
? date(
'Y-m-d',
strtotime($invoice_data['payment.date'])
)
: date('y-m-d'),
'transaction_reference' => $this->getString(
$invoice_data,
'payment.transaction_reference'
),
'amount' => $this->getFloat(
$invoice_data,
'payment.amount'
),
],
];
} elseif ($status === 'paid') {
$transformed['payments'] = [
[
'date' => isset( $invoice_data['payment.date'] ) ? date( 'Y-m-d', strtotime( $invoice_data['payment.date'] ) ) : date( 'y-m-d' ),
'transaction_reference' => $this->getString( $invoice_data, 'payment.transaction_reference' ),
'amount' => $this->getFloat( $invoice_data, 'invoice.amount' ),
'date' => isset($invoice_data['payment.date'])
? date(
'Y-m-d',
strtotime($invoice_data['payment.date'])
)
: date('y-m-d'),
'transaction_reference' => $this->getString(
$invoice_data,
'payment.transaction_reference'
),
'amount' => $this->getFloat(
$invoice_data,
'invoice.amount'
),
],
];
} elseif ( isset( $transformed['amount'] ) && isset( $transformed['balance'] ) && ($transformed['amount'] != $transformed['balance'])) {
} elseif (
isset($transformed['amount']) &&
isset($transformed['balance']) &&
$transformed['amount'] != $transformed['balance']
) {
$transformed['payments'] = [
[
'date' => isset( $invoice_data['payment.date'] ) ? date( 'Y-m-d', strtotime( $invoice_data['payment.date'] ) ) : date( 'y-m-d' ),
'transaction_reference' => $this->getString( $invoice_data, 'payment.transaction_reference' ),
'amount' => $transformed['amount'] - $transformed['balance'],
'date' => isset($invoice_data['payment.date'])
? date(
'Y-m-d',
strtotime($invoice_data['payment.date'])
)
: date('y-m-d'),
'transaction_reference' => $this->getString(
$invoice_data,
'payment.transaction_reference'
),
'amount' =>
$transformed['amount'] - $transformed['balance'],
],
];
}
@ -122,18 +206,34 @@ class InvoiceTransformer extends BaseTransformer {
'product_key' => $this->getString($record, 'item.product_key'),
'notes' => $this->getString($record, 'item.notes'),
'discount' => $this->getFloat($record, 'item.discount'),
'is_amount_discount' => filter_var( $this->getString( $record, 'item.is_amount_discount' ), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE ),
'is_amount_discount' => filter_var(
$this->getString($record, 'item.is_amount_discount'),
FILTER_VALIDATE_BOOLEAN,
FILTER_NULL_ON_FAILURE
),
'tax_name1' => $this->getString($record, 'item.tax_name1'),
'tax_rate1' => $this->getFloat($record, 'item.tax_rate1'),
'tax_name2' => $this->getString($record, 'item.tax_name2'),
'tax_rate2' => $this->getFloat($record, 'item.tax_rate2'),
'tax_name3' => $this->getString($record, 'item.tax_name3'),
'tax_rate3' => $this->getFloat($record, 'item.tax_rate3'),
'custom_value1' => $this->getString( $record, 'item.custom_value1' ),
'custom_value2' => $this->getString( $record, 'item.custom_value2' ),
'custom_value3' => $this->getString( $record, 'item.custom_value3' ),
'custom_value4' => $this->getString( $record, 'item.custom_value4' ),
'type_id' => "1", //$this->getInvoiceTypeId( $record, 'item.type_id' ),
'custom_value1' => $this->getString(
$record,
'item.custom_value1'
),
'custom_value2' => $this->getString(
$record,
'item.custom_value2'
),
'custom_value3' => $this->getString(
$record,
'item.custom_value3'
),
'custom_value4' => $this->getString(
$record,
'item.custom_value4'
),
'type_id' => '1', //$this->getInvoiceTypeId( $record, 'item.type_id' ),
];
}
$transformed['line_items'] = $line_items;

View File

@ -17,15 +17,19 @@ use App\Import\Transformer\BaseTransformer;
/**
* Class PaymentTransformer.
*/
class PaymentTransformer extends BaseTransformer {
class PaymentTransformer extends BaseTransformer
{
/**
* @param $data
*
* @return array
*/
public function transform( $data ) {
$client_id = $this->getClient( $this->getString( $data, 'payment.client_id' ), $this->getString( $data, 'payment.client_id' ) );
public function transform($data)
{
$client_id = $this->getClient(
$this->getString($data, 'payment.client_id'),
$this->getString($data, 'payment.client_id')
);
if (empty($client_id)) {
throw new ImportException('Could not find client.');
@ -38,7 +42,10 @@ class PaymentTransformer extends BaseTransformer {
'amount' => $this->getFloat($data, 'payment.amount'),
'refunded' => $this->getFloat($data, 'payment.refunded'),
'applied' => $this->getFloat($data, 'payment.applied'),
'transaction_reference' => $this->getString( $data, 'payment.transaction_reference ' ),
'transaction_reference' => $this->getString(
$data,
'payment.transaction_reference '
),
'date' => $this->getString($data, 'payment.date'),
'private_notes' => $this->getString($data, 'payment.private_notes'),
'custom_value1' => $this->getString($data, 'payment.custom_value1'),
@ -48,9 +55,10 @@ class PaymentTransformer extends BaseTransformer {
'client_id' => $client_id,
];
if ( isset( $data['payment.invoice_number'] ) &&
$invoice_id = $this->getInvoiceId( $data['payment.invoice_number'] ) ) {
if (
isset($data['payment.invoice_number']) &&
($invoice_id = $this->getInvoiceId($data['payment.invoice_number']))
) {
$transformed['invoices'] = [
[
'invoice_id' => $invoice_id,

View File

@ -30,7 +30,7 @@ class ClientTransformer extends BaseTransformer
throw new ImportException('Client already exists');
}
$settings = new \stdClass;
$settings = new \stdClass();
$settings->currency_id = (string) $this->getCurrencyByCode($data);
return [
@ -42,11 +42,23 @@ class ClientTransformer extends BaseTransformer
'postal_code' => $this->getString($data, 'client.postal_code'),
'city' => $this->getString($data, 'client.city'),
'state' => $this->getString($data, 'client.state'),
'shipping_address1' => $this->getString( $data, 'client.shipping_address1' ),
'shipping_address2' => $this->getString( $data, 'client.shipping_address2' ),
'shipping_address1' => $this->getString(
$data,
'client.shipping_address1'
),
'shipping_address2' => $this->getString(
$data,
'client.shipping_address2'
),
'shipping_city' => $this->getString($data, 'client.shipping_city'),
'shipping_state' => $this->getString( $data, 'client.shipping_state' ),
'shipping_postal_code' => $this->getString( $data, 'client.shipping_postal_code' ),
'shipping_state' => $this->getString(
$data,
'client.shipping_state'
),
'shipping_postal_code' => $this->getString(
$data,
'client.shipping_postal_code'
),
'public_notes' => $this->getString($data, 'client.public_notes'),
'private_notes' => $this->getString($data, 'client.private_notes'),
'website' => $this->getString($data, 'client.website'),
@ -56,25 +68,52 @@ class ClientTransformer extends BaseTransformer
'custom_value2' => $this->getString($data, 'client.custom_value2'),
'custom_value3' => $this->getString($data, 'client.custom_value3'),
'custom_value4' => $this->getString($data, 'client.custom_value4'),
'balance' => preg_replace( '/[^0-9,.]+/', '', $this->getFloat( $data, 'client.balance' ) ),
'paid_to_date' => preg_replace( '/[^0-9,.]+/', '', $this->getFloat( $data, 'client.paid_to_date' ) ),
'balance' => preg_replace(
'/[^0-9,.]+/',
'',
$this->getFloat($data, 'client.balance')
),
'paid_to_date' => preg_replace(
'/[^0-9,.]+/',
'',
$this->getFloat($data, 'client.paid_to_date')
),
'credit_balance' => 0,
'settings' => $settings,
'client_hash' => Str::random(40),
'contacts' => [
[
'first_name' => $this->getString( $data, 'contact.first_name' ),
'first_name' => $this->getString(
$data,
'contact.first_name'
),
'last_name' => $this->getString($data, 'contact.last_name'),
'email' => $this->getString($data, 'contact.email'),
'phone' => $this->getString($data, 'contact.phone'),
'custom_value1' => $this->getString( $data, 'contact.custom_value1' ),
'custom_value2' => $this->getString( $data, 'contact.custom_value2' ),
'custom_value3' => $this->getString( $data, 'contact.custom_value3' ),
'custom_value4' => $this->getString( $data, 'contact.custom_value4' ),
'custom_value1' => $this->getString(
$data,
'contact.custom_value1'
),
'custom_value2' => $this->getString(
$data,
'contact.custom_value2'
),
'custom_value3' => $this->getString(
$data,
'contact.custom_value3'
),
'custom_value4' => $this->getString(
$data,
'contact.custom_value4'
),
],
],
'country_id' => isset( $data['client.country'] ) ? $this->getCountryId( $data['client.country']) : null,
'shipping_country_id' => isset($data['client.shipping_country'] ) ? $this->getCountryId( $data['client.shipping_country'] ) : null,
'country_id' => isset($data['client.country'])
? $this->getCountryId($data['client.country'])
: null,
'shipping_country_id' => isset($data['client.shipping_country'])
? $this->getCountryId($data['client.shipping_country'])
: null,
];
}
}