repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Database/Migrations/2021_09_30_154222_alter_lead_pipeline_stages_table.php
packages/Webkul/Lead/src/Database/Migrations/2021_09_30_154222_alter_lead_pipeline_stages_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { $tablePrefix = DB::getTablePrefix(); Schema::table('lead_pipeline_stages', function (Blueprint $table) { $table->string('code')->after('id')->nullable(); $table->string('name')->after('code')->nullable(); }); DB::table('lead_pipeline_stages') ->join('lead_stages', 'lead_pipeline_stages.lead_stage_id', '=', 'lead_stages.id') ->update([ 'lead_pipeline_stages.code' => DB::raw($tablePrefix.'lead_stages.code'), 'lead_pipeline_stages.name' => DB::raw($tablePrefix.'lead_stages.name'), ]); Schema::table('lead_pipeline_stages', function (Blueprint $table) use ($tablePrefix) { $table->dropForeign($tablePrefix.'lead_pipeline_stages_lead_stage_id_foreign'); $table->dropColumn('lead_stage_id'); $table->unique(['code', 'lead_pipeline_id']); $table->unique(['name', 'lead_pipeline_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('lead_pipeline_stages', function (Blueprint $table) { $table->dropColumn('code'); $table->dropColumn('name'); $table->integer('lead_stage_id')->unsigned(); $table->foreign('lead_stage_id')->references('id')->on('lead_stages')->onDelete('cascade'); $table->dropUnique(['lead_pipeline_stages_code_lead_pipeline_id_unique', 'lead_pipeline_stages_name_lead_pipeline_id_unique']); }); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Database/Migrations/2021_07_02_201822_create_lead_quotes_table.php
packages/Webkul/Lead/src/Database/Migrations/2021_07_02_201822_create_lead_quotes_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('lead_quotes', function (Blueprint $table) { $table->integer('quote_id')->unsigned(); $table->foreign('quote_id')->references('id')->on('quotes')->onDelete('cascade'); $table->integer('lead_id')->unsigned(); $table->foreign('lead_id')->references('id')->on('leads')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('lead_quotes'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Database/Migrations/2024_11_29_120302_modify_foreign_keys_in_leads_table.php
packages/Webkul/Lead/src/Database/Migrations/2024_11_29_120302_modify_foreign_keys_in_leads_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('leads', function (Blueprint $table) { $table->integer('user_id')->unsigned()->nullable()->change(); $table->integer('person_id')->unsigned()->nullable()->change(); $table->integer('lead_source_id')->unsigned()->nullable()->change(); $table->integer('lead_type_id')->unsigned()->nullable()->change(); $table->dropForeign(['user_id']); $table->dropForeign(['person_id']); $table->dropForeign(['lead_source_id']); $table->dropForeign(['lead_type_id']); $table->foreign('user_id') ->references('id')->on('users') ->onDelete('set null'); $table->foreign('person_id') ->references('id')->on('persons') ->onDelete('restrict'); $table->foreign('lead_source_id') ->references('id')->on('lead_sources') ->onDelete('restrict'); $table->foreign('lead_type_id') ->references('id')->on('lead_types') ->onDelete('restrict'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('leads', function (Blueprint $table) { $table->dropForeign(['user_id']); $table->dropForeign(['person_id']); $table->dropForeign(['lead_source_id']); $table->dropForeign(['lead_type_id']); $table->integer('user_id')->unsigned()->nullable()->change(); $table->integer('person_id')->unsigned()->nullable(false)->change(); $table->integer('lead_source_id')->unsigned()->nullable(false)->change(); $table->integer('lead_type_id')->unsigned()->nullable(false)->change(); $table->foreign('user_id') ->references('id')->on('users') ->onDelete('cascade'); $table->foreign('person_id') ->references('id')->on('persons') ->onDelete('cascade'); $table->foreign('lead_source_id') ->references('id')->on('lead_sources') ->onDelete('cascade'); $table->foreign('lead_type_id') ->references('id')->on('lead_types') ->onDelete('cascade'); }); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Database/Migrations/2021_04_21_172847_create_lead_types_table.php
packages/Webkul/Lead/src/Database/Migrations/2021_04_21_172847_create_lead_types_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('lead_types', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('lead_types'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Database/Migrations/2021_05_20_141240_create_lead_tags_table.php
packages/Webkul/Lead/src/Database/Migrations/2021_05_20_141240_create_lead_tags_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('lead_tags', function (Blueprint $table) { $table->integer('tag_id')->unsigned(); $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade'); $table->integer('lead_id')->unsigned(); $table->foreign('lead_id')->references('id')->on('leads')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('lead_tags'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Database/Migrations/2021_05_12_150329_create_lead_activities_table.php
packages/Webkul/Lead/src/Database/Migrations/2021_05_12_150329_create_lead_activities_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('lead_activities', function (Blueprint $table) { $table->integer('activity_id')->unsigned(); $table->foreign('activity_id')->references('id')->on('activities')->onDelete('cascade'); $table->integer('lead_id')->unsigned(); $table->foreign('lead_id')->references('id')->on('leads')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('lead_activities'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Database/Migrations/2021_04_22_164215_create_leads_table.php
packages/Webkul/Lead/src/Database/Migrations/2021_04_22_164215_create_leads_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('leads', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description')->nullable(); $table->decimal('lead_value', 12, 4)->nullable(); $table->boolean('status')->nullable(); $table->text('lost_reason')->nullable(); $table->datetime('closed_at')->nullable(); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->integer('person_id')->unsigned(); $table->foreign('person_id')->references('id')->on('persons')->onDelete('cascade'); $table->integer('lead_source_id')->unsigned(); $table->foreign('lead_source_id')->references('id')->on('lead_sources')->onDelete('cascade'); $table->integer('lead_type_id')->unsigned(); $table->foreign('lead_type_id')->references('id')->on('lead_types')->onDelete('cascade'); $table->integer('lead_pipeline_id')->unsigned()->nullable(); $table->foreign('lead_pipeline_id')->references('id')->on('lead_pipelines')->onDelete('cascade'); $table->integer('lead_stage_id')->unsigned(); $table->foreign('lead_stage_id')->references('id')->on('lead_stages')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('leads'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Database/Migrations/2021_04_22_171805_create_lead_products_table.php
packages/Webkul/Lead/src/Database/Migrations/2021_04_22_171805_create_lead_products_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('lead_products', function (Blueprint $table) { $table->increments('id'); $table->integer('quantity')->default(0); $table->decimal('price', 12, 4)->nullable(); $table->decimal('amount', 12, 4)->nullable(); $table->integer('lead_id')->unsigned(); $table->foreign('lead_id')->references('id')->on('leads')->onDelete('cascade'); $table->integer('product_id')->unsigned(); $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('lead_products'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Database/Migrations/2025_07_01_133612_alter_lead_pipelines_table.php
packages/Webkul/Lead/src/Database/Migrations/2025_07_01_133612_alter_lead_pipelines_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('lead_pipelines', function (Blueprint $table) { $table->string('name')->unique()->change(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('lead_pipelines', function (Blueprint $table) { $table->dropUnique(['name']); $table->string('name')->change(); }); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Database/Migrations/2021_09_30_135857_add_column_rotten_days_in_lead_pipelines_table.php
packages/Webkul/Lead/src/Database/Migrations/2021_09_30_135857_add_column_rotten_days_in_lead_pipelines_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('lead_pipelines', function (Blueprint $table) { $table->integer('rotten_days')->after('is_default')->default(30); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('lead_pipelines', function (Blueprint $table) { $table->dropColumn('rotten_days'); }); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/ProductProxy.php
packages/Webkul/Lead/src/Models/ProductProxy.php
<?php namespace Webkul\Lead\Models; use Konekt\Concord\Proxies\ModelProxy; class ProductProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/Stage.php
packages/Webkul/Lead/src/Models/Stage.php
<?php namespace Webkul\Lead\Models; use Illuminate\Database\Eloquent\Model; use Webkul\Lead\Contracts\Stage as StageContract; class Stage extends Model implements StageContract { public $timestamps = false; protected $table = 'lead_pipeline_stages'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'code', 'name', 'probability', 'sort_order', 'lead_pipeline_id', ]; /** * Get the pipeline that owns the pipeline stage. */ public function pipeline() { return $this->belongsTo(PipelineProxy::modelClass(), 'lead_pipeline_id'); } /** * Get the leads. */ public function leads() { return $this->hasMany(LeadProxy::modelClass(), 'lead_pipeline_stage_id'); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/Type.php
packages/Webkul/Lead/src/Models/Type.php
<?php namespace Webkul\Lead\Models; use Illuminate\Database\Eloquent\Model; use Webkul\Lead\Contracts\Type as TypeContract; class Type extends Model implements TypeContract { protected $table = 'lead_types'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', ]; /** * Get the leads. */ public function leads() { return $this->hasMany(LeadProxy::modelClass()); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/PipelineProxy.php
packages/Webkul/Lead/src/Models/PipelineProxy.php
<?php namespace Webkul\Lead\Models; use Konekt\Concord\Proxies\ModelProxy; class PipelineProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/Product.php
packages/Webkul/Lead/src/Models/Product.php
<?php namespace Webkul\Lead\Models; use Illuminate\Database\Eloquent\Model; use Webkul\Lead\Contracts\Product as ProductContract; use Webkul\Product\Models\ProductProxy; class Product extends Model implements ProductContract { protected $table = 'lead_products'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'quantity', 'price', 'amount', 'product_id', 'lead_id', ]; /** * Get the product owns the lead product. */ public function product() { return $this->belongsTo(ProductProxy::modelClass()); } /** * Get the lead that owns the lead product. */ public function lead() { return $this->belongsTo(LeadProxy::modelClass()); } /** * Get the customer full name. */ public function getNameAttribute() { return $this->product->name; } /** * @return array */ public function toArray() { $array = parent::toArray(); $array['name'] = $this->name; return $array; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/SourceProxy.php
packages/Webkul/Lead/src/Models/SourceProxy.php
<?php namespace Webkul\Lead\Models; use Konekt\Concord\Proxies\ModelProxy; class SourceProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/Lead.php
packages/Webkul/Lead/src/Models/Lead.php
<?php namespace Webkul\Lead\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Webkul\Activity\Models\ActivityProxy; use Webkul\Activity\Traits\LogsActivity; use Webkul\Attribute\Traits\CustomAttribute; use Webkul\Contact\Models\PersonProxy; use Webkul\Email\Models\EmailProxy; use Webkul\Lead\Contracts\Lead as LeadContract; use Webkul\Quote\Models\QuoteProxy; use Webkul\Tag\Models\TagProxy; use Webkul\User\Models\UserProxy; class Lead extends Model implements LeadContract { use CustomAttribute, LogsActivity; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'title', 'description', 'lead_value', 'status', 'lost_reason', 'expected_close_date', 'closed_at', 'user_id', 'person_id', 'lead_source_id', 'lead_type_id', 'lead_pipeline_id', 'lead_pipeline_stage_id', ]; /** * Cast the attributes to their respective types. * * @var array */ protected $casts = [ 'closed_at' => 'datetime:D M d, Y H:i A', 'expected_close_date' => 'date:D M d, Y', ]; /** * The attributes that are appended. * * @var array */ protected $appends = [ 'rotten_days', ]; /** * Get the user that owns the lead. */ public function user(): BelongsTo { return $this->belongsTo(UserProxy::modelClass()); } /** * Get the person that owns the lead. */ public function person(): BelongsTo { return $this->belongsTo(PersonProxy::modelClass()); } /** * Get the type that owns the lead. */ public function type(): BelongsTo { return $this->belongsTo(TypeProxy::modelClass(), 'lead_type_id'); } /** * Get the source that owns the lead. */ public function source(): BelongsTo { return $this->belongsTo(SourceProxy::modelClass(), 'lead_source_id'); } /** * Get the pipeline that owns the lead. */ public function pipeline(): BelongsTo { return $this->belongsTo(PipelineProxy::modelClass(), 'lead_pipeline_id'); } /** * Get the pipeline stage that owns the lead. */ public function stage(): BelongsTo { return $this->belongsTo(StageProxy::modelClass(), 'lead_pipeline_stage_id'); } /** * Get the activities. */ public function activities(): BelongsToMany { return $this->belongsToMany(ActivityProxy::modelClass(), 'lead_activities'); } /** * Get the products. */ public function products(): HasMany { return $this->hasMany(ProductProxy::modelClass()); } /** * Get the emails. */ public function emails(): HasMany { return $this->hasMany(EmailProxy::modelClass()); } /** * The quotes that belong to the lead. */ public function quotes(): BelongsToMany { return $this->belongsToMany(QuoteProxy::modelClass(), 'lead_quotes'); } /** * The tags that belong to the lead. */ public function tags(): BelongsToMany { return $this->belongsToMany(TagProxy::modelClass(), 'lead_tags'); } /** * Returns the rotten days */ public function getRottenDaysAttribute() { if (! $this->stage) { return 0; } if (in_array($this->stage->code, ['won', 'lost'])) { return 0; } if (! $this->created_at) { return 0; } $rottenDate = $this->created_at->addDays($this->pipeline->rotten_days); return $rottenDate->diffInDays(Carbon::now(), false); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/Source.php
packages/Webkul/Lead/src/Models/Source.php
<?php namespace Webkul\Lead\Models; use Illuminate\Database\Eloquent\Model; use Webkul\Lead\Contracts\Source as SourceContract; class Source extends Model implements SourceContract { protected $table = 'lead_sources'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', ]; /** * Get the leads. */ public function leads() { return $this->hasMany(LeadProxy::modelClass(), 'lead_source_id', 'id'); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/TypeProxy.php
packages/Webkul/Lead/src/Models/TypeProxy.php
<?php namespace Webkul\Lead\Models; use Konekt\Concord\Proxies\ModelProxy; class TypeProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/LeadProxy.php
packages/Webkul/Lead/src/Models/LeadProxy.php
<?php namespace Webkul\Lead\Models; use Konekt\Concord\Proxies\ModelProxy; class LeadProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/StageProxy.php
packages/Webkul/Lead/src/Models/StageProxy.php
<?php namespace Webkul\Lead\Models; use Konekt\Concord\Proxies\ModelProxy; class StageProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Models/Pipeline.php
packages/Webkul/Lead/src/Models/Pipeline.php
<?php namespace Webkul\Lead\Models; use Illuminate\Database\Eloquent\Model; use Webkul\Lead\Contracts\Pipeline as PipelineContract; class Pipeline extends Model implements PipelineContract { protected $table = 'lead_pipelines'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'rotten_days', 'is_default', ]; /** * Get the leads. */ public function leads() { return $this->hasMany(LeadProxy::modelClass(), 'lead_pipeline_id'); } /** * Get the stages that owns the pipeline. */ public function stages() { return $this->hasMany(StageProxy::modelClass(), 'lead_pipeline_id')->orderBy('sort_order', 'ASC'); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Repositories/TypeRepository.php
packages/Webkul/Lead/src/Repositories/TypeRepository.php
<?php namespace Webkul\Lead\Repositories; use Webkul\Core\Eloquent\Repository; class TypeRepository extends Repository { /** * Specify Model class name * * @return mixed */ public function model() { return 'Webkul\Lead\Contracts\Type'; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Repositories/PipelineRepository.php
packages/Webkul/Lead/src/Repositories/PipelineRepository.php
<?php namespace Webkul\Lead\Repositories; use Illuminate\Container\Container; use Illuminate\Support\Str; use Webkul\Core\Eloquent\Repository; class PipelineRepository extends Repository { /** * Create a new repository instance. * * @return void */ public function __construct( protected StageRepository $stageRepository, Container $container ) { parent::__construct($container); } /** * Specify model class name. * * @return mixed */ public function model() { return 'Webkul\Lead\Contracts\Pipeline'; } /** * Create pipeline. * * @return \Webkul\Lead\Contracts\Pipeline */ public function create(array $data) { if ($data['is_default'] ?? false) { $this->model->query()->update(['is_default' => 0]); } $pipeline = $this->model->create($data); foreach ($data['stages'] as $stageData) { $this->stageRepository->create(array_merge([ 'lead_pipeline_id' => $pipeline->id, ], $stageData)); } return $pipeline; } /** * Update pipeline. * * @param int $id * @param string $attribute * @return \Webkul\Lead\Contracts\Pipeline */ public function update(array $data, $id, $attribute = 'id') { $pipeline = $this->find($id); if ($data['is_default'] ?? false) { $this->model->query()->where('id', '<>', $id)->update(['is_default' => 0]); } $pipeline->update($data); $previousStageIds = $pipeline->stages()->pluck('id'); foreach ($data['stages'] as $stageId => $stageData) { if (Str::contains($stageId, 'stage_')) { $this->stageRepository->create(array_merge([ 'lead_pipeline_id' => $pipeline->id, ], $stageData)); } else { if (is_numeric($index = $previousStageIds->search($stageId))) { $previousStageIds->forget($index); } $this->stageRepository->update($stageData, $stageId); } } foreach ($previousStageIds as $stageId) { $pipeline->leads()->where('lead_pipeline_stage_id', $stageId)->update([ 'lead_pipeline_stage_id' => $pipeline->stages()->first()->id, ]); $this->stageRepository->delete($stageId); } return $pipeline; } /** * Return the default pipeline. * * @return \Webkul\Lead\Contracts\Pipeline */ public function getDefaultPipeline() { $pipeline = $this->findOneByField('is_default', 1); if (! $pipeline) { $pipeline = $this->first(); } return $pipeline; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Repositories/StageRepository.php
packages/Webkul/Lead/src/Repositories/StageRepository.php
<?php namespace Webkul\Lead\Repositories; use Webkul\Core\Eloquent\Repository; class StageRepository extends Repository { /** * Specify Model class name * * @return mixed */ public function model() { return 'Webkul\Lead\Contracts\Stage'; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Repositories/LeadRepository.php
packages/Webkul/Lead/src/Repositories/LeadRepository.php
<?php namespace Webkul\Lead\Repositories; use Carbon\Carbon; use Illuminate\Container\Container; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use Webkul\Attribute\Repositories\AttributeRepository; use Webkul\Attribute\Repositories\AttributeValueRepository; use Webkul\Contact\Repositories\PersonRepository; use Webkul\Core\Eloquent\Repository; use Webkul\Lead\Contracts\Lead; class LeadRepository extends Repository { /** * Searchable fields. */ protected $fieldSearchable = [ 'title', 'lead_value', 'status', 'user_id', 'user.name', 'person_id', 'person.name', 'lead_source_id', 'lead_type_id', 'lead_pipeline_id', 'lead_pipeline_stage_id', 'created_at', 'closed_at', 'expected_close_date', ]; /** * Create a new repository instance. * * @return void */ public function __construct( protected StageRepository $stageRepository, protected PersonRepository $personRepository, protected ProductRepository $productRepository, protected AttributeRepository $attributeRepository, protected AttributeValueRepository $attributeValueRepository, Container $container ) { parent::__construct($container); } /** * Specify model class name. * * @return mixed */ public function model() { return Lead::class; } /** * Get leads query. * * @param int $pipelineId * @param int $pipelineStageId * @param string $term * @param string $createdAtRange * @return mixed */ public function getLeadsQuery($pipelineId, $pipelineStageId, $term, $createdAtRange) { return $this->with([ 'attribute_values', 'pipeline', 'stage', ])->scopeQuery(function ($query) use ($pipelineId, $pipelineStageId, $term, $createdAtRange) { return $query->select( 'leads.id as id', 'leads.created_at as created_at', 'title', 'lead_value', 'persons.name as person_name', 'leads.person_id as person_id', 'lead_pipelines.id as lead_pipeline_id', 'lead_pipeline_stages.name as status', 'lead_pipeline_stages.id as lead_pipeline_stage_id' ) ->addSelect(DB::raw('DATEDIFF('.DB::getTablePrefix().'leads.created_at + INTERVAL lead_pipelines.rotten_days DAY, now()) as rotten_days')) ->leftJoin('persons', 'leads.person_id', '=', 'persons.id') ->leftJoin('lead_pipelines', 'leads.lead_pipeline_id', '=', 'lead_pipelines.id') ->leftJoin('lead_pipeline_stages', 'leads.lead_pipeline_stage_id', '=', 'lead_pipeline_stages.id') ->where('title', 'like', "%$term%") ->where('leads.lead_pipeline_id', $pipelineId) ->where('leads.lead_pipeline_stage_id', $pipelineStageId) ->when($createdAtRange, function ($query) use ($createdAtRange) { return $query->whereBetween('leads.created_at', $createdAtRange); }) ->where(function ($query) { if ($userIds = bouncer()->getAuthorizedUserIds()) { $query->whereIn('leads.user_id', $userIds); } }); }); } /** * Create. * * @return \Webkul\Lead\Contracts\Lead */ public function create(array $data) { /** * If a person is provided, create or update the person and set the `person_id`. */ if (isset($data['person'])) { if (! empty($data['person']['id'])) { $person = $this->personRepository->findOrFail($data['person']['id']); } else { $person = $this->personRepository->create(array_merge($data['person'], [ 'entity_type' => 'persons', ])); } $data['person_id'] = $person->id; } if (empty($data['expected_close_date'])) { $data['expected_close_date'] = null; } $lead = parent::create(array_merge([ 'lead_pipeline_id' => 1, 'lead_pipeline_stage_id' => 1, ], $data)); $this->attributeValueRepository->save(array_merge($data, [ 'entity_id' => $lead->id, ])); if (isset($data['products'])) { foreach ($data['products'] as $product) { $this->productRepository->create(array_merge($product, [ 'lead_id' => $lead->id, 'amount' => $product['price'] * $product['quantity'], ])); } } return $lead; } /** * Update. * * @param int $id * @param array|\Illuminate\Database\Eloquent\Collection $attributes * @return \Webkul\Lead\Contracts\Lead */ public function update(array $data, $id, $attributes = []) { /** * If a person is provided, create or update the person and set the `person_id`. * Be cautious, as a lead can be updated without providing person data. * For example, in the lead Kanban section, when switching stages, only the stage will be updated. */ if (isset($data['person'])) { if (! empty($data['person']['id'])) { $person = $this->personRepository->findOrFail($data['person']['id']); } else { $person = $this->personRepository->create(array_merge($data['person'], [ 'entity_type' => 'persons', ])); } $data['person_id'] = $person->id; } if (isset($data['lead_pipeline_stage_id'])) { $stage = $this->stageRepository->find($data['lead_pipeline_stage_id']); if (in_array($stage->code, ['won', 'lost'])) { $data['closed_at'] = $data['closed_at'] ?? Carbon::now(); } else { $data['closed_at'] = null; } } if (empty($data['expected_close_date'])) { $data['expected_close_date'] = null; } $lead = parent::update($data, $id); /** * If attributes are provided, only save the provided attributes and return. * A collection of attributes may also be provided, which will be treated as valid, * regardless of whether it is empty or not. */ if (! empty($attributes)) { /** * If attributes are provided as an array, then fetch the attributes from the database; * otherwise, use the provided collection of attributes. */ if (is_array($attributes)) { $conditions = ['entity_type' => $data['entity_type']]; if (isset($data['quick_add'])) { $conditions['quick_add'] = 1; } $attributes = $this->attributeRepository->where($conditions) ->whereIn('code', $attributes) ->get(); } $this->attributeValueRepository->save(array_merge($data, [ 'entity_id' => $lead->id, ]), $attributes); return $lead; } $this->attributeValueRepository->save(array_merge($data, [ 'entity_id' => $lead->id, ])); $previousProductIds = $lead->products()->pluck('id'); if (isset($data['products'])) { foreach ($data['products'] as $productId => $productInputs) { if (Str::contains($productId, 'product_')) { $this->productRepository->create(array_merge([ 'lead_id' => $lead->id, ], $productInputs)); } else { if (is_numeric($index = $previousProductIds->search($productId))) { $previousProductIds->forget($index); } $this->productRepository->update($productInputs, $productId); } } } foreach ($previousProductIds as $productId) { $this->productRepository->delete($productId); } return $lead; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Repositories/ProductRepository.php
packages/Webkul/Lead/src/Repositories/ProductRepository.php
<?php namespace Webkul\Lead\Repositories; use Webkul\Core\Eloquent\Repository; class ProductRepository extends Repository { /** * Specify Model class name * * @return mixed */ public function model() { return 'Webkul\Lead\Contracts\Product'; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Repositories/SourceRepository.php
packages/Webkul/Lead/src/Repositories/SourceRepository.php
<?php namespace Webkul\Lead\Repositories; use Webkul\Core\Eloquent\Repository; class SourceRepository extends Repository { /** * Specify Model class name * * @return mixed */ public function model() { return 'Webkul\Lead\Contracts\Source'; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Providers/LeadServiceProvider.php
packages/Webkul/Lead/src/Providers/LeadServiceProvider.php
<?php namespace Webkul\Lead\Providers; use Illuminate\Routing\Router; use Illuminate\Support\ServiceProvider; class LeadServiceProvider extends ServiceProvider { /** * Bootstrap services. * * @return void */ public function boot(Router $router) { $this->loadMigrationsFrom(__DIR__.'/../Database/Migrations'); } /** * Register services. * * @return void */ public function register() {} }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Lead/src/Providers/ModuleServiceProvider.php
packages/Webkul/Lead/src/Providers/ModuleServiceProvider.php
<?php namespace Webkul\Lead\Providers; use Webkul\Core\Providers\BaseModuleServiceProvider; class ModuleServiceProvider extends BaseModuleServiceProvider { protected $models = [ \Webkul\Lead\Models\Lead::class, \Webkul\Lead\Models\Pipeline::class, \Webkul\Lead\Models\Product::class, \Webkul\Lead\Models\Source::class, \Webkul\Lead\Models\Stage::class, \Webkul\Lead\Models\Type::class, ]; }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Contracts/User.php
packages/Webkul/User/src/Contracts/User.php
<?php namespace Webkul\User\Contracts; interface User {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Contracts/Role.php
packages/Webkul/User/src/Contracts/Role.php
<?php namespace Webkul\User\Contracts; interface Role {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Contracts/Group.php
packages/Webkul/User/src/Contracts/Group.php
<?php namespace Webkul\User\Contracts; interface Group {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Database/Migrations/2021_03_12_074957_create_user_password_resets_table.php
packages/Webkul/User/src/Database/Migrations/2021_03_12_074957_create_user_password_resets_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('user_password_resets', function (Blueprint $table) { $table->string('email')->index(); $table->string('token'); $table->timestamp('created_at')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('user_password_resets'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Database/Migrations/2021_03_12_074867_create_user_groups_table.php
packages/Webkul/User/src/Database/Migrations/2021_03_12_074867_create_user_groups_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('user_groups', function (Blueprint $table) { $table->integer('group_id')->unsigned(); $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('user_groups'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Database/Migrations/2021_09_22_194622_add_unique_index_to_name_in_groups_table.php
packages/Webkul/User/src/Database/Migrations/2021_09_22_194622_add_unique_index_to_name_in_groups_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('groups', function (Blueprint $table) { $table->unique('name'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('groups', function (Blueprint $table) { $table->dropUnique('groups_name_unique'); }); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Database/Migrations/2021_03_12_074578_create_groups_table.php
packages/Webkul/User/src/Database/Migrations/2021_03_12_074578_create_groups_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('groups', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('description')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('groups'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Database/Migrations/2021_03_12_074597_create_roles_table.php
packages/Webkul/User/src/Database/Migrations/2021_03_12_074597_create_roles_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('roles', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('description')->nullable(); $table->string('permission_type'); $table->json('permissions')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('roles'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Database/Migrations/2021_11_12_171510_add_image_column_in_users_table.php
packages/Webkul/User/src/Database/Migrations/2021_11_12_171510_add_image_column_in_users_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('image')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('image'); }); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Database/Migrations/2021_03_12_074857_create_users_table.php
packages/Webkul/User/src/Database/Migrations/2021_03_12_074857_create_users_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password')->nullable(); $table->boolean('status')->default(0); $table->integer('role_id')->unsigned(); $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Models/RoleProxy.php
packages/Webkul/User/src/Models/RoleProxy.php
<?php namespace Webkul\User\Models; use Konekt\Concord\Proxies\ModelProxy; class RoleProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Models/User.php
packages/Webkul/User/src/Models/User.php
<?php namespace Webkul\User\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Facades\Storage; use Laravel\Sanctum\HasApiTokens; use Webkul\User\Contracts\User as UserContract; class User extends Authenticatable implements UserContract { use HasApiTokens, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'image', 'password', 'api_token', 'role_id', 'status', 'view_permission', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'api_token', 'remember_token', ]; /** * Get image url for the product image. */ public function image_url() { if (! $this->image) { return; } return Storage::url($this->image); } /** * Get image url for the product image. */ public function getImageUrlAttribute() { return $this->image_url(); } /** * @return array */ public function toArray() { $array = parent::toArray(); $array['image_url'] = $this->image_url; return $array; } /** * Get the role that owns the user. */ public function role() { return $this->belongsTo(RoleProxy::modelClass()); } /** * The groups that belong to the user. */ public function groups() { return $this->belongsToMany(GroupProxy::modelClass(), 'user_groups'); } /** * Checks if user has permission to perform certain action. * * @param string $permission * @return bool */ public function hasPermission($permission) { if ($this->role->permission_type == 'custom' && ! $this->role->permissions) { return false; } return in_array($permission, $this->role->permissions); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Models/UserProxy.php
packages/Webkul/User/src/Models/UserProxy.php
<?php namespace Webkul\User\Models; use Konekt\Concord\Proxies\ModelProxy; class UserProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Models/Role.php
packages/Webkul/User/src/Models/Role.php
<?php namespace Webkul\User\Models; use Illuminate\Database\Eloquent\Model; use Webkul\User\Contracts\Role as RoleContract; class Role extends Model implements RoleContract { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'description', 'permission_type', 'permissions', ]; protected $casts = [ 'permissions' => 'array', ]; /** * Get the users. */ public function users() { return $this->hasMany(UserProxy::modelClass()); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Models/GroupProxy.php
packages/Webkul/User/src/Models/GroupProxy.php
<?php namespace Webkul\User\Models; use Konekt\Concord\Proxies\ModelProxy; class GroupProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Models/Group.php
packages/Webkul/User/src/Models/Group.php
<?php namespace Webkul\User\Models; use Illuminate\Database\Eloquent\Model; use Webkul\User\Contracts\Group as GroupContract; class Group extends Model implements GroupContract { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'description', ]; /** * The users that belong to the group. */ public function users() { return $this->belongsToMany(UserProxy::modelClass(), 'user_groups'); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Repositories/RoleRepository.php
packages/Webkul/User/src/Repositories/RoleRepository.php
<?php namespace Webkul\User\Repositories; use Webkul\Core\Eloquent\Repository; class RoleRepository extends Repository { /** * Specify Model class name * * @return mixed */ public function model() { return 'Webkul\User\Contracts\Role'; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Repositories/GroupRepository.php
packages/Webkul/User/src/Repositories/GroupRepository.php
<?php namespace Webkul\User\Repositories; use Webkul\Core\Eloquent\Repository; class GroupRepository extends Repository { /** * Specify Model class name * * @return mixed */ public function model() { return 'Webkul\User\Contracts\Group'; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Repositories/UserRepository.php
packages/Webkul/User/src/Repositories/UserRepository.php
<?php namespace Webkul\User\Repositories; use Webkul\Core\Eloquent\Repository; class UserRepository extends Repository { /** * Searchable fields */ protected $fieldSearchable = [ 'name', 'email', 'status', 'view_permission', 'role_id', ]; /** * Specify Model class name * * @return mixed */ public function model() { return 'Webkul\User\Contracts\User'; } /** * This function will return user ids of current user's groups * * @return array */ public function getCurrentUserGroupsUserIds() { $userIds = $this->scopeQuery(function ($query) { return $query->select('users.*') ->leftJoin('user_groups', 'users.id', '=', 'user_groups.user_id') ->leftJoin('groups', 'user_groups.group_id', 'groups.id') ->whereIn('groups.id', auth()->guard('user')->user()->groups()->pluck('id')); })->get()->pluck('id')->toArray(); return $userIds; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Providers/UserServiceProvider.php
packages/Webkul/User/src/Providers/UserServiceProvider.php
<?php namespace Webkul\User\Providers; use Illuminate\Routing\Router; use Illuminate\Support\ServiceProvider; class UserServiceProvider extends ServiceProvider { /** * Bootstrap services. * * @return void */ public function boot(Router $router) { $this->loadMigrationsFrom(__DIR__.'/../Database/Migrations'); } /** * Register services. * * @return void */ public function register() {} }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/User/src/Providers/ModuleServiceProvider.php
packages/Webkul/User/src/Providers/ModuleServiceProvider.php
<?php namespace Webkul\User\Providers; use Webkul\Core\Providers\BaseModuleServiceProvider; class ModuleServiceProvider extends BaseModuleServiceProvider { protected $models = [ \Webkul\User\Models\Group::class, \Webkul\User\Models\Role::class, \Webkul\User\Models\User::class, ]; }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Helpers/Campaign.php
packages/Webkul/Marketing/src/Helpers/Campaign.php
<?php namespace Webkul\Marketing\Helpers; use Carbon\Carbon; use Illuminate\Support\Facades\Mail; use Webkul\Contact\Repositories\PersonRepository; use Webkul\Marketing\Mail\CampaignMail; use Webkul\Marketing\Repositories\CampaignRepository; use Webkul\Marketing\Repositories\EventRepository; class Campaign { /** * Create a new helper instance. * * * @return void */ public function __construct( protected EventRepository $eventRepository, protected CampaignRepository $campaignRepository, protected PersonRepository $personRepository, ) {} /** * Process the email. */ public function process(): void { $campaigns = $this->campaignRepository->getModel() ->leftJoin('marketing_events', 'marketing_campaigns.marketing_event_id', 'marketing_events.id') ->leftJoin('email_templates', 'marketing_campaigns.marketing_template_id', 'email_templates.id') ->select('marketing_campaigns.*') ->where('marketing_campaigns.status', 1) ->where(function ($query) { $query->where('marketing_events.date', Carbon::now()->format('Y-m-d')) ->orWhereNull('marketing_events.date'); }) ->get(); collect($campaigns)->each(function ($campaign) { collect($this->getPersonsEmails())->each(fn ($email) => Mail::queue(new CampaignMail($email, $campaign))); }); } /** * Get the email address. */ private function getPersonsEmails(): array { return $this->personRepository->pluck('emails') ->flatMap(fn ($emails) => collect($emails)->pluck('value')) ->all(); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Mail/CampaignMail.php
packages/Webkul/Marketing/src/Mail/CampaignMail.php
<?php namespace Webkul\Marketing\Mail; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Address; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; use Webkul\Marketing\Contracts\Campaign; class CampaignMail extends Mailable { /** * Create a new message instance. * * @return void */ public function __construct( public string $email, public Campaign $campaign ) {} /** * Get the message envelope. */ public function envelope(): Envelope { return new Envelope( to: [ new Address($this->email), ], subject: $this->campaign->subject, ); } /** * Get the message content definition. */ public function content(): Content { return new Content( htmlString: $this->campaign->email_template->content, ); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Contracts/Campaign.php
packages/Webkul/Marketing/src/Contracts/Campaign.php
<?php namespace Webkul\Marketing\Contracts; interface Campaign {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Contracts/Event.php
packages/Webkul/Marketing/src/Contracts/Event.php
<?php namespace Webkul\Marketing\Contracts; interface Event {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Database/Migrations/2024_10_29_044744_create_marketing_events_table.php
packages/Webkul/Marketing/src/Database/Migrations/2024_10_29_044744_create_marketing_events_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('marketing_events', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('description'); $table->date('date'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('marketing_events'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Database/Migrations/2024_11_04_122500_create_marketing_campaigns_table.php
packages/Webkul/Marketing/src/Database/Migrations/2024_11_04_122500_create_marketing_campaigns_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::create('marketing_campaigns', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('subject'); $table->boolean('status')->default(0); $table->string('type'); $table->string('mail_to'); $table->string('spooling')->nullable(); $table->unsignedInteger('marketing_template_id')->nullable(); $table->unsignedInteger('marketing_event_id')->nullable(); $table->timestamps(); $table->foreign('marketing_template_id')->references('id')->on('email_templates')->onDelete('set null'); $table->foreign('marketing_event_id')->references('id')->on('marketing_events')->onDelete('set null'); }); } public function down(): void { Schema::dropIfExists('marketing_campaigns'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Console/Commands/CampaignCommand.php
packages/Webkul/Marketing/src/Console/Commands/CampaignCommand.php
<?php namespace Webkul\Marketing\Console\Commands; use Illuminate\Console\Command; use Webkul\Marketing\Helpers\Campaign; class CampaignCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'campaign:process'; /** * The console command description. * * @var string */ protected $description = 'Process campaigns and send emails to the contact persons.'; /** * Create a new command instance. * * @return void */ public function __construct(protected Campaign $campaignHelper) { parent::__construct(); } /** * Execute the console command. */ public function handle() { $this->info('🚀 Starting campaign processing...'); try { $this->campaignHelper->process(); $this->info('✅ Campaign processing completed successfully!'); } catch (\Exception $e) { $this->error('❌ An error occurred during campaign processing: '.$e->getMessage()); } } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Models/Campaign.php
packages/Webkul/Marketing/src/Models/Campaign.php
<?php namespace Webkul\Marketing\Models; use Illuminate\Database\Eloquent\Model; use Webkul\EmailTemplate\Models\EmailTemplateProxy; use Webkul\Marketing\Contracts\Campaign as CampaignContract; class Campaign extends Model implements CampaignContract { /** * Define the table for the model. * * @var string */ protected $table = 'marketing_campaigns'; /** * The attributes that are fillable. * * @var array */ protected $fillable = [ 'name', 'subject', 'status', 'marketing_template_id', 'marketing_event_id', 'spooling', ]; /** * Get the email template */ public function email_template() { return $this->belongsTo(EmailTemplateProxy::modelClass(), 'marketing_template_id'); } /** * Get the event */ public function event() { return $this->belongsTo(EventProxy::modelClass(), 'marketing_event_id'); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Models/Event.php
packages/Webkul/Marketing/src/Models/Event.php
<?php namespace Webkul\Marketing\Models; use Illuminate\Database\Eloquent\Model; use Webkul\Marketing\Contracts\Event as EventContract; class Event extends Model implements EventContract { /** * The table associated with the model. * * @var string */ protected $table = 'marketing_events'; /** * The attributes that are fillable. * * @var array */ protected $fillable = [ 'name', 'description', 'date', ]; public function campaigns() { return $this->hasMany(CampaignProxy::modelClass(), 'marketing_event_id'); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Models/CampaignProxy.php
packages/Webkul/Marketing/src/Models/CampaignProxy.php
<?php namespace Webkul\Marketing\Models; use Konekt\Concord\Proxies\ModelProxy; class CampaignProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Models/EventProxy.php
packages/Webkul/Marketing/src/Models/EventProxy.php
<?php namespace Webkul\Marketing\Models; use Konekt\Concord\Proxies\ModelProxy; class EventProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Repositories/CampaignRepository.php
packages/Webkul/Marketing/src/Repositories/CampaignRepository.php
<?php namespace Webkul\Marketing\Repositories; use Webkul\Core\Eloquent\Repository; use Webkul\Marketing\Contracts\Campaign; class CampaignRepository extends Repository { /** * Specify Model class name. */ public function model(): string { return Campaign::class; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Repositories/EventRepository.php
packages/Webkul/Marketing/src/Repositories/EventRepository.php
<?php namespace Webkul\Marketing\Repositories; use Webkul\Core\Eloquent\Repository; use Webkul\Marketing\Contracts\Event; class EventRepository extends Repository { /** * Specify Model class name. */ public function model(): string { return Event::class; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Providers/MarketingServiceProvider.php
packages/Webkul/Marketing/src/Providers/MarketingServiceProvider.php
<?php namespace Webkul\Marketing\Providers; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Support\ServiceProvider; use Webkul\Marketing\Console\Commands\CampaignCommand; class MarketingServiceProvider extends ServiceProvider { /** * Bootstrap services. */ public function boot(): void { $this->loadMigrationsFrom(__DIR__.'/../Database/Migrations'); $this->callAfterResolving(Schedule::class, function (Schedule $schedule) { $schedule->command('campaign:process')->daily(); }); } /** * Register services. */ public function register(): void { $this->registerCommands(); $this->app->register(ModuleServiceProvider::class); } /** * Register the commands. */ private function registerCommands(): void { if ($this->app->runningInConsole()) { $this->commands([ CampaignCommand::class, ]); } } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Marketing/src/Providers/ModuleServiceProvider.php
packages/Webkul/Marketing/src/Providers/ModuleServiceProvider.php
<?php namespace Webkul\Marketing\Providers; use Webkul\Core\Providers\BaseModuleServiceProvider; class ModuleServiceProvider extends BaseModuleServiceProvider { /** * Define the module's array. * * @var array */ protected $models = [ \Webkul\Marketing\Models\Event::class, \Webkul\Marketing\Models\Campaign::class, ]; }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/EmailTemplate/src/Contracts/EmailTemplate.php
packages/Webkul/EmailTemplate/src/Contracts/EmailTemplate.php
<?php namespace Webkul\EmailTemplate\Contracts; interface EmailTemplate {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/EmailTemplate/src/Database/Migrations/2021_09_03_172713_create_email_templates_table.php
packages/Webkul/EmailTemplate/src/Database/Migrations/2021_09_03_172713_create_email_templates_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('email_templates', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('subject'); $table->text('content'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('email_templates'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/EmailTemplate/src/Database/Migrations/2025_07_09_133553_alter_email_templates_table.php
packages/Webkul/EmailTemplate/src/Database/Migrations/2025_07_09_133553_alter_email_templates_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('email_templates', function (Blueprint $table) { $table->string('name')->unique()->change(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('email_templates', function (Blueprint $table) { $table->dropUnique(['name']); $table->string('name')->change(); }); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/EmailTemplate/src/Models/EmailTemplateProxy.php
packages/Webkul/EmailTemplate/src/Models/EmailTemplateProxy.php
<?php namespace Webkul\EmailTemplate\Models; use Konekt\Concord\Proxies\ModelProxy; class EmailTemplateProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/EmailTemplate/src/Models/EmailTemplate.php
packages/Webkul/EmailTemplate/src/Models/EmailTemplate.php
<?php namespace Webkul\EmailTemplate\Models; use Illuminate\Database\Eloquent\Model; use Webkul\EmailTemplate\Contracts\EmailTemplate as EmailTemplateContract; class EmailTemplate extends Model implements EmailTemplateContract { protected $fillable = [ 'name', 'subject', 'content', ]; }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/EmailTemplate/src/Repositories/EmailTemplateRepository.php
packages/Webkul/EmailTemplate/src/Repositories/EmailTemplateRepository.php
<?php namespace Webkul\EmailTemplate\Repositories; use Webkul\Core\Eloquent\Repository; class EmailTemplateRepository extends Repository { /** * Specify Model class name * * @return mixed */ public function model() { return 'Webkul\EmailTemplate\Contracts\EmailTemplate'; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/EmailTemplate/src/Providers/EmailTemplateServiceProvider.php
packages/Webkul/EmailTemplate/src/Providers/EmailTemplateServiceProvider.php
<?php namespace Webkul\EmailTemplate\Providers; use Illuminate\Support\ServiceProvider; class EmailTemplateServiceProvider extends ServiceProvider { /** * Bootstrap services. * * @return void */ public function boot() { $this->loadMigrationsFrom(__DIR__.'/../Database/Migrations'); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/EmailTemplate/src/Providers/ModuleServiceProvider.php
packages/Webkul/EmailTemplate/src/Providers/ModuleServiceProvider.php
<?php namespace Webkul\EmailTemplate\Providers; use Webkul\Core\Providers\BaseModuleServiceProvider; class ModuleServiceProvider extends BaseModuleServiceProvider { protected $models = [ \Webkul\EmailTemplate\Models\EmailTemplate::class, ]; }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Jobs/Import/IndexBatch.php
packages/Webkul/DataTransfer/src/Jobs/Import/IndexBatch.php
<?php namespace Webkul\DataTransfer\Jobs\Import; use Illuminate\Bus\Batchable; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Webkul\DataTransfer\Helpers\Import as ImportHelper; class IndexBatch implements ShouldQueue { use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @param mixed $importBatch * @return void */ public function __construct(protected $importBatch) { $this->importBatch = $importBatch; } /** * Execute the job. * * @return void */ public function handle() { $typeImported = app(ImportHelper::class) ->setImport($this->importBatch->import) ->getTypeImporter(); $typeImported->indexBatch($this->importBatch); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Jobs/Import/Linking.php
packages/Webkul/DataTransfer/src/Jobs/Import/Linking.php
<?php namespace Webkul\DataTransfer\Jobs\Import; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Webkul\DataTransfer\Helpers\Import as ImportHelper; class Linking implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @param mixed $import * @return void */ public function __construct(protected $import) { $this->import = $import; } /** * Execute the job. * * @return void */ public function handle() { app(ImportHelper::class) ->setImport($this->import) ->linking(); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Jobs/Import/LinkBatch.php
packages/Webkul/DataTransfer/src/Jobs/Import/LinkBatch.php
<?php namespace Webkul\DataTransfer\Jobs\Import; use Illuminate\Bus\Batchable; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Webkul\DataTransfer\Helpers\Import as ImportHelper; class LinkBatch implements ShouldQueue { use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @param mixed $importBatch * @return void */ public function __construct(protected $importBatch) { $this->importBatch = $importBatch; } /** * Execute the job. * * @return void */ public function handle() { $typeImported = app(ImportHelper::class) ->setImport($this->importBatch->import) ->getTypeImporter(); $typeImported->linkBatch($this->importBatch); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Jobs/Import/Completed.php
packages/Webkul/DataTransfer/src/Jobs/Import/Completed.php
<?php namespace Webkul\DataTransfer\Jobs\Import; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Webkul\DataTransfer\Helpers\Import as ImportHelper; class Completed implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @param mixed $import * @return void */ public function __construct(protected $import) { $this->import = $import; } /** * Execute the job. * * @return void */ public function handle() { app(ImportHelper::class) ->setImport($this->import) ->completed(); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Jobs/Import/Indexing.php
packages/Webkul/DataTransfer/src/Jobs/Import/Indexing.php
<?php namespace Webkul\DataTransfer\Jobs\Import; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Webkul\DataTransfer\Helpers\Import as ImportHelper; class Indexing implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @param mixed $import * @return void */ public function __construct(protected $import) { $this->import = $import; } /** * Execute the job. * * @return void */ public function handle() { app(ImportHelper::class) ->setImport($this->import) ->indexing(); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Jobs/Import/ImportBatch.php
packages/Webkul/DataTransfer/src/Jobs/Import/ImportBatch.php
<?php namespace Webkul\DataTransfer\Jobs\Import; use Illuminate\Bus\Batchable; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Webkul\DataTransfer\Helpers\Import as ImportHelper; class ImportBatch implements ShouldQueue { use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @param mixed $importBatch * @return void */ public function __construct(protected $importBatch) { $this->importBatch = $importBatch; } /** * Execute the job. * * @return void */ public function handle() { $typeImported = app(ImportHelper::class) ->setImport($this->importBatch->import) ->getTypeImporter(); $typeImported->importBatch($this->importBatch); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Error.php
packages/Webkul/DataTransfer/src/Helpers/Error.php
<?php namespace Webkul\DataTransfer\Helpers; class Error { /** * Error Items. */ protected array $items = []; /** * Invalid rows. */ protected array $invalidRows = []; /** * Skipped rows. */ protected array $skippedRows = []; /** * Errors count. */ protected int $errorsCount = 0; /** * Error message template. */ protected array $messageTemplate = []; /** * Add error message template. */ public function addErrorMessage(string $code, string $template): self { $this->messageTemplate[$code] = $template; return $this; } /** * Add error message. */ public function addError(string $code, ?int $rowNumber = null, ?string $columnName = null, ?string $message = null): self { if ($this->isErrorAlreadyAdded($rowNumber, $code, $columnName)) { return $this; } $this->addRowToInvalid($rowNumber); $message = $this->getErrorMessage($code, $message, $columnName); $this->items[$rowNumber][] = [ 'code' => $code, 'column' => $columnName, 'message' => $message, ]; $this->errorsCount++; return $this; } /** * Check if error is already added for the row, code and column. */ public function isErrorAlreadyAdded(?int $rowNumber, string $code, ?string $columnName): bool { return collect($this->items[$rowNumber] ?? []) ->where('code', $code) ->where('column', $columnName) ->isNotEmpty(); } /** * Add specific row to invalid list via row number. */ protected function addRowToInvalid(?int $rowNumber): self { if (is_null($rowNumber)) { return $this; } if (! in_array($rowNumber, $this->invalidRows)) { $this->invalidRows[] = $rowNumber; } return $this; } /** * Add specific row to invalid list via row number. */ public function addRowToSkip(?int $rowNumber): self { if (is_null($rowNumber)) { return $this; } if (! in_array($rowNumber, $this->skippedRows)) { $this->skippedRows[] = $rowNumber; } return $this; } /** * Check if row is invalid by row number. */ public function isRowInvalid(int $rowNumber): bool { return in_array($rowNumber, array_merge($this->invalidRows, $this->skippedRows)); } /** * Build an error message via code, message and column name. */ protected function getErrorMessage(?string $code, ?string $message, ?string $columnName): string { if ( empty($message) && isset($this->messageTemplate[$code]) ) { $message = (string) $this->messageTemplate[$code]; } if ( $columnName && $message ) { $message = sprintf($message, $columnName); } if (! $message) { $message = $code; } return $message; } /** * Get number of invalid rows. */ public function getInvalidRowsCount(): int { return count($this->invalidRows); } /** * Get current error count. */ public function getErrorsCount(): int { return $this->errorsCount; } /** * Get all errors from an import process. */ public function getAllErrors(): array { return $this->items; } /** * Return all errors grouped by code. */ public function getAllErrorsGroupedByCode(): array { $errors = []; foreach ($this->items as $rowNumber => $rowErrors) { foreach ($rowErrors as $error) { if ($rowNumber === '') { $errors[$error['code']][$error['message']] = null; } else { $errors[$error['code']][$error['message']][] = $rowNumber; } } } return $errors; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Import.php
packages/Webkul/DataTransfer/src/Helpers/Import.php
<?php namespace Webkul\DataTransfer\Helpers; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Csv; use PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Webkul\DataTransfer\Contracts\Import as ImportContract; use Webkul\DataTransfer\Contracts\ImportBatch as ImportBatchContract; use Webkul\DataTransfer\Helpers\Importers\AbstractImporter; use Webkul\DataTransfer\Helpers\Sources\AbstractSource; use Webkul\DataTransfer\Helpers\Sources\CSV as CSVSource; use Webkul\DataTransfer\Helpers\Sources\Excel as ExcelSource; use Webkul\DataTransfer\Repositories\ImportBatchRepository; use Webkul\DataTransfer\Repositories\ImportRepository; class Import { /** * Import state for pending import. */ public const STATE_PENDING = 'pending'; /** * Import state for validated import. */ public const STATE_VALIDATED = 'validated'; /** * Import state for processing import. */ public const STATE_PROCESSING = 'processing'; /** * Import state for processed import. */ public const STATE_PROCESSED = 'processed'; /** * Import state for linking import. */ public const STATE_LINKING = 'linking'; /** * Import state for linked import. */ public const STATE_LINKED = 'linked'; /** * Import state for indexing import. */ public const STATE_INDEXING = 'indexing'; /** * Import state for indexed import. */ public const STATE_INDEXED = 'indexed'; /** * Import state for completed import. */ public const STATE_COMPLETED = 'completed'; /** * Validation strategy for skipping the error during the import process. */ public const VALIDATION_STRATEGY_SKIP_ERRORS = 'skip-errors'; /** * Validation strategy for stopping the import process on error. */ public const VALIDATION_STRATEGY_STOP_ON_ERROR = 'stop-on-errors'; /** * Action constant for updating/creating for the resource. */ public const ACTION_APPEND = 'append'; /** * Action constant for deleting the resource. */ public const ACTION_DELETE = 'delete'; /** * Import instance. */ protected ImportContract $import; /** * Error helper instance. * * @var \Webkul\DataTransfer\Helpers\Error */ protected $typeImporter; /** * Create a new helper instance. * * @return void */ public function __construct( protected ImportRepository $importRepository, protected ImportBatchRepository $importBatchRepository, protected Error $errorHelper ) {} /** * Set import instance. */ public function setImport(ImportContract $import): self { $this->import = $import; return $this; } /** * Returns import instance. */ public function getImport(): ImportContract { return $this->import; } /** * Returns error helper instance. * * @return \Webkul\DataTransfer\Helpers\Error */ public function getErrorHelper() { return $this->errorHelper; } /** * Returns source helper instance. */ public function getSource(): AbstractSource { if (Str::contains($this->import->file_path, '.csv')) { $source = new CSVSource( $this->import->file_path, $this->import->field_separator, ); } else { $source = new ExcelSource( $this->import->file_path, $this->import->field_separator, ); } return $source; } /** * Validates import and returns validation result. */ public function validate(): bool { try { $source = $this->getSource(); $typeImporter = $this->getTypeImporter()->setSource($source); $typeImporter->validateData(); } catch (\Exception $e) { $this->errorHelper->addError( AbstractImporter::ERROR_CODE_SYSTEM_EXCEPTION, null, null, $e->getMessage() ); } $import = $this->importRepository->update([ 'state' => self::STATE_VALIDATED, 'processed_rows_count' => $this->getProcessedRowsCount(), 'invalid_rows_count' => $this->errorHelper->getInvalidRowsCount(), 'errors_count' => $this->errorHelper->getErrorsCount(), 'errors' => $this->getFormattedErrors(), 'error_file_path' => $this->uploadErrorReport(), ], $this->import->id); $this->setImport($import); return $this->isValid(); } /** * Starts import process. */ public function isValid(): bool { if ($this->isErrorLimitExceeded()) { return false; } if ($this->import->processed_rows_count <= $this->import->invalid_rows_count) { return false; } return true; } /** * Check if error limit has been exceeded. */ public function isErrorLimitExceeded(): bool { if ( $this->import->validation_strategy == self::VALIDATION_STRATEGY_STOP_ON_ERROR && $this->import->errors_count > $this->import->allowed_errors ) { return true; } return false; } /** * Starts import process. */ public function start(?ImportBatchContract $importBatch = null): bool { DB::beginTransaction(); try { $typeImporter = $this->getTypeImporter(); $typeImporter->importData($importBatch); } catch (\Exception $e) { /** * Rollback transaction. */ DB::rollBack(); throw $e; } finally { /** * Commit transaction. */ DB::commit(); } return true; } /** * Link import resources. */ public function link(ImportBatchContract $importBatch): bool { DB::beginTransaction(); try { $typeImporter = $this->getTypeImporter(); $typeImporter->linkData($importBatch); } catch (\Exception $e) { /** * Rollback transaction. */ DB::rollBack(); throw $e; } finally { /** * Commit transaction. */ DB::commit(); } return true; } /** * Index import resources. */ public function index(ImportBatchContract $importBatch): bool { DB::beginTransaction(); try { $typeImporter = $this->getTypeImporter(); $typeImporter->indexData($importBatch); } catch (\Exception $e) { /** * Rollback transaction. */ DB::rollBack(); throw $e; } finally { /** * Commit transaction. */ DB::commit(); } return true; } /** * Started the import process. */ public function started(): void { $import = $this->importRepository->update([ 'state' => self::STATE_PROCESSING, 'started_at' => now(), 'summary' => [], ], $this->import->id); $this->setImport($import); Event::dispatch('data_transfer.imports.started', $import); } /** * Started the import linking process. */ public function linking(): void { $import = $this->importRepository->update([ 'state' => self::STATE_LINKING, ], $this->import->id); $this->setImport($import); Event::dispatch('data_transfer.imports.linking', $import); } /** * Started the import indexing process. */ public function indexing(): void { $import = $this->importRepository->update([ 'state' => self::STATE_INDEXING, ], $this->import->id); $this->setImport($import); Event::dispatch('data_transfer.imports.indexing', $import); } /** * Start the import process. */ public function completed(): void { $summary = $this->importBatchRepository ->select( DB::raw('SUM(json_unquote(json_extract(summary, \'$."created"\'))) AS created'), DB::raw('SUM(json_unquote(json_extract(summary, \'$."updated"\'))) AS updated'), DB::raw('SUM(json_unquote(json_extract(summary, \'$."deleted"\'))) AS deleted'), ) ->where('import_id', $this->import->id) ->groupBy('import_id') ->first() ->toArray(); $import = $this->importRepository->update([ 'state' => self::STATE_COMPLETED, 'summary' => $summary, 'completed_at' => now(), ], $this->import->id); $this->setImport($import); Event::dispatch('data_transfer.imports.completed', $import); } /** * Returns import stats. */ public function stats(string $state): array { $total = $this->import->batches->count(); $completed = $this->import->batches->where('state', $state)->count(); $progress = $total ? round($completed / $total * 100) : 0; $summary = $this->importBatchRepository ->select( DB::raw('SUM(json_unquote(json_extract(summary, \'$."created"\'))) AS created'), DB::raw('SUM(json_unquote(json_extract(summary, \'$."updated"\'))) AS updated'), DB::raw('SUM(json_unquote(json_extract(summary, \'$."deleted"\'))) AS deleted'), ) ->where('import_id', $this->import->id) ->where('state', $state) ->groupBy('import_id') ->first() ?->toArray(); return [ 'batches' => [ 'total' => $total, 'completed' => $completed, 'remaining' => $total - $completed, ], 'progress' => $progress, 'summary' => $summary ?? [ 'created' => 0, 'updated' => 0, 'deleted' => 0, ], ]; } /** * Return all error grouped by error code. */ public function getFormattedErrors(): array { $errors = []; foreach ($this->errorHelper->getAllErrorsGroupedByCode() as $groupedErrors) { foreach ($groupedErrors as $errorMessage => $rowNumbers) { if (! empty($rowNumbers)) { $errors[] = 'Row(s) '.implode(', ', $rowNumbers).': '.$errorMessage; } else { $errors[] = $errorMessage; } } } return $errors; } /** * Uploads error report and save the path to the database. */ public function uploadErrorReport(): ?string { /** * Return null if there are no errors. */ if (! $this->errorHelper->getErrorsCount()) { return null; } /** * Return null if there are no invalid rows. */ if (! $this->errorHelper->getInvalidRowsCount()) { return null; } $errors = $this->errorHelper->getAllErrors(); $source = $this->getTypeImporter()->getSource(); $source->rewind(); $spreadsheet = new Spreadsheet; $sheet = $spreadsheet->getActiveSheet(); /** * Add headers with extra error column. */ $sheet->fromArray( [array_merge($source->getColumnNames(), [ 'error', ])], null, 'A1' ); $rowNumber = 2; while ($source->valid()) { try { $rowData = $source->current(); } catch (\InvalidArgumentException $e) { $source->next(); continue; } $rowErrors = $errors[$source->getCurrentRowNumber()] ?? []; if (! empty($rowErrors)) { $rowErrors = Arr::pluck($rowErrors, 'message'); } $rowData[] = implode('|', $rowErrors); $sheet->fromArray([$rowData], null, 'A'.$rowNumber++); $source->next(); } $fileType = pathinfo($this->import->file_path, PATHINFO_EXTENSION); switch ($fileType) { case 'csv': $writer = new Csv($spreadsheet); $writer->setDelimiter($this->import->field_separator); break; case 'xls': $writer = new Xls($spreadsheet); case 'xlsx': $writer = new Xlsx($spreadsheet); break; default: throw new \InvalidArgumentException("Unsupported file type: $fileType"); } $errorFilePath = 'imports/'.time().'-error-report.'.$fileType; $writer->save(Storage::disk('public')->path($errorFilePath)); return $errorFilePath; } /** * Validates source file and returns validation result. */ public function getTypeImporter(): AbstractImporter { if (! $this->typeImporter) { $importerConfig = config('importers.'.$this->import->type); $this->typeImporter = app()->make($importerConfig['importer']) ->setImport($this->import) ->setErrorHelper($this->errorHelper); } return $this->typeImporter; } /** * Returns number of checked rows. */ public function getProcessedRowsCount(): int { return $this->getTypeImporter()->getProcessedRowsCount(); } /** * Is linking resource required for the import operation. */ public function isLinkingRequired(): bool { return $this->getTypeImporter()->isLinkingRequired(); } /** * Is indexing resource required for the import operation. */ public function isIndexingRequired(): bool { return $this->getTypeImporter()->isIndexingRequired(); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Sources/CSV.php
packages/Webkul/DataTransfer/src/Helpers/Sources/CSV.php
<?php namespace Webkul\DataTransfer\Helpers\Sources; use Illuminate\Support\Facades\Storage; class CSV extends AbstractSource { /** * CSV reader. */ protected mixed $reader; /** * Create a new helper instance. * * @return void */ public function __construct( string $filePath, protected string $delimiter = ',' ) { try { $this->reader = fopen(Storage::disk('public')->path($filePath), 'r'); $this->columnNames = fgetcsv($this->reader, 4096, $delimiter); $this->totalColumns = count($this->columnNames); } catch (\Exception $e) { throw new \LogicException("Unable to open file: '{$filePath}'"); } } /** * Close file handle. * * @return void */ public function __destruct() { if (! is_object($this->reader)) { return; } $this->reader->close(); } /** * Read next line from csv. */ protected function getNextRow(): array { $parsed = fgetcsv($this->reader, 4096, $this->delimiter); if (is_array($parsed) && count($parsed) != $this->totalColumns) { foreach ($parsed as $element) { if ($element && strpos($element, "'") !== false) { $this->foundWrongQuoteFlag = true; break; } } } else { $this->foundWrongQuoteFlag = false; } return is_array($parsed) ? $parsed : []; } /** * Rewind the iterator to the first row. */ public function rewind(): void { rewind($this->reader); parent::rewind(); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Sources/Excel.php
packages/Webkul/DataTransfer/src/Helpers/Sources/Excel.php
<?php namespace Webkul\DataTransfer\Helpers\Sources; use Illuminate\Support\Facades\Storage; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\IOFactory; class Excel extends AbstractSource { /** * CSV reader. */ protected mixed $reader; /** * Current row number. */ protected int $currentRowNumber = 1; /** * Create a new helper instance. * * @return void */ public function __construct(string $filePath) { try { $factory = IOFactory::load(Storage::disk('public')->path($filePath)); $this->reader = $factory->getActiveSheet(); $highestColumn = $this->reader->getHighestColumn(); $this->totalColumns = Coordinate::columnIndexFromString($highestColumn); $this->columnNames = $this->getNextRow(); } catch (\Exception $e) { throw new \LogicException("Unable to open file: '{$filePath}'"); } } /** * Read next line from csv. */ protected function getNextRow(): array|bool { for ($column = 1; $column <= $this->totalColumns; $column++) { $rowData[] = $this->reader->getCellByColumnAndRow($column, $this->currentRowNumber)->getValue(); } $filteredRowData = array_filter($rowData); if (empty($filteredRowData)) { return false; } return $rowData; } /** * Rewind the iterator to the first row. */ public function rewind(): void { $this->currentRowNumber = 1; $this->next(); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Sources/AbstractSource.php
packages/Webkul/DataTransfer/src/Helpers/Sources/AbstractSource.php
<?php namespace Webkul\DataTransfer\Helpers\Sources; use Webkul\DataTransfer\Helpers\Importers\AbstractImporter; abstract class AbstractSource { /** * Column names. */ protected array $columnNames = []; /** * Quantity of columns. */ protected int $totalColumns = 0; /** * Current row. */ protected array $currentRowData = []; /** * Current row number. */ protected int $currentRowNumber = -1; /** * Flag to indicate that wrong quote was found. */ protected bool $foundWrongQuoteFlag = false; /** * Read next line from source. */ abstract protected function getNextRow(): array|bool; /** * Return the key of the current row. */ public function getCurrentRowNumber(): int { return $this->currentRowNumber; } /** * Checks if current position is valid. */ public function valid(): bool { return $this->currentRowNumber !== -1; } /** * Read next line from source. */ public function current(): array { $row = $this->currentRowData; if (count($row) != $this->totalColumns) { if ($this->foundWrongQuoteFlag) { throw new \InvalidArgumentException(AbstractImporter::ERROR_CODE_WRONG_QUOTES); } else { throw new \InvalidArgumentException(AbstractImporter::ERROR_CODE_COLUMNS_NUMBER); } } return array_combine($this->columnNames, $row); } /** * Read next line from source. */ public function next(): void { $this->currentRowNumber++; $row = $this->getNextRow(); if ($row === false || $row === []) { $this->currentRowData = []; $this->currentRowNumber = -1; } else { $this->currentRowData = $row; } } /** * Rewind the iterator to the first row. */ public function rewind(): void { $this->currentRowNumber = 0; $this->currentRowData = []; $this->getNextRow(); $this->next(); } /** * Column names getter. */ public function getColumnNames(): array { return $this->columnNames; } /** * Column names getter. */ public function getTotalColumns(): int { return count($this->columnNames); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Importers/AbstractImporter.php
packages/Webkul/DataTransfer/src/Helpers/Importers/AbstractImporter.php
<?php namespace Webkul\DataTransfer\Helpers\Importers; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Event; use Webkul\Attribute\Repositories\AttributeRepository; use Webkul\Attribute\Repositories\AttributeValueRepository; use Webkul\Core\Contracts\Validations\Decimal; use Webkul\DataTransfer\Contracts\Import as ImportContract; use Webkul\DataTransfer\Contracts\ImportBatch as ImportBatchContract; use Webkul\DataTransfer\Helpers\Import; use Webkul\DataTransfer\Jobs\Import\Completed as CompletedJob; use Webkul\DataTransfer\Jobs\Import\ImportBatch as ImportBatchJob; use Webkul\DataTransfer\Jobs\Import\IndexBatch as IndexBatchJob; use Webkul\DataTransfer\Jobs\Import\Indexing as IndexingJob; use Webkul\DataTransfer\Jobs\Import\LinkBatch as LinkBatchJob; use Webkul\DataTransfer\Jobs\Import\Linking as LinkingJob; use Webkul\DataTransfer\Repositories\ImportBatchRepository; abstract class AbstractImporter { /** * Error code for system exception. */ public const ERROR_CODE_SYSTEM_EXCEPTION = 'system_exception'; /** * Error code for column not found. */ public const ERROR_CODE_COLUMN_NOT_FOUND = 'column_not_found'; /** * Error code for column empty header. */ public const ERROR_CODE_COLUMN_EMPTY_HEADER = 'column_empty_header'; /** * Error code for column name invalid. */ public const ERROR_CODE_COLUMN_NAME_INVALID = 'column_name_invalid'; /** * Error code for invalid attribute. */ public const ERROR_CODE_INVALID_ATTRIBUTE = 'invalid_attribute_name'; /** * Error code for wrong quotes. */ public const ERROR_CODE_WRONG_QUOTES = 'wrong_quotes'; /** * Error code for wrong columns number. */ public const ERROR_CODE_COLUMNS_NUMBER = 'wrong_columns_number'; /** * Error message templates. */ protected array $errorMessages = [ self::ERROR_CODE_SYSTEM_EXCEPTION => 'data_transfer::app.validation.errors.system', self::ERROR_CODE_COLUMN_NOT_FOUND => 'data_transfer::app.validation.errors.column-not-found', self::ERROR_CODE_COLUMN_EMPTY_HEADER => 'data_transfer::app.validation.errors.column-empty-headers', self::ERROR_CODE_COLUMN_NAME_INVALID => 'data_transfer::app.validation.errors.column-name-invalid', self::ERROR_CODE_INVALID_ATTRIBUTE => 'data_transfer::app.validation.errors.invalid-attribute', self::ERROR_CODE_WRONG_QUOTES => 'data_transfer::app.validation.errors.wrong-quotes', self::ERROR_CODE_COLUMNS_NUMBER => 'data_transfer::app.validation.errors.column-numbers', ]; public const BATCH_SIZE = 100; /** * Is linking required. */ protected bool $linkingRequired = false; /** * Is indexing required. */ protected bool $indexingRequired = false; /** * Error helper instance. * * @var \Webkul\DataTransfer\Helpers\Error */ protected $errorHelper; /** * Import instance. */ protected ImportContract $import; /** * Source instance. * * @var \Webkul\DataTransfer\Helpers\Source */ protected $source; /** * Valid column names. */ protected array $validColumnNames = []; /** * Array of numbers of validated rows as keys and boolean TRUE as values. */ protected array $validatedRows = []; /** * Number of rows processed by validation. */ protected int $processedRowsCount = 0; /** * Number of created items. */ protected int $createdItemsCount = 0; /** * Number of updated items. */ protected int $updatedItemsCount = 0; /** * Number of deleted items. */ protected int $deletedItemsCount = 0; /** * Create a new helper instance. * * @return void */ public function __construct( protected ImportBatchRepository $importBatchRepository, protected AttributeRepository $attributeRepository, protected AttributeValueRepository $attributeValueRepository ) {} /** * Validate data row. */ abstract public function validateRow(array $rowData, int $rowNumber): bool; /** * Import data rows. */ abstract public function importBatch(ImportBatchContract $importBatchContract): bool; /** * Initialize Product error messages. */ protected function initErrorMessages(): void { foreach ($this->errorMessages as $errorCode => $message) { $this->errorHelper->addErrorMessage($errorCode, trans($message)); } } /** * Import instance. */ public function setImport(ImportContract $import): self { $this->import = $import; return $this; } /** * Import instance. * * @param \Webkul\DataTransfer\Helpers\Source $errorHelper */ public function setSource($source) { $this->source = $source; return $this; } /** * Import instance. * * @param \Webkul\DataTransfer\Helpers\Error $errorHelper */ public function setErrorHelper($errorHelper): self { $this->errorHelper = $errorHelper; $this->initErrorMessages(); return $this; } /** * Import instance. * * @return \Webkul\DataTransfer\Helpers\Source */ public function getSource() { return $this->source; } /** * Retrieve valid column names. */ public function getValidColumnNames(): array { return $this->validColumnNames; } /** * Validate data. */ public function validateData(): void { Event::dispatch('data_transfer.imports.validate.before', $this->import); $errors = []; $absentColumns = array_diff($this->permanentAttributes, $columns = $this->getSource()->getColumnNames()); if (! empty($absentColumns)) { $errors[self::ERROR_CODE_COLUMN_NOT_FOUND] = $absentColumns; } foreach ($columns as $columnNumber => $columnName) { if (empty($columnName)) { $errors[self::ERROR_CODE_COLUMN_EMPTY_HEADER][] = $columnNumber + 1; } elseif (! preg_match('/^[a-z][a-z0-9_]*$/', $columnName)) { $errors[self::ERROR_CODE_COLUMN_NAME_INVALID][] = $columnName; } elseif (! in_array($columnName, $this->getValidColumnNames())) { $errors[self::ERROR_CODE_INVALID_ATTRIBUTE][] = $columnName; } } /** * Add Columns Errors. */ foreach ($errors as $errorCode => $error) { $this->addErrors($errorCode, $error); } if (! $this->errorHelper->getErrorsCount()) { $this->saveValidatedBatches(); } Event::dispatch('data_transfer.imports.validate.after', $this->import); } /** * Save validated batches. */ protected function saveValidatedBatches(): self { $source = $this->getSource(); $batchRows = []; $source->rewind(); /** * Clean previous saved batches. */ $this->importBatchRepository->deleteWhere([ 'import_id' => $this->import->id, ]); while ( $source->valid() || count($batchRows) ) { if ( count($batchRows) == self::BATCH_SIZE || ! $source->valid() ) { $this->importBatchRepository->create([ 'import_id' => $this->import->id, 'data' => $batchRows, ]); $batchRows = []; } if ($source->valid()) { $rowData = $source->current(); if ($this->validateRow($rowData, $source->getCurrentRowNumber())) { $batchRows[] = $this->prepareRowForDb($rowData); } $this->processedRowsCount++; $source->next(); } } return $this; } /** * Prepare validation rules. */ public function getValidationRules(string $entityType, array $rowData): array { if (empty($entityType)) { return []; } $rules = []; $attributes = $this->attributeRepository->scopeQuery(fn ($query) => $query->whereIn('code', array_keys($rowData))->where('entity_type', $entityType))->get(); foreach ($attributes as $attribute) { $validations = []; if ($attribute->type == 'boolean') { continue; } elseif ($attribute->type == 'address') { if (! $attribute->is_required) { continue; } $validations = [ $attribute->code.'.address' => 'required', $attribute->code.'.country' => 'required', $attribute->code.'.state' => 'required', $attribute->code.'.city' => 'required', $attribute->code.'.postcode' => 'required', ]; } elseif ($attribute->type == 'email') { $validations = [ $attribute->code => [$attribute->is_required ? 'required' : 'nullable'], $attribute->code.'.*.value' => [$attribute->is_required ? 'required' : 'nullable', 'email'], $attribute->code.'.*.label' => $attribute->is_required ? 'required' : 'nullable', ]; } elseif ($attribute->type == 'phone') { $validations = [ $attribute->code => [$attribute->is_required ? 'required' : 'nullable'], $attribute->code.'.*.value' => [$attribute->is_required ? 'required' : 'nullable'], $attribute->code.'.*.label' => $attribute->is_required ? 'required' : 'nullable', ]; } else { $validations[$attribute->code] = [$attribute->is_required ? 'required' : 'nullable']; if ($attribute->type == 'text' && $attribute->validation) { array_push($validations[$attribute->code], $attribute->validation == 'decimal' ? new Decimal : $attribute->validation ); } if ($attribute->type == 'price') { array_push($validations[$attribute->code], new Decimal); } } if ($attribute->is_unique) { array_push($validations[in_array($attribute->type, ['email', 'phone']) ? $attribute->code.'.*.value' : $attribute->code ], function ($field, $value, $fail) use ($attribute) { if (! $this->attributeValueRepository->isValueUnique(null, $attribute->entity_type, $attribute, $field)) { $fail(trans('data_transfer::app.validation.errors.already-exists', ['attribute' => $attribute->name])); } }); } $rules = [ ...$rules, ...$validations, ]; } return $rules; } /** * Start the import process. */ public function importData(?ImportBatchContract $importBatch = null): bool { if ($importBatch) { $this->importBatch($importBatch); return true; } $typeBatches = []; foreach ($this->import->batches as $batch) { $typeBatches['import'][] = new ImportBatchJob($batch); if ($this->isLinkingRequired()) { $typeBatches['link'][] = new LinkBatchJob($batch); } if ($this->isIndexingRequired()) { $typeBatches['index'][] = new IndexBatchJob($batch); } } $chain[] = Bus::batch($typeBatches['import']); if (! empty($typeBatches['link'])) { $chain[] = new LinkingJob($this->import); $chain[] = Bus::batch($typeBatches['link']); } if (! empty($typeBatches['index'])) { $chain[] = new IndexingJob($this->import); $chain[] = Bus::batch($typeBatches['index']); } $chain[] = new CompletedJob($this->import); Bus::chain($chain)->dispatch(); return true; } /** * Link resource data. */ public function linkData(ImportBatchContract $importBatch): bool { $this->linkBatch($importBatch); return true; } /** * Index resource data. */ public function indexData(ImportBatchContract $importBatch): bool { $this->indexBatch($importBatch); return true; } /** * Add errors to error aggregator. */ protected function addErrors(string $code, mixed $errors): void { $this->errorHelper->addError( $code, null, implode('", "', $errors) ); } /** * Add row as skipped. * * @param int|null $rowNumber * @param string|null $columnName * @param string|null $errorMessage * @return $this */ protected function skipRow($rowNumber, string $errorCode, $columnName = null, $errorMessage = null): self { $this->errorHelper->addError( $errorCode, $rowNumber, $columnName, $errorMessage ); $this->errorHelper->addRowToSkip($rowNumber); return $this; } /** * Prepare row data to save into the database. */ protected function prepareRowForDb(array $rowData): array { $rowData = array_map(function ($value) { return $value === '' ? null : $value; }, $rowData); return $rowData; } /** * Returns number of checked rows. */ public function getProcessedRowsCount(): int { return $this->processedRowsCount; } /** * Returns number of created items count. */ public function getCreatedItemsCount(): int { return $this->createdItemsCount; } /** * Returns number of updated items count. */ public function getUpdatedItemsCount(): int { return $this->updatedItemsCount; } /** * Returns number of deleted items count. */ public function getDeletedItemsCount(): int { return $this->deletedItemsCount; } /** * Is linking resource required for the import operation. */ public function isLinkingRequired(): bool { if ($this->import->action == Import::ACTION_DELETE) { return false; } return $this->linkingRequired; } /** * Is indexing resource required for the import operation. */ public function isIndexingRequired(): bool { if ($this->import->action == Import::ACTION_DELETE) { return false; } return $this->indexingRequired; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Importers/Products/SKUStorage.php
packages/Webkul/DataTransfer/src/Helpers/Importers/Products/SKUStorage.php
<?php namespace Webkul\DataTransfer\Helpers\Importers\Products; use Webkul\Product\Repositories\ProductRepository; class SKUStorage { /** * Delimiter for SKU information. */ private const DELIMITER = '|'; /** * Items contains SKU as key and product information as value. */ protected array $items = []; /** * Columns which will be selected from database. */ protected array $selectColumns = [ 'id', 'sku', ]; /** * Create a new helper instance. * * @return void */ public function __construct(protected ProductRepository $productRepository) {} /** * Initialize storage. */ public function init(): void { $this->items = []; $this->load(); } /** * Load the SKU. */ public function load(array $skus = []): void { if (empty($skus)) { $products = $this->productRepository->all($this->selectColumns); } else { $products = $this->productRepository->findWhereIn('sku', $skus, $this->selectColumns); } foreach ($products as $product) { $this->set($product->sku, [ 'id' => $product->id, 'sku' => $product->sku, ]); } } /** * Get SKU information. */ public function set(string $sku, array $data): self { $this->items[$sku] = implode(self::DELIMITER, [ $data['id'], $data['sku'], ]); return $this; } /** * Check if SKU exists. */ public function has(string $sku): bool { return isset($this->items[$sku]); } /** * Get SKU information. */ public function get(string $sku): ?array { if (! $this->has($sku)) { return null; } $data = explode(self::DELIMITER, $this->items[$sku]); return [ 'id' => $data[0], ]; } /** * Is storage is empty. */ public function isEmpty(): int { return empty($this->items); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Importers/Products/Importer.php
packages/Webkul/DataTransfer/src/Helpers/Importers/Products/Importer.php
<?php namespace Webkul\DataTransfer\Helpers\Importers\Products; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Validator; use Webkul\Attribute\Repositories\AttributeOptionRepository; use Webkul\Attribute\Repositories\AttributeRepository; use Webkul\Attribute\Repositories\AttributeValueRepository; use Webkul\DataTransfer\Contracts\ImportBatch as ImportBatchContract; use Webkul\DataTransfer\Helpers\Import; use Webkul\DataTransfer\Helpers\Importers\AbstractImporter; use Webkul\DataTransfer\Repositories\ImportBatchRepository; use Webkul\Product\Repositories\ProductInventoryRepository; use Webkul\Product\Repositories\ProductRepository; class Importer extends AbstractImporter { /** * Error code for non existing SKU. */ const ERROR_SKU_NOT_FOUND_FOR_DELETE = 'sku_not_found_to_delete'; /** * Error message templates. */ protected array $messages = [ self::ERROR_SKU_NOT_FOUND_FOR_DELETE => 'data_transfer::app.importers.products.validation.errors.sku-not-found', ]; /** * Permanent entity columns. */ protected array $permanentAttributes = ['sku']; /** * Permanent entity column. */ protected string $masterAttributeCode = 'sku'; /** * Cached attributes. */ protected mixed $attributes = []; /** * Valid csv columns. */ protected array $validColumnNames = [ 'sku', 'name', 'description', 'quantity', 'price', ]; /** * Create a new helper instance. * * @return void */ public function __construct( protected ImportBatchRepository $importBatchRepository, protected AttributeRepository $attributeRepository, protected AttributeOptionRepository $attributeOptionRepository, protected ProductRepository $productRepository, protected ProductInventoryRepository $productInventoryRepository, protected AttributeValueRepository $attributeValueRepository, protected SKUStorage $skuStorage ) { parent::__construct( $importBatchRepository, $attributeRepository, $attributeValueRepository ); $this->initAttributes(); } /** * Load all attributes and families to use later. */ protected function initAttributes(): void { $this->attributes = $this->attributeRepository->all(); foreach ($this->attributes as $attribute) { $this->validColumnNames[] = $attribute->code; } } /** * Initialize Product error templates. */ protected function initErrorMessages(): void { foreach ($this->messages as $errorCode => $message) { $this->errorHelper->addErrorMessage($errorCode, trans($message)); } parent::initErrorMessages(); } /** * Save validated batches. */ protected function saveValidatedBatches(): self { $source = $this->getSource(); $source->rewind(); $this->skuStorage->init(); while ($source->valid()) { try { $rowData = $source->current(); } catch (\InvalidArgumentException $e) { $source->next(); continue; } $this->validateRow($rowData, $source->getCurrentRowNumber()); $source->next(); } parent::saveValidatedBatches(); return $this; } /** * Validates row. */ public function validateRow(array $rowData, int $rowNumber): bool { /** * If row is already validated than no need for further validation. */ if (isset($this->validatedRows[$rowNumber])) { return ! $this->errorHelper->isRowInvalid($rowNumber); } $this->validatedRows[$rowNumber] = true; /** * If import action is delete than no need for further validation. */ if ($this->import->action == Import::ACTION_DELETE) { if (! $this->isSKUExist($rowData['sku'])) { $this->skipRow($rowNumber, self::ERROR_SKU_NOT_FOUND_FOR_DELETE, 'sku'); return false; } return true; } /** * Validate product attributes */ $validator = Validator::make($rowData, $this->getValidationRules('products', $rowData)); if ($validator->fails()) { foreach ($validator->errors()->getMessages() as $attributeCode => $message) { $failedAttributes = $validator->failed(); $errorCode = array_key_first($failedAttributes[$attributeCode] ?? []); $this->skipRow($rowNumber, $errorCode, $attributeCode, current($message)); } } return ! $this->errorHelper->isRowInvalid($rowNumber); } /** * Start the import process. */ public function importBatch(ImportBatchContract $batch): bool { Event::dispatch('data_transfer.imports.batch.import.before', $batch); if ($batch->import->action == Import::ACTION_DELETE) { $this->deleteProducts($batch); } else { $this->saveProductsData($batch); } /** * Update import batch summary. */ $batch = $this->importBatchRepository->update([ 'state' => Import::STATE_PROCESSED, 'summary' => [ 'created' => $this->getCreatedItemsCount(), 'updated' => $this->getUpdatedItemsCount(), 'deleted' => $this->getDeletedItemsCount(), ], ], $batch->id); Event::dispatch('data_transfer.imports.batch.import.after', $batch); return true; } /** * Delete products from current batch. */ protected function deleteProducts(ImportBatchContract $batch): bool { /** * Load SKU storage with batch skus. */ $this->skuStorage->load(Arr::pluck($batch->data, 'sku')); $idsToDelete = []; foreach ($batch->data as $rowData) { if (! $this->isSKUExist($rowData['sku'])) { continue; } $product = $this->skuStorage->get($rowData['sku']); $idsToDelete[] = $product['id']; } $idsToDelete = array_unique($idsToDelete); $this->deletedItemsCount = count($idsToDelete); $this->productRepository->deleteWhere([['id', 'IN', $idsToDelete]]); return true; } /** * Save products from current batch. */ protected function saveProductsData(ImportBatchContract $batch): bool { /** * Load SKU storage with batch skus. */ $this->skuStorage->load(Arr::pluck($batch->data, 'sku')); $products = []; /** * Prepare products for import. */ foreach ($batch->data as $rowData) { $this->prepareProducts($rowData, $products); } $this->saveProducts($products); return true; } /** * Prepare products from current batch. */ public function prepareProducts(array $rowData, array &$products): void { if ($this->isSKUExist($rowData['sku'])) { $products['update'][$rowData['sku']] = $rowData; } else { $products['insert'][$rowData['sku']] = [ ...$rowData, 'created_at' => $rowData['created_at'] ?? now(), 'updated_at' => $rowData['updated_at'] ?? now(), ]; } } /** * Save products from current batch. */ public function saveProducts(array $products): void { if (! empty($products['update'])) { $this->updatedItemsCount += count($products['update']); $this->productRepository->upsert( $products['update'], $this->masterAttributeCode ); } if (! empty($products['insert'])) { $this->createdItemsCount += count($products['insert']); $this->productRepository->insert($products['insert']); } } /** * Save channels from current batch. */ public function saveChannels(array $channels): void { $productChannels = []; foreach ($channels as $sku => $channelIds) { $product = $this->skuStorage->get($sku); foreach (array_unique($channelIds) as $channelId) { $productChannels[] = [ 'product_id' => $product['id'], 'channel_id' => $channelId, ]; } } DB::table('product_channels')->upsert( $productChannels, [ 'product_id', 'channel_id', ], ); } /** * Save links. */ public function loadUnloadedSKUs(array $skus): void { $notLoadedSkus = []; foreach ($skus as $sku) { if ($this->skuStorage->has($sku)) { continue; } $notLoadedSkus[] = $sku; } /** * Load not loaded SKUs to the sku storage. */ if (! empty($notLoadedSkus)) { $this->skuStorage->load($notLoadedSkus); } } /** * Check if SKU exists. */ public function isSKUExist(string $sku): bool { return $this->skuStorage->has($sku); } /** * Prepare row data to save into the database. */ protected function prepareRowForDb(array $rowData): array { return parent::prepareRowForDb($rowData); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Importers/Persons/Storage.php
packages/Webkul/DataTransfer/src/Helpers/Importers/Persons/Storage.php
<?php namespace Webkul\DataTransfer\Helpers\Importers\Persons; use Webkul\Contact\Repositories\PersonRepository; class Storage { /** * Items contains email as key and product information as value. */ protected array $items = []; /** * Columns which will be selected from database. */ protected array $selectColumns = [ 'id', 'emails', ]; /** * Create a new helper instance. * * @return void */ public function __construct(protected PersonRepository $personRepository) {} /** * Initialize storage. */ public function init(): void { $this->items = []; $this->load(); } /** * Load the Emails. */ public function load(array $emails = []): void { if (empty($emails)) { $persons = $this->personRepository->all($this->selectColumns); } else { $persons = $this->personRepository->scopeQuery(function ($query) use ($emails) { return $query->where(function ($subQuery) use ($emails) { foreach ($emails as $email) { $subQuery->orWhereJsonContains('emails', ['value' => $email]); } }); })->all($this->selectColumns); } $persons->each(function ($person) { collect($person->emails) ->each(fn ($email) => $this->set($email['value'], $person->id)); }); } /** * Get email information. */ public function set(string $email, int $id): self { $this->items[$email] = $id; return $this; } /** * Check if email exists. */ public function has(string $email): bool { return isset($this->items[$email]); } /** * Get email information. */ public function get(string $email): ?int { if (! $this->has($email)) { return null; } return $this->items[$email]; } /** * Is storage is empty. */ public function isEmpty(): int { return empty($this->items); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Importers/Persons/Importer.php
packages/Webkul/DataTransfer/src/Helpers/Importers/Persons/Importer.php
<?php namespace Webkul\DataTransfer\Helpers\Importers\Persons; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Validator; use Webkul\Attribute\Repositories\AttributeRepository; use Webkul\Attribute\Repositories\AttributeValueRepository; use Webkul\Contact\Repositories\PersonRepository; use Webkul\DataTransfer\Contracts\ImportBatch as ImportBatchContract; use Webkul\DataTransfer\Helpers\Import; use Webkul\DataTransfer\Helpers\Importers\AbstractImporter; use Webkul\DataTransfer\Repositories\ImportBatchRepository; class Importer extends AbstractImporter { /** * Error code for non existing email. */ const ERROR_EMAIL_NOT_FOUND_FOR_DELETE = 'email_not_found_to_delete'; /** * Error code for duplicated email. */ const ERROR_DUPLICATE_EMAIL = 'duplicated_email'; /** * Error code for duplicated phone. */ const ERROR_DUPLICATE_PHONE = 'duplicated_phone'; /** * Permanent entity columns. */ protected array $validColumnNames = [ 'contact_numbers', 'emails', 'job_title', 'name', 'organization_id', 'user_id', ]; /** * Error message templates. */ protected array $messages = [ self::ERROR_EMAIL_NOT_FOUND_FOR_DELETE => 'data_transfer::app.importers.persons.validation.errors.email-not-found', self::ERROR_DUPLICATE_EMAIL => 'data_transfer::app.importers.persons.validation.errors.duplicate-email', self::ERROR_DUPLICATE_PHONE => 'data_transfer::app.importers.persons.validation.errors.duplicate-phone', ]; /** * Permanent entity columns. * * @var string[] */ protected $permanentAttributes = ['emails']; /** * Permanent entity column. */ protected string $masterAttributeCode = 'unique_id'; /** * Emails storage. */ protected array $emails = []; /** * Phones storage. */ protected array $phones = []; /** * Create a new helper instance. * * @return void */ public function __construct( protected ImportBatchRepository $importBatchRepository, protected PersonRepository $personRepository, protected AttributeRepository $attributeRepository, protected AttributeValueRepository $attributeValueRepository, protected Storage $personStorage, ) { parent::__construct( $importBatchRepository, $attributeRepository, $attributeValueRepository, ); } /** * Initialize Product error templates. */ protected function initErrorMessages(): void { foreach ($this->messages as $errorCode => $message) { $this->errorHelper->addErrorMessage($errorCode, trans($message)); } parent::initErrorMessages(); } /** * Validate data. */ public function validateData(): void { $this->personStorage->init(); parent::validateData(); } /** * Validates row. */ public function validateRow(array $rowData, int $rowNumber): bool { $rowData = $this->parsedRowData($rowData); /** * If row is already validated than no need for further validation. */ if (isset($this->validatedRows[$rowNumber])) { return ! $this->errorHelper->isRowInvalid($rowNumber); } $this->validatedRows[$rowNumber] = true; /** * If import action is delete than no need for further validation. */ if ($this->import->action == Import::ACTION_DELETE) { foreach ($rowData['emails'] as $email) { if (! $this->isEmailExist($email['value'])) { $this->skipRow($rowNumber, self::ERROR_EMAIL_NOT_FOUND_FOR_DELETE, 'email'); return false; } return true; } } /** * Validate row data. */ $validator = Validator::make($rowData, [ ...$this->getValidationRules('persons', $rowData), 'organization_id' => 'required|exists:organizations,id', 'user_id' => 'required|exists:users,id', 'contact_numbers' => 'required|array', 'contact_numbers.*.value' => 'required|numeric', 'contact_numbers.*.label' => 'required|in:home,work', 'emails' => 'required|array', 'emails.*.value' => 'required|email', 'emails.*.label' => 'required|in:home,work', ]); if ($validator->fails()) { $failedAttributes = $validator->failed(); foreach ($validator->errors()->getMessages() as $attributeCode => $message) { $errorCode = array_key_first($failedAttributes[$attributeCode] ?? []); $this->skipRow($rowNumber, $errorCode, $attributeCode, current($message)); } } /** * Check if email is unique. */ if (! empty($emails = $rowData['emails'])) { foreach ($emails as $email) { if (! in_array($email['value'], $this->emails)) { $this->emails[] = $email['value']; } else { $message = sprintf( trans($this->messages[self::ERROR_DUPLICATE_EMAIL]), $email['value'] ); $this->skipRow($rowNumber, self::ERROR_DUPLICATE_EMAIL, 'email', $message); } } } /** * Check if phone(s) are unique. */ if (! empty($rowData['contact_numbers'])) { foreach ($rowData['contact_numbers'] as $phone) { if (! in_array($phone['value'], $this->phones)) { if (! empty($phone['value'])) { $this->phones[] = $phone['value']; } } else { $message = sprintf( trans($this->messages[self::ERROR_DUPLICATE_PHONE]), $phone['value'] ); $this->skipRow($rowNumber, self::ERROR_DUPLICATE_PHONE, 'phone', $message); } } } return ! $this->errorHelper->isRowInvalid($rowNumber); } /** * Start the import process. */ public function importBatch(ImportBatchContract $batch): bool { Event::dispatch('data_transfer.imports.batch.import.before', $batch); if ($batch->import->action == Import::ACTION_DELETE) { $this->deletePersons($batch); } else { $this->savePersonData($batch); } /** * Update import batch summary. */ $batch = $this->importBatchRepository->update([ 'state' => Import::STATE_PROCESSED, 'summary' => [ 'created' => $this->getCreatedItemsCount(), 'updated' => $this->getUpdatedItemsCount(), 'deleted' => $this->getDeletedItemsCount(), ], ], $batch->id); Event::dispatch('data_transfer.imports.batch.import.after', $batch); return true; } /** * Delete persons from current batch. */ protected function deletePersons(ImportBatchContract $batch): bool { /** * Load person storage with batch emails. */ $emails = collect(Arr::pluck($batch->data, 'emails')) ->map(function ($emails) { $emails = json_decode($emails, true); foreach ($emails as $email) { return $email['value']; } }); $this->personStorage->load($emails->toArray()); $idsToDelete = []; foreach ($batch->data as $rowData) { $rowData = $this->parsedRowData($rowData); foreach ($rowData['emails'] as $email) { if (! $this->isEmailExist($email['value'])) { continue; } $idsToDelete[] = $this->personStorage->get($email['value']); } } $idsToDelete = array_unique($idsToDelete); $this->deletedItemsCount = count($idsToDelete); $this->personRepository->deleteWhere([['id', 'IN', $idsToDelete]]); return true; } /** * Save person from current batch. */ protected function savePersonData(ImportBatchContract $batch): bool { /** * Load person storage with batch email. */ $emails = collect(Arr::pluck($batch->data, 'emails')) ->map(function ($emails) { $emails = json_decode($emails, true); foreach ($emails as $email) { return $email['value']; } }); $this->personStorage->load($emails->toArray()); $persons = []; $attributeValues = []; /** * Prepare persons for import. */ foreach ($batch->data as $rowData) { $this->preparePersons($rowData, $persons); $this->prepareAttributeValues($rowData, $attributeValues); } $this->savePersons($persons); $this->saveAttributeValues($attributeValues); return true; } /** * Prepare persons from current batch. */ public function preparePersons(array $rowData, array &$persons): void { $emails = $this->prepareEmail($rowData['emails']); foreach ($emails as $email) { $contactNumber = json_decode($rowData['contact_numbers'], true); $rowData['unique_id'] = "{$rowData['user_id']}|{$rowData['organization_id']}|{$email}|{$contactNumber[0]['value']}"; if ($this->isEmailExist($email)) { $persons['update'][$email] = $rowData; } else { $persons['insert'][$email] = [ ...$rowData, 'created_at' => $rowData['created_at'] ?? now(), 'updated_at' => $rowData['updated_at'] ?? now(), ]; } } } /** * Save persons from current batch. */ public function savePersons(array $persons): void { if (! empty($persons['update'])) { $this->updatedItemsCount += count($persons['update']); $this->personRepository->upsert( $persons['update'], $this->masterAttributeCode, ); } if (! empty($persons['insert'])) { $this->createdItemsCount += count($persons['insert']); $this->personRepository->insert($persons['insert']); /** * Update the sku storage with newly created products */ $emails = array_keys($persons['insert']); $newPersons = $this->personRepository->where(function ($query) use ($emails) { foreach ($emails as $email) { $query->orWhereJsonContains('emails', [['value' => $email]]); } })->get(); foreach ($newPersons as $person) { $this->personStorage->set($person->emails[0]['value'], $person->id); } } } /** * Save attribute values for the person. */ public function saveAttributeValues(array $attributeValues): void { $personAttributeValues = []; foreach ($attributeValues as $email => $attributeValue) { foreach ($attributeValue as $attribute) { $attribute['entity_id'] = (int) $this->personStorage->get($email); $attribute['unique_id'] = implode('|', array_filter([ $attribute['entity_id'], $attribute['attribute_id'], ])); $attribute['entity_type'] = 'persons'; $personAttributeValues[$attribute['unique_id']] = $attribute; } } $this->attributeValueRepository->upsert($personAttributeValues, 'unique_id'); } /** * Check if email exists. */ public function isEmailExist(string $email): bool { return $this->personStorage->has($email); } /** * Prepare attribute values for the person. */ public function prepareAttributeValues(array $rowData, array &$attributeValues): void { foreach ($rowData as $code => $value) { if (is_null($value)) { continue; } $where = ['code' => $code]; if ($code === 'name') { $where['entity_type'] = 'persons'; } $attribute = $this->attributeRepository->findOneWhere($where); if (! $attribute) { continue; } $typeFields = $this->personRepository->getModel()::$attributeTypeFields; $attributeTypeValues = array_fill_keys(array_values($typeFields), null); $emails = $this->prepareEmail($rowData['emails']); foreach ($emails as $email) { $attributeValues[$email][] = array_merge($attributeTypeValues, [ 'attribute_id' => $attribute->id, $typeFields[$attribute->type] => $value, ]); } } } /** * Get parsed email and phone. */ private function parsedRowData(array $rowData): array { $rowData['emails'] = json_decode($rowData['emails'], true); $rowData['contact_numbers'] = json_decode($rowData['contact_numbers'], true); return $rowData; } /** * Prepare email from row data. */ private function prepareEmail(array|string $emails): Collection { static $cache = []; return collect($emails) ->map(function ($emailString) use (&$cache) { if (isset($cache[$emailString])) { return $cache[$emailString]; } $decoded = json_decode($emailString, true); $emailValue = is_array($decoded) && isset($decoded[0]['value']) ? $decoded[0]['value'] : null; return $cache[$emailString] = $emailValue; }); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Importers/Leads/Storage.php
packages/Webkul/DataTransfer/src/Helpers/Importers/Leads/Storage.php
<?php namespace Webkul\DataTransfer\Helpers\Importers\Leads; use Webkul\Lead\Repositories\LeadRepository; class Storage { /** * Items contains identifier as key and product information as value. */ protected array $items = []; /** * Columns which will be selected from database. */ protected array $selectColumns = ['id', 'title']; /** * Create a new helper instance. * * @return void */ public function __construct(protected LeadRepository $leadRepository) {} /** * Initialize storage. */ public function init(): void { $this->items = []; $this->load(); } /** * Load the leads. */ public function load(array $titles = []): void { if (empty($titles)) { $leads = $this->leadRepository->all($this->selectColumns); } else { $leads = $this->leadRepository->findWhereIn('title', $titles, $this->selectColumns); } foreach ($leads as $lead) { $this->set($lead->title, [ 'id' => $lead->id, 'title' => $lead->title, ]); } } /** * Get Ids and Unique Id. */ public function set(string $title, array $data): self { $this->items[$title] = $data; return $this; } /** * Check if unique id exists. */ public function has(string $title): bool { return isset($this->items[$title]); } /** * Get unique id information. */ public function get(string $title): ?array { if (! $this->has($title)) { return null; } return $this->items[$title]; } public function getItems(): array { return $this->items; } /** * Is storage is empty. */ public function isEmpty(): bool { return empty($this->items); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Helpers/Importers/Leads/Importer.php
packages/Webkul/DataTransfer/src/Helpers/Importers/Leads/Importer.php
<?php namespace Webkul\DataTransfer\Helpers\Importers\Leads; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Validator; use Webkul\Attribute\Repositories\AttributeRepository; use Webkul\Attribute\Repositories\AttributeValueRepository; use Webkul\Core\Contracts\Validations\Decimal; use Webkul\DataTransfer\Contracts\ImportBatch as ImportBatchContract; use Webkul\DataTransfer\Helpers\Import; use Webkul\DataTransfer\Helpers\Importers\AbstractImporter; use Webkul\DataTransfer\Repositories\ImportBatchRepository; use Webkul\Lead\Repositories\LeadRepository; use Webkul\Lead\Repositories\ProductRepository as LeadProductRepository; class Importer extends AbstractImporter { /** * Error code for non existing id. */ const ERROR_ID_NOT_FOUND_FOR_DELETE = 'id_not_found_to_delete'; /** * Permanent entity columns. */ protected array $validColumnNames = [ 'id', 'title', 'description', 'lead_value', 'status', 'lost_reason', 'closed_at', 'user_id', 'person_id', 'lead_source_id', 'lead_type_id', 'lead_pipeline_id', 'lead_pipeline_stage_id', 'expected_close_date', 'product', ]; /** * Error message templates. */ protected array $messages = [ self::ERROR_ID_NOT_FOUND_FOR_DELETE => 'data_transfer::app.importers.leads.validation.errors.id-not-found', ]; /** * Permanent entity columns. * * @var string[] */ protected $permanentAttributes = ['title']; /** * Permanent entity column. */ protected string $masterAttributeCode = 'id'; /** * Is linking required */ protected bool $linkingRequired = true; /** * Create a new helper instance. * * @return void */ public function __construct( protected ImportBatchRepository $importBatchRepository, protected LeadRepository $leadRepository, protected LeadProductRepository $leadProductRepository, protected AttributeRepository $attributeRepository, protected AttributeValueRepository $attributeValueRepository, protected Storage $leadsStorage, ) { parent::__construct( $importBatchRepository, $attributeRepository, $attributeValueRepository, ); } /** * Initialize leads error templates. */ protected function initErrorMessages(): void { foreach ($this->messages as $errorCode => $message) { $this->errorHelper->addErrorMessage($errorCode, trans($message)); } parent::initErrorMessages(); } /** * Validate data. */ public function validateData(): void { $this->leadsStorage->init(); parent::validateData(); } /** * Validates row. */ public function validateRow(array $rowData, int $rowNumber): bool { /** * If row is already validated than no need for further validation. */ if (isset($this->validatedRows[$rowNumber])) { return ! $this->errorHelper->isRowInvalid($rowNumber); } $this->validatedRows[$rowNumber] = true; /** * If import action is delete than no need for further validation. */ if ($this->import->action == Import::ACTION_DELETE) { if (! $this->isTitleExist($rowData['title'])) { $this->skipRow($rowNumber, self::ERROR_ID_NOT_FOUND_FOR_DELETE, 'id'); return false; } return true; } if (! empty($rowData['product'])) { $product = $this->parseProducts($rowData['product']); $validator = Validator::make($product, [ 'id' => 'required|exists:products,id', 'price' => 'required', 'quantity' => 'required', ]); if ($validator->fails()) { $failedAttributes = $validator->failed(); foreach ($validator->errors()->getMessages() as $attributeCode => $message) { $errorCode = array_key_first($failedAttributes[$attributeCode] ?? []); $this->skipRow($rowNumber, $errorCode, $attributeCode, current($message)); } } } /** * Validate leads attributes. */ $validator = Validator::make($rowData, [ ...$this->getValidationRules('leads|persons', $rowData), 'id' => 'numeric', 'status' => 'sometimes|required|in:0,1', 'user_id' => 'required|exists:users,id', 'person_id' => 'required|exists:persons,id', 'lead_source_id' => 'required|exists:lead_sources,id', 'lead_type_id' => 'required|exists:lead_types,id', 'lead_pipeline_id' => 'required|exists:lead_pipelines,id', 'lead_pipeline_stage_id' => 'required|exists:lead_pipeline_stages,id', ]); if ($validator->fails()) { $failedAttributes = $validator->failed(); foreach ($validator->errors()->getMessages() as $attributeCode => $message) { $errorCode = array_key_first($failedAttributes[$attributeCode] ?? []); $this->skipRow($rowNumber, $errorCode, $attributeCode, current($message)); } } return ! $this->errorHelper->isRowInvalid($rowNumber); } /** * Prepare row data for lead product. */ protected function parseProducts(?string $products): array { $productData = []; $productArray = explode(',', $products); foreach ($productArray as $product) { if (empty($product)) { continue; } [$key, $value] = explode('=', $product); $productData[$key] = $value; } if ( isset($productData['price']) && isset($productData['quantity']) ) { $productData['amount'] = $productData['price'] * $productData['quantity']; } return $productData; } /** * Get validation rules. */ public function getValidationRules(string $entityTypes, array $rowData): array { $rules = []; foreach (explode('|', $entityTypes) as $entityType) { $attributes = $this->attributeRepository->scopeQuery(fn ($query) => $query->whereIn('code', array_keys($rowData))->where('entity_type', $entityType))->get(); foreach ($attributes as $attribute) { if ($entityType == 'persons') { $attribute->code = 'person.'.$attribute->code; } $validations = []; if ($attribute->type == 'boolean') { continue; } elseif ($attribute->type == 'address') { if (! $attribute->is_required) { continue; } $validations = [ $attribute->code.'.address' => 'required', $attribute->code.'.country' => 'required', $attribute->code.'.state' => 'required', $attribute->code.'.city' => 'required', $attribute->code.'.postcode' => 'required', ]; } elseif ($attribute->type == 'email') { $validations = [ $attribute->code => [$attribute->is_required ? 'required' : 'nullable'], $attribute->code.'.*.value' => [$attribute->is_required ? 'required' : 'nullable', 'email'], $attribute->code.'.*.label' => $attribute->is_required ? 'required' : 'nullable', ]; } elseif ($attribute->type == 'phone') { $validations = [ $attribute->code => [$attribute->is_required ? 'required' : 'nullable'], $attribute->code.'.*.value' => [$attribute->is_required ? 'required' : 'nullable'], $attribute->code.'.*.label' => $attribute->is_required ? 'required' : 'nullable', ]; } else { $validations[$attribute->code] = [$attribute->is_required ? 'required' : 'nullable']; if ($attribute->type == 'text' && $attribute->validation) { array_push($validations[$attribute->code], $attribute->validation == 'decimal' ? new Decimal : $attribute->validation ); } if ($attribute->type == 'price') { array_push($validations[$attribute->code], new Decimal); } } if ($attribute->is_unique) { array_push($validations[in_array($attribute->type, ['email', 'phone']) ? $attribute->code.'.*.value' : $attribute->code ], function ($field, $value, $fail) use ($attribute) { if (! $this->attributeValueRepository->isValueUnique( null, $attribute->entity_type, $attribute, request($field) ) ) { $fail(trans('data_transfer::app.validation.errors.already-exists', ['attribute' => $attribute->name])); } }); } $rules = [ ...$rules, ...$validations, ]; } } return $rules; } /** * Start the import process. */ public function importBatch(ImportBatchContract $batch): bool { Event::dispatch('data_transfer.imports.batch.import.before', $batch); if ($batch->import->action == Import::ACTION_DELETE) { $this->deleteLeads($batch); } else { $this->saveLeads($batch); } /** * Update import batch summary. */ $batch = $this->importBatchRepository->update([ 'state' => Import::STATE_PROCESSED, 'summary' => [ 'created' => $this->getCreatedItemsCount(), 'updated' => $this->getUpdatedItemsCount(), 'deleted' => $this->getDeletedItemsCount(), ], ], $batch->id); Event::dispatch('data_transfer.imports.batch.import.after', $batch); return true; } /** * Start the products linking process */ public function linkBatch(ImportBatchContract $batch): bool { Event::dispatch('data_transfer.imports.batch.linking.before', $batch); /** * Load leads storage with batch ids. */ $this->leadsStorage->load(Arr::pluck($batch->data, 'title')); $products = []; foreach ($batch->data as $rowData) { /** * Prepare products. */ $this->prepareProducts($rowData, $products); } $this->saveProducts($products); /** * Update import batch summary */ $this->importBatchRepository->update([ 'state' => Import::STATE_LINKED, ], $batch->id); Event::dispatch('data_transfer.imports.batch.linking.after', $batch); return true; } /** * Prepare products. */ public function prepareProducts($rowData, &$product): void { if (! empty($rowData['product'])) { $product[$rowData['title']] = $this->parseProducts($rowData['product']); } } /** * Save products. */ public function saveProducts(array $products): void { $leadProducts = []; foreach ($products as $title => $product) { $lead = $this->leadsStorage->get($title); $leadProducts['insert'][] = [ 'lead_id' => $lead['id'], 'product_id' => $product['id'], 'price' => $product['price'], 'quantity' => $product['quantity'], 'amount' => $product['amount'], ]; } foreach ($leadProducts['insert'] as $key => $leadProduct) { $this->leadProductRepository->deleteWhere([ 'lead_id' => $leadProduct['lead_id'], 'product_id' => $leadProduct['product_id'], ]); } $this->leadProductRepository->upsert($leadProducts['insert'], ['lead_id', 'product_id']); } /** * Delete leads from current batch. */ protected function deleteLeads(ImportBatchContract $batch): bool { /** * Load leads storage with batch ids. */ $this->leadsStorage->load(Arr::pluck($batch->data, 'title')); $idsToDelete = []; foreach ($batch->data as $rowData) { if (! $this->isTitleExist($rowData['title'])) { continue; } $idsToDelete[] = $this->leadsStorage->get($rowData['title']); } $idsToDelete = array_unique($idsToDelete); $this->deletedItemsCount = count($idsToDelete); $this->leadRepository->deleteWhere([['id', 'IN', $idsToDelete]]); return true; } /** * Save leads from current batch. */ protected function saveLeads(ImportBatchContract $batch): bool { /** * Load lead storage with batch unique title. */ $this->leadsStorage->load(Arr::pluck($batch->data, 'title')); $leads = []; /** * Prepare leads for import. */ foreach ($batch->data as $rowData) { if (isset($rowData['id'])) { $leads['update'][$rowData['id']] = Arr::except($rowData, ['product']); } else { $leads['insert'][$rowData['title']] = [ ...Arr::except($rowData, ['id', 'product']), 'created_at' => $rowData['created_at'] ?? now(), 'updated_at' => $rowData['updated_at'] ?? now(), ]; } } if (! empty($leads['update'])) { $this->updatedItemsCount += count($leads['update']); $this->leadRepository->upsert( $leads['update'], $this->masterAttributeCode ); } if (! empty($leads['insert'])) { $this->createdItemsCount += count($leads['insert']); $this->leadRepository->insert($leads['insert']); /** * Update the sku storage with newly created products */ $newLeads = $this->leadRepository->findWhereIn( 'title', array_keys($leads['insert']), [ 'id', 'title', ] ); foreach ($newLeads as $lead) { $this->leadsStorage->set($lead->title, [ 'id' => $lead->id, 'title' => $lead->title, ]); } } return true; } /** * Check if title exists. */ public function isTitleExist(string $title): bool { return $this->leadsStorage->has($title); } /** * Prepare row data to save into the database. */ protected function prepareRowForDb(array $rowData): array { return parent::prepareRowForDb($rowData); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Contracts/ImportBatch.php
packages/Webkul/DataTransfer/src/Contracts/ImportBatch.php
<?php namespace Webkul\DataTransfer\Contracts; interface ImportBatch {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Contracts/Import.php
packages/Webkul/DataTransfer/src/Contracts/Import.php
<?php namespace Webkul\DataTransfer\Contracts; interface Import {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Database/Migrations/2024_01_11_154741_create_import_batches_table.php
packages/Webkul/DataTransfer/src/Database/Migrations/2024_01_11_154741_create_import_batches_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('import_batches', function (Blueprint $table) { $table->increments('id'); $table->string('state')->default('pending'); $table->json('data'); $table->json('summary')->nullable(); $table->integer('import_id')->unsigned(); $table->foreign('import_id')->references('id')->on('imports')->onDelete('cascade'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('import_batches'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Database/Migrations/2024_01_11_154640_create_imports_table.php
packages/Webkul/DataTransfer/src/Database/Migrations/2024_01_11_154640_create_imports_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('imports', function (Blueprint $table) { $table->increments('id'); $table->string('state')->default('pending'); $table->boolean('process_in_queue')->default(1); $table->string('type'); $table->string('action'); $table->string('validation_strategy'); $table->integer('allowed_errors')->default(0); $table->integer('processed_rows_count')->default(0); $table->integer('invalid_rows_count')->default(0); $table->integer('errors_count')->default(0); $table->json('errors')->nullable(); $table->string('field_separator'); $table->string('file_path'); $table->string('error_file_path')->nullable(); $table->json('summary')->nullable(); $table->datetime('started_at')->nullable(); $table->datetime('completed_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('imports'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Config/importers.php
packages/Webkul/DataTransfer/src/Config/importers.php
<?php return [ 'persons' => [ 'title' => 'data_transfer::app.importers.persons.title', 'importer' => 'Webkul\DataTransfer\Helpers\Importers\Persons\Importer', 'sample_path' => 'data-transfer/samples/persons.csv', ], 'products' => [ 'title' => 'data_transfer::app.importers.products.title', 'importer' => 'Webkul\DataTransfer\Helpers\Importers\Products\Importer', 'sample_path' => 'data-transfer/samples/products.csv', ], 'leads' => [ 'title' => 'data_transfer::app.importers.leads.title', 'importer' => 'Webkul\DataTransfer\Helpers\Importers\Leads\Importer', 'sample_path' => 'data-transfer/samples/leads.csv', ], ];
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Resources/lang/pt_BR/app.php
packages/Webkul/DataTransfer/src/Resources/lang/pt_BR/app.php
<?php return [ 'importers' => [ 'persons' => [ 'title' => 'Pessoas', 'validation' => [ 'errors' => [ 'duplicate-email' => 'E-mail : \'%s\' é encontrado mais de uma vez no arquivo de importação.', 'duplicate-phone' => 'Telefone : \'%s\' é encontrado mais de uma vez no arquivo de importação.', 'email-not-found' => 'E-mail : \'%s\' não foi encontrado no sistema.', ], ], ], 'products' => [ 'title' => 'Produtos', 'validation' => [ 'errors' => [ 'sku-not-found' => 'Produto com este código não foi encontrado', ], ], ], 'leads' => [ 'title' => 'Oportunidades', 'validation' => [ 'errors' => [ 'id-not-found' => 'ID : \'%s\' não foi encontrado no sistema.', ], ], ], ], 'validation' => [ 'errors' => [ 'column-empty-headers' => 'As colunas de número "%s" têm cabeçalhos vazios.', 'column-name-invalid' => 'Nomes de colunas inválidos: "%s".', 'column-not-found' => 'Colunas obrigatórias não encontradas: %s.', 'column-numbers' => 'O número de colunas não corresponde ao número de linhas no cabeçalho.', 'invalid-attribute' => 'O cabeçalho contém atributo(s) inválido(s): "%s".', 'system' => 'Ocorreu um erro inesperado no sistema.', 'wrong-quotes' => 'Aspas curvas usadas em vez de aspas retas.', 'already-exists' => 'O :attribute já existe.', ], ], ];
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Resources/lang/tr/app.php
packages/Webkul/DataTransfer/src/Resources/lang/tr/app.php
<?php return [ 'importers' => [ 'persons' => [ 'title' => 'Kişiler', 'validation' => [ 'errors' => [ 'duplicate-email' => 'E-posta: \'%s\' içe aktarma dosyasında birden fazla kez bulundu.', 'duplicate-phone' => 'Telefon: \'%s\' içe aktarma dosyasında birden fazla kez bulundu.', 'email-not-found' => 'E-posta: \'%s\' sistemde bulunamadı.', ], ], ], 'products' => [ 'title' => 'Ürünler', 'validation' => [ 'errors' => [ 'sku-not-found' => 'Belirtilen SKU\'ya sahip ürün bulunamadı.', ], ], ], 'leads' => [ 'title' => 'Müşteri Adayları', 'validation' => [ 'errors' => [ 'id-not-found' => 'ID: \'%s\' sistemde bulunamadı.', ], ], ], ], 'validation' => [ 'errors' => [ 'column-empty-headers' => '"%s" numaralı sütunların başlıkları boş.', 'column-name-invalid' => 'Geçersiz sütun adları: "%s".', 'column-not-found' => 'Gerekli sütunlar bulunamadı: %s.', 'column-numbers' => 'Sütun sayısı başlıktaki satır sayısına karşılık gelmiyor.', 'invalid-attribute' => 'Başlık geçersiz öznitelikler içeriyor: "%s".', 'system' => 'Beklenmeyen bir sistem hatası oluştu.', 'wrong-quotes' => 'Doğru olmayan tırnak işaretleri kullanıldı.', ], ], ];
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/DataTransfer/src/Resources/lang/en/app.php
packages/Webkul/DataTransfer/src/Resources/lang/en/app.php
<?php return [ 'importers' => [ 'persons' => [ 'title' => 'Persons', 'validation' => [ 'errors' => [ 'duplicate-email' => 'Email : \'%s\' is found more than once in the import file.', 'duplicate-phone' => 'Phone : \'%s\' is found more than once in the import file.', 'email-not-found' => 'Email : \'%s\' not found in the system.', ], ], ], 'products' => [ 'title' => 'Products', 'validation' => [ 'errors' => [ 'sku-not-found' => 'Product with specified SKU not found', ], ], ], 'leads' => [ 'title' => 'Leads', 'validation' => [ 'errors' => [ 'id-not-found' => 'ID : \'%s\' not found in the system.', ], ], ], ], 'validation' => [ 'errors' => [ 'column-empty-headers' => 'Columns number "%s" have empty headers.', 'column-name-invalid' => 'Invalid column names: "%s".', 'column-not-found' => 'Required columns not found: %s.', 'column-numbers' => 'Number of columns does not correspond to the number of rows in the header.', 'invalid-attribute' => 'Header contains invalid attribute(s): "%s".', 'system' => 'An unexpected system error occurred.', 'wrong-quotes' => 'Curly quotes used instead of straight quotes.', 'already-exists' => 'The :attribute already exists.', ], ], ];
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false