]> _ Git - psq.git/commitdiff
attachemnt pdf on 2nd email, eneryone in subscriber list gets email
authorLouis Jeckel <louis.jeckel@outlook.com>
Wed, 13 Jan 2021 12:30:53 +0000 (13:30 +0100)
committerLouis Jeckel <louis.jeckel@outlook.com>
Wed, 13 Jan 2021 12:30:53 +0000 (13:30 +0100)
12 files changed:
app/EmailBatch.php
app/FileCollection.php
app/Http/Controllers/Admin/PublishController.php
app/Jobs/ProcessEmailBatch.php
app/Mail/BatchMail.php
app/Nova/Metrics/RegistrationCompletePartition.php
app/Nova/Metrics/TotalUsers.php
app/Nova/Metrics/UsersPartition.php
app/PdfFile.php
app/User.php
database/migrations/2021_01_13_000535_add_sends_pdf_to_collection.php [new file with mode: 0644]
resources/views/emails/batch-pdf.blade.php

index b999e1fb20c02d86b4929d8056e4080feaed2834..551b5f37a8dd5149bbb266602f2295162a5d52ee 100644 (file)
@@ -3,6 +3,7 @@
 namespace App;
 
 use App\Mail\BatchMail;
+use Arr;
 use Carbon\Carbon;
 use Illuminate\Database\Eloquent\Model;
 use \Illuminate\Database\Eloquent\Relations;
@@ -22,6 +23,8 @@ class EmailBatch extends TwillModel
 {
     protected $guarded = [];
     protected $softDeletes = false;
+
+
     use BelongsToPdfFile;
 
 
@@ -34,6 +37,78 @@ class EmailBatch extends TwillModel
         'sent_to'
     ];
 
+    /**
+     * @param $data
+     * @return EmailBatch
+     */
+    public static function createFromRequest($data): EmailBatch
+    {
+        $batch = new self;
+
+        $recipientSlug  = Arr::get($data, 'recipient_group.slug');
+        $prefix = $recipientSlug === 'admin' ?
+            '** TEST ** ' :
+            '';
+
+        $batch->subject = $prefix . Arr::get($data, 'email.subject', '');
+        $batch->content = [
+            'body' => Arr::get($data, 'email.content'),
+            'link' => Arr::get($data, 'email.link'),
+            'html' => Arr::get($data, 'email.html'),
+            'type' => Arr::get($data, 'email.type', 0) //0: newsletter, 1: PDF
+
+        ];
+        $batch->file_id = Arr::get($data, 'file.id');
+        $batch->sent_to = [];
+
+        $batch->save();
+
+
+        return $batch;
+
+    }
+
+    /**
+     * @param $data
+     * @return EmailBatch|null
+     */
+    public static function createAttachmentMailFromRequest($data): ?EmailBatch
+    {
+        $fileId = Arr::get($data, 'file.id');
+        /** @var PdfFile $file */
+
+        if($fileId === null) {
+            return null;
+        }
+
+        $file = PdfFile::find($fileId);
+
+        if(!$file || ! $file->collection->sends_pdf) {
+            return null;
+        }
+
+        $batch = new self;
+        $recipientSlug  = Arr::get($data, 'recipient_group.slug');
+        $prefix = $recipientSlug === 'admin' ?
+            '** TEST ** [Version PDF]' :
+            '[Version PDF] ';
+
+        $batch->subject = $prefix . Arr::get($data, 'email.subject', '');
+        $batch->file_id = $fileId;
+
+        $batch->content = [
+            'body' => "Bonjour, ci-joint la version PDF de {$file->title}",
+            'type' => 0
+
+        ];
+        $batch->sent_to = [];
+
+        $batch->save();
+
+        return $batch;
+
+    }
+
     /**
      * @return Relations\HasMany
      */
@@ -82,10 +157,21 @@ class EmailBatch extends TwillModel
                 $this->content['body'],
                 $this->subject,
                 $this->content['link'] ?? null,
-                optional($this->file)->coverUrl
+                optional($this->file)->coverUrl,
+                $this->getView()
             ))->render();
     }
 
+    /**
+     * @return int
+     */
+    public function getView()
+    {
+        if($this->content['type'] == 1) {
+            return BatchMail::MAIL_TYPE_PDF_FILE;
+        }
+        return BatchMail::MAIL_TYPE_NEWSLETTER;
+    }
     /**
      * @return string
      */
index 26334f493c10a89b56ddab56afb0b99b1add6476..06a59e385b1c3d0b6f9f1c6b876066b4ac9edc99 100644 (file)
@@ -11,6 +11,7 @@ use Illuminate\Database\Eloquent\Model;
  * @property string $slug
  * @property string $name
  * @property string $short_name
+ * @property bool $sends_pdf
  * @method static FileCollection findOrFail($id) FileCollection
  */
 class FileCollection extends Model
@@ -19,6 +20,8 @@ class FileCollection extends Model
 
     public $timestamps = false;
 
+    protected $guarded = [];
+
     public function files()
     {
         return $this->hasMany(PdfFile::class, 'collection_id');
index ec0f4dd39a61257dcb7df5b772aa35cd44e33252..9973344793c5773362e204d67dc99acd201f911d 100644 (file)
@@ -14,6 +14,7 @@ use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Http\Request;
 use Illuminate\Http\Resources\Json\ResourceCollection;
 use Illuminate\Support\Arr;
+use PharIo\Manifest\Email;
 
 
 class PublishController extends Controller
@@ -40,34 +41,28 @@ class PublishController extends Controller
      */
     public function publish(Request $request)
     {
-        $batch = new EmailBatch();
         $data = $request->input('data');
 
-        //0: newsletter, 1: PDF
-        $type = Arr::get($data, 'email.type', 0);
-        $recipientGroup = Arr::get($data, 'recipient_group');
-        $recipientSlug  = Arr::get($data, 'recipient_group.slug');
-        $prefix = $recipientSlug === 'admin' ?
-            '** TEST ** ' :
-            '';
-
-        $batch->subject = $prefix . Arr::get($data, 'email.subject', '');
-        $batch->content = [
-            'body' => Arr::get($data, 'email.content'),
-            'link' => Arr::get($data, 'email.link'),
-            'html' => Arr::get($data, 'email.html')
-        ];
-        $batch->file_id = Arr::get($data, 'file.id');
-        $batch->sent_to = [];
 
-        $batch->save();
+        $recipientGroup = Arr::get($data, 'recipient_group');
 
-        $builder = $recipientGroup === null ?
+        /** @var Builder $usersBuilder */
+        $usersBuilder = $recipientGroup === null ?
             User::receivesEmails() :
             PublishController::sendGroups()[$recipientGroup['slug']]['builder'];
-        $processEmailBatch = new ProcessEmailBatch($batch, $builder);
 
-        dispatch($processEmailBatch->withFile());
+        $userReceivesPdfBuilder = clone $usersBuilder;
+
+        $batch = EmailBatch::createFromRequest($data);
+        $processEmailBatch = new ProcessEmailBatch($batch, $usersBuilder);
+        dispatch($processEmailBatch);
+
+        if($pdfBatch = EmailBatch::createAttachmentMailFromRequest($data)) {
+            $userReceivesPdfBuilder->receivesPdf();
+            $pdfProcessEmailBatch = new ProcessEmailBatch($pdfBatch, $userReceivesPdfBuilder);
+            dispatch($pdfProcessEmailBatch->withFile());
+
+        }
 
         return ['data' => $batch->id];
     }
@@ -160,6 +155,7 @@ class PublishController extends Controller
             $request->input('subject'),
             $request->input('link'),
             $request->input('image'),
+            BatchMail::MAIL_TYPE_PDF_FILE
         ))->render();
     }
 
index 4deefd0cd0a5b7b27bde9c8232ecdf461ef2f174..f5ed9c8bce6c79d785b2d42617b387d4470c0c0e 100644 (file)
@@ -80,7 +80,6 @@ class ProcessEmailBatch implements ShouldQueue
 
         $this->users = $usersBuilder->get();
 
-        $this->html = $this->batch->content['html'];
         $this->replaceVariables();
     }
 
@@ -187,8 +186,7 @@ class ProcessEmailBatch implements ShouldQueue
 
 
 
-            $view = $this->html ?? $this->batch->renderFromContent();
-
+            $view = $this->batch->render();
 
 
             $params = [
index 177be53678f162d917cf0922135b1b0ba73649cd..bc6a37cd02d13bbe3c43610e6d0f32e1278f3262 100644 (file)
@@ -44,8 +44,9 @@ class BatchMail extends Mailable
      * @param string $subject
      * @param string|null $link
      * @param null $image
+     * @param int $type
      */
-    public function __construct($content, $subject, $link = null, $image = null)
+    public function __construct($content, $subject, $link = null, $image = null, $type = self::MAIL_TYPE_NEWSLETTER)
     {
         //
         $this->subject = $subject;
@@ -53,7 +54,7 @@ class BatchMail extends Mailable
         $this->image = $image;
 
 
-        $this->emailView = self::getView(self::MAIL_TYPE_PDF_FILE);
+        $this->emailView = self::getView($type);
 
         $this->content = $this->emailView === 'batch-pdf' ?
             (Html2Markdown::convert($content)) :
@@ -64,6 +65,8 @@ class BatchMail extends Mailable
         }
     }
 
+
+
     /**
      * @param $id
      * @return string
index a2337db389a33625aa5f3ddaef48920839ea8147..8c2dbb009bd6a17004b096f43b785fee8d6bdac0 100644 (file)
@@ -20,8 +20,8 @@ class RegistrationCompletePartition extends Partition
     public function calculate(NovaRequest $request)
     {
         return $this->result([
-            'Compte activé' => User::registeredUser()->registrationComplete()->count(),
-            'Compte non activé' => User::registeredUser()->registrationIncomplete()->count(),
+            'Compte activé' => User::subscriber()->registrationComplete()->count(),
+            'Compte non activé' => User::subscriber()->registrationIncomplete()->count(),
         ]);
     }
 
index 6a70a8419a1b158c0efe2ec85f986513a6799a46..389f96e6db10ffc406bd630d6aebc7e8cc6ffa21 100644 (file)
@@ -18,7 +18,7 @@ class TotalUsers extends Value
      */
     public function calculate(NovaRequest $request)
     {
-        return $this->result(User::registeredUser()->count());
+        return $this->result(User::subscriber()->count());
     }
 
 
index 0e271ef444e142f0753e8f2a961b7f94a9fba363..59dc4b50992fd111c49eec96844407117b53d88b 100644 (file)
@@ -20,11 +20,10 @@ class UsersPartition extends Partition
     public function calculate(NovaRequest $request)
     {
         return $this->result([
-            'Abonnés (groupe)' => $g = User::hasOrgSubscription()->count(),
-            'Abonnés (indiv)' => $i = User::hasIndSubscription()->count(),
+            'Abonnés' => $g = User::subscriber()->count(),
             "Période d'essai" => $t = User::isOnTrial()->count(),
             "Découverte" => $d = User::isOnDiscovery()->count(),
-            "Reste" => User::count() - $i - $g - $t -$d
+            "Reste" => User::count() - $g - $t -$d
         ]);
     }
 
index df1f31d71fb8c721b44b40fa041533d302887723..b323d8fd22cef53cd6c8191b5b3613055b2532f6 100644 (file)
@@ -104,13 +104,15 @@ class PdfFile extends TwillModel implements Sortable
 
 
         /** @var PdfFile $pdfFile */
-        $pdfFile = self::create([
-            'ref' => $ref,
-            'collection_id' => $collection_id,
+        $pdfFile = self::query()->updateOrCreate([
             'slug' => Str::slug("{$collection->slug}_{$ref}"),
+            'published' => 0,
+            'collection_id' => $collection_id,
+        ],
+        [
+            'ref' => $ref,
             'title' => "{$collection->short_name} - $ref",
             'headlines' => $headlines,
-            'published' => 0,
         ]);
 
 
@@ -429,9 +431,9 @@ class PdfFile extends TwillModel implements Sortable
      */
     public function getMailableUrl(User $user): string
     {
-        if($user->receives_pdf) {
-            return $this->getDownloadUrl();
-        }
+//        if($user->receives_pdf) {
+//            return $this->getDownloadUrl();
+//        }
         return ($user->type === User::TYPE_DISCOVER && !$user->reg_complete) ?
             $this->getSignedUrl($user) :
             $this->getUrlWithToken($user);
@@ -669,6 +671,8 @@ class PdfFile extends TwillModel implements Sortable
         $builder->where('is_free', true);
     }
 
+
+
     /**
      * @return string
      */
index 90cb6f44070752a0acc335925e572fc9628951fc..4634fba2616e999ddf3fd35077c71a92cb375f22 100644 (file)
@@ -138,6 +138,10 @@ class User extends Authenticatable implements MustVerifyEmail, SendsEmails
             'badge' => 'success',
             'label' => 'Abonnement actif (indep)'
         ],
+        'subscribed' => [
+            'badge' => 'success',
+            'label' => 'Abonnement actif'
+        ],
         'trial' => [
             'badge' => 'info',
             'label' => "Période d'essai"
@@ -318,7 +322,7 @@ class User extends Authenticatable implements MustVerifyEmail, SendsEmails
      */
     public function hasValidSubscription(): bool
     {
-        return $this->orgIsSubscribed() || $this->subscribed();
+        return $this->type === self::TYPE_SUBSCRIBER;
     }
 
     /**
@@ -431,10 +435,11 @@ class User extends Authenticatable implements MustVerifyEmail, SendsEmails
 
     /**
      * @param Builder $builder
+     * @deprecated
      */
     public function scopeHasActiveSubscription(Builder $builder): void
     {
-        $builder->hasOrgSubscription()->orWhere->hasIndSubscription();
+        $builder->subscriber();
     }
 
     /**
@@ -473,7 +478,7 @@ class User extends Authenticatable implements MustVerifyEmail, SendsEmails
     /**
      * @param Builder $builder
      */
-    public function scopeRegisteredUser(Builder $builder): void
+    public function scopeSubscriber(Builder $builder): void
     {
         $builder->where('type', self::TYPE_SUBSCRIBER);
     }
@@ -523,6 +528,14 @@ class User extends Authenticatable implements MustVerifyEmail, SendsEmails
 
     }
 
+    /**
+     * @param Builder $builder
+     */
+    public function scopeReceivesPdf(Builder $builder): void
+    {
+        $builder->where('receives_pdf', 1);
+    }
+
 
 
 
@@ -562,15 +575,7 @@ class User extends Authenticatable implements MustVerifyEmail, SendsEmails
 
         switch($this->type) {
             case self::TYPE_SUBSCRIBER:
-                if($this->orgIsSubscribed) {
-                    $id = 'org_subscribed';
-                }
-                if($this->subscribed()) {
-                    $id = 'ind_subscribed';
-                }
-                if($this->onTrial()) {
-                    $id = 'trial';
-                }
+                $id = 'subscribed';
                 break;
 
             case self::TYPE_PROSPECT:
diff --git a/database/migrations/2021_01_13_000535_add_sends_pdf_to_collection.php b/database/migrations/2021_01_13_000535_add_sends_pdf_to_collection.php
new file mode 100644 (file)
index 0000000..51e3d51
--- /dev/null
@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class AddSendsPdfToCollection extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('collections', function (Blueprint $table) {
+            $table->boolean('sends_pdf')->default(0);
+        });
+        \App\FileCollection::query()->first()->update(['sends_pdf' => true]);
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('collections', function (Blueprint $table) {
+            $table->boolean('sends_pdf')->default(0);
+        });
+    }
+}
index c6099d410d62976ba8c9bb0941b6b85514684f70..c75360c20bee78a9326dab5d5af4321e91f8826a 100644 (file)
@@ -12,6 +12,7 @@
         </td>
     </tr>
 </table>
+<br>
 
 {!! $content !!}