Move wall messages to social posts

pull/4161/head
Angel Fernando Quiroz Campos 3 years ago
parent d1f8ed028c
commit f038a2b4d7
  1. 19
      public/main/inc/ajax/social.ajax.php
  2. 31
      public/main/inc/lib/message.lib.php
  3. 33
      src/CoreBundle/Entity/Message.php
  4. 315
      src/CoreBundle/Entity/SocialPost.php
  5. 35
      src/CoreBundle/Entity/SocialPostFeedback.php
  6. 97
      src/CoreBundle/Entity/User.php
  7. 6
      src/CoreBundle/Framework/Container.php
  8. 87
      src/CoreBundle/Migrations/Schema/V200/Version20200821224242.php
  9. 39
      src/CoreBundle/Repository/SocialPostRepository.php
  10. 52
      tests/CoreBundle/Repository/MessageRepositoryTest.php
  11. 75
      tests/CoreBundle/Repository/SocialPostRepositoryTest.php

@ -1,8 +1,8 @@
<?php <?php
/* For licensing terms, see /license.txt */ /* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Entity\Message; use Chamilo\CoreBundle\Entity\SocialPost;
use Chamilo\CoreBundle\Entity\MessageFeedback; use Chamilo\CoreBundle\Entity\SocialPostFeedback;
use Chamilo\CoreBundle\Framework\Container; use Chamilo\CoreBundle\Framework\Container;
use ChamiloSession as Session; use ChamiloSession as Session;
@ -225,10 +225,9 @@ switch ($action) {
} }
$em = Database::getManager(); $em = Database::getManager();
$messageRepo = $em->getRepository(Message::class); $messageRepo = $em->getRepository(SocialPost::class);
$messageLikesRepo = $em->getRepository(MessageFeedback::class); $messageLikesRepo = $em->getRepository(SocialPostFeedback::class);
/** @var Message $message */
$message = $messageRepo->find($messageId); $message = $messageRepo->find($messageId);
if (empty($message)) { if (empty($message)) {
@ -236,12 +235,12 @@ switch ($action) {
exit; exit;
} }
if ((int) $message->getGroupId() !== $groupId) { if (!empty($message->getGroupReceiver())) {
if ($message->getGroupReceiver()->getId() !== $groupId) {
echo json_encode(false); echo json_encode(false);
exit; exit;
} }
if (!empty($message->getGroupId())) {
$usergroup = new UserGroupModel(); $usergroup = new UserGroupModel();
$groupInfo = $usergroup->get($groupId); $groupInfo = $usergroup->get($groupId);
@ -260,12 +259,12 @@ switch ($action) {
$user = api_get_user_entity($current_user_id); $user = api_get_user_entity($current_user_id);
$userLike = $messageLikesRepo->findOneBy(['message' => $message, 'user' => $user]); $userLike = $messageLikesRepo->findOneBy(['post' => $message, 'user' => $user]);
if (empty($userLike)) { if (empty($userLike)) {
$userLike = new MessageFeedback(); $userLike = new SocialPostFeedback();
$userLike $userLike
->setMessage($message) ->setSocialPost($message)
->setUser($user); ->setUser($user);
} }

@ -5,7 +5,8 @@
use Chamilo\CoreBundle\Entity\Course; use Chamilo\CoreBundle\Entity\Course;
use Chamilo\CoreBundle\Entity\Message; use Chamilo\CoreBundle\Entity\Message;
use Chamilo\CoreBundle\Entity\MessageAttachment; use Chamilo\CoreBundle\Entity\MessageAttachment;
use Chamilo\CoreBundle\Entity\MessageFeedback; use Chamilo\CoreBundle\Entity\SocialPost;
use Chamilo\CoreBundle\Entity\SocialPostFeedback;
use Chamilo\CoreBundle\Entity\User; use Chamilo\CoreBundle\Entity\User;
use Chamilo\CoreBundle\Framework\Container; use Chamilo\CoreBundle\Framework\Container;
use ChamiloSession as Session; use ChamiloSession as Session;
@ -1648,36 +1649,20 @@ class MessageManager
* *
* @return array * @return array
*/ */
public static function countLikesAndDislikes($messageId, $userId) public static function countLikesAndDislikes($messageId, $userId): array
{ {
if (!api_get_configuration_value('social_enable_messages_feedback')) { if (!api_get_configuration_value('social_enable_messages_feedback')) {
return []; return [];
} }
$messageId = (int) $messageId; $user = Container::getUserRepository()->find($userId);
$userId = (int) $userId; $socialPost = Container::getSocialPostRepository()->find($messageId);
$em = Database::getManager();
$query = $em
->createQuery('
SELECT SUM(l.liked) AS likes, SUM(l.disliked) AS dislikes FROM ChamiloCoreBundle:MessageFeedback l
WHERE l.message = :message
')
->setParameters(['message' => $messageId]);
try {
$counts = $query->getSingleResult();
} catch (Exception $e) {
$counts = ['likes' => 0, 'dislikes' => 0];
}
$userLike = $em $userLike = $user->getSocialPostFeedbackBySocialPost($socialPost);
->getRepository(MessageFeedback::class)
->findOneBy(['message' => $messageId, 'user' => $userId]);
return [ return [
'likes' => (int) $counts['likes'], 'likes' => $socialPost->getCountFeedbackLikes(),
'dislikes' => (int) $counts['dislikes'], 'dislikes' => $socialPost->getCountFeedbackDislikes(),
'user_liked' => $userLike ? $userLike->isLiked() : false, 'user_liked' => $userLike ? $userLike->isLiked() : false,
'user_disliked' => $userLike ? $userLike->isDisliked() : false, 'user_disliked' => $userLike ? $userLike->isDisliked() : false,
]; ];

@ -238,18 +238,6 @@ class Message
#[Groups(['message:read'])] #[Groups(['message:read'])]
protected Collection $attachments; protected Collection $attachments;
/**
* @var Collection<int, MessageFeedback>
*
* @ORM\OneToMany(targetEntity="MessageFeedback", mappedBy="message", orphanRemoval=true)
*/
protected Collection $likes;
#[Groups(['message:read'])]
protected int $countLikes = 0;
#[Groups(['message:read'])]
protected int $countDislikes = 0;
public function __construct() public function __construct()
{ {
$this->sendDate = new DateTime('now'); $this->sendDate = new DateTime('now');
@ -258,7 +246,6 @@ class Message
$this->content = ''; $this->content = '';
$this->attachments = new ArrayCollection(); $this->attachments = new ArrayCollection();
$this->children = new ArrayCollection(); $this->children = new ArrayCollection();
$this->likes = new ArrayCollection();
$this->receivers = new ArrayCollection(); $this->receivers = new ArrayCollection();
$this->receiversCc = new ArrayCollection(); $this->receiversCc = new ArrayCollection();
$this->receiversTo = new ArrayCollection(); $this->receiversTo = new ArrayCollection();
@ -541,24 +528,4 @@ class Message
return $this; return $this;
} }
public function getCountLikes(): int
{
$criteria = Criteria::create();
$criteria->where(
Criteria::expr()->eq('liked', true)
);
return $this->likes->matching($criteria)->count();
}
public function getCountDislikes(): int
{
$criteria = Criteria::create();
$criteria->where(
Criteria::expr()->eq('disliked', true)
);
return $this->likes->matching($criteria)->count();
}
} }

@ -0,0 +1,315 @@
<?php
namespace Chamilo\CoreBundle\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Chamilo\CoreBundle\Repository\SocialPostRepository;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Table(name="social_post", indexes={
* @ORM\Index(name="idx_social_post_sender", columns={"sender_id"}),
* @ORM\Index(name="idx_social_post_user", columns={"user_receiver_id"}),
* @ORM\Index(name="idx_social_post_group", columns={"group_receiver_id"}),
* @ORM\Index(name="idx_social_post_type", columns={"type"})
* })
* @ORM\Entity(repositoryClass=SocialPostRepository::class)
*/
#[ApiResource(
attributes: [
'security' => "is_granted('ROLE_USER')",
],
denormalizationContext: [
'groups' => ['social_post:write'],
],
normalizationContext: [
'groups' => ['social_post:read'],
],
)]
class SocialPost
{
public const TYPE_WALL_POST = 1;
public const TYPE_WALL_COMMENT = 2;
public const TYPE_GROUP_MESSAGE = 3;
public const TYPE_PROMOTED_MESSAGE = 4;
public const STATUS_SENT = 1;
public const STATUS_DELETED = 2;
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(name="id", type="bigint")
*/
protected int $id;
/**
* @ORM\ManyToOne(targetEntity="Chamilo\CoreBundle\Entity\User", inversedBy="sentSocialPosts")
* @ORM\JoinColumn(nullable=false)
*/
#[Groups(['social_post:read'])]
protected User $sender;
/**
* @ORM\ManyToOne(targetEntity="Chamilo\CoreBundle\Entity\User", inversedBy="receivedSocialPosts")
*/
#[Groups(['social_post:read'])]
protected User $userReceiver;
/**
* @ORM\Column(type="text")
*/
#[Groups(['social_post:read'])]
protected string $content;
/**
* @Assert\Choice({
* SocialPost::TYPE_WALL_POST,
* SocialPost::TYPE_WALL_COMMENT,
* SocialPost::TYPE_GROUP_MESSAGE,
* SocialPost::TYPE_PROMOTED_MESSAGE,
* },
* message="Choose a valid type."
* )
* @ORM\Column(type="smallint")
*/
protected int $type;
/**
* @Assert\Choice({
* SocialPost::STATUS_SENT,
* SocialPost::STATUS_DELETED,
* }, message="Choose a status.")
*
* @ORM\Column(type="smallint")
*/
protected int $status;
/**
* @ORM\Column(type="datetime")
*/
#[Groups(['social_post:read'])]
protected DateTime $sendDate;
/**
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
#[Groups(['social_post:read'])]
protected DateTime $updatedAt;
/**
* @ORM\OneToMany(targetEntity="Chamilo\CoreBundle\Entity\SocialPostFeedback", mappedBy="socialPost")
*/
protected Collection $feedbacks;
/**
* @ORM\ManyToOne(targetEntity="Chamilo\CoreBundle\Entity\Usergroup")
* @ORM\JoinColumn(onDelete="CASCADE")
*/
protected ?Usergroup $groupReceiver = null;
/**
* @ORM\OneToMany(targetEntity="Chamilo\CoreBundle\Entity\SocialPost", mappedBy="parent")
*/
protected Collection $children;
/**
* @ORM\ManyToOne(targetEntity="Chamilo\CoreBundle\Entity\SocialPost", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected ?SocialPost $parent = null;
#[Groups(['social_post:read'])]
protected int $countFeedbackLikes = 0;
#[Groups(['social_post:read'])]
protected int $countFeedbackDislikes = 0;
public function __construct()
{
$this->sendDate = new DateTime();
$this->updatedAt = $this->sendDate;
$this->status = self::STATUS_SENT;
$this->feedbacks = new ArrayCollection();
}
public function getId(): int
{
return $this->id;
}
public function setId(int $id): SocialPost
{
$this->id = $id;
return $this;
}
public function getSender(): User
{
return $this->sender;
}
public function setSender(User $sender): SocialPost
{
$this->sender = $sender;
return $this;
}
public function getUserReceiver(): User
{
return $this->userReceiver;
}
public function setUserReceiver(User $userReceiver): SocialPost
{
$this->userReceiver = $userReceiver;
return $this;
}
public function getStatus(): int
{
return $this->status;
}
public function setStatus(int $status): SocialPost
{
$this->status = $status;
return $this;
}
public function getSendDate(): DateTime
{
return $this->sendDate;
}
public function setSendDate(DateTime $sendDate): SocialPost
{
$this->sendDate = $sendDate;
return $this;
}
public function getContent(): string
{
return $this->content;
}
public function setContent(string $content): SocialPost
{
$this->content = $content;
return $this;
}
public function getUpdatedAt(): DateTime
{
return $this->updatedAt;
}
public function setUpdatedAt(DateTime $updatedAt): SocialPost
{
$this->updatedAt = $updatedAt;
return $this;
}
public function getFeedbacks(): Collection
{
return $this->feedbacks;
}
public function setFeedbacks(Collection $feedbacks): SocialPost
{
$this->feedbacks = $feedbacks;
return $this;
}
public function addFeedback(SocialPostFeedback $feedback): self
{
if (!$this->feedbacks->contains($feedback)) {
$this->feedbacks[] = $feedback;
$feedback->setSocialPost($this);
}
return $this;
}
public function getCountFeedbackLikes(): int
{
$criteria = Criteria::create();
$criteria->where(
Criteria::expr()
->eq('liked', true)
);
return $this->feedbacks->matching($criteria)
->count()
;
}
public function getCountFeedbackDislikes(): int
{
$criteria = Criteria::create();
$criteria->where(
Criteria::expr()
->eq('disliked', true)
);
return $this->feedbacks->matching($criteria)
->count()
;
}
public function getParent(): ?self
{
return $this->parent;
}
public function setParent(self $parent = null): self
{
$this->parent = $parent;
return $this;
}
/**
* @return Collection<int, SocialPost>
*/
public function getChildren(): Collection
{
return $this->children;
}
public function addChild(self $child): self
{
$this->children[] = $child;
$child->setParent($this);
return $this;
}
public function getGroupReceiver(): ?Usergroup
{
return $this->groupReceiver;
}
public function setGroupReceiver(?Usergroup $groupReceiver): self
{
$this->groupReceiver = $groupReceiver;
return $this;
}
}

@ -1,9 +1,8 @@
<?php <?php
/* For licensing terms, see /license.txt */
declare(strict_types=1); declare(strict_types=1);
/* For licensing terms, see /license.txt */
namespace Chamilo\CoreBundle\Entity; namespace Chamilo\CoreBundle\Entity;
use Chamilo\CoreBundle\Traits\UserTrait; use Chamilo\CoreBundle\Traits\UserTrait;
@ -14,14 +13,14 @@ use Gedmo\Mapping\Annotation as Gedmo;
/** /**
* @ORM\Table( * @ORM\Table(
* name="message_feedback", * name="social_post_feedback",
* indexes={ * indexes={
* @Index(name="idx_message_feedback_uid_mid", columns={"message_id", "user_id"}) * @Index(name="idx_social_post_uid_spid", columns={"social_post_id", "user_id"})
* } * }
* ) * )
* @ORM\Entity() * @ORM\Entity()
*/ */
class MessageFeedback class SocialPostFeedback
{ {
use UserTrait; use UserTrait;
@ -33,13 +32,13 @@ class MessageFeedback
protected int $id; protected int $id;
/** /**
* @ORM\ManyToOne(targetEntity="Chamilo\CoreBundle\Entity\Message", inversedBy="likes") * @ORM\ManyToOne(targetEntity="Chamilo\CoreBundle\Entity\SocialPost", inversedBy="feedbacks")
* @ORM\JoinColumn(name="message_id", referencedColumnName="id", nullable=false, onDelete="CASCADE") * @ORM\JoinColumn(name="social_post_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
*/ */
protected Message $message; protected SocialPost $socialPost;
/** /**
* @ORM\ManyToOne(targetEntity="Chamilo\CoreBundle\Entity\User") * @ORM\ManyToOne(targetEntity="Chamilo\CoreBundle\Entity\User", inversedBy="socialPostsFeedbacks")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false, onDelete="CASCADE") * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
*/ */
protected User $user; protected User $user;
@ -61,22 +60,19 @@ class MessageFeedback
*/ */
protected DateTime $updatedAt; protected DateTime $updatedAt;
/** public function getId(): int
* @return int
*/
public function getId()
{ {
return $this->id; return $this->id;
} }
public function getMessage(): Message public function getSocialPost(): SocialPost
{ {
return $this->message; return $this->socialPost;
} }
public function setMessage(Message $message): self public function setSocialPost(SocialPost $socialPost): self
{ {
$this->message = $message; $this->socialPost = $socialPost;
return $this; return $this;
} }
@ -105,10 +101,7 @@ class MessageFeedback
return $this; return $this;
} }
/** public function getUpdatedAt(): DateTime
* @return DateTime
*/
public function getUpdatedAt()
{ {
return $this->updatedAt; return $this->updatedAt;
} }

@ -796,6 +796,21 @@ class User implements UserInterface, EquatableInterface, ResourceInterface, Reso
#[Groups(['user:read', 'user_json:read'])] #[Groups(['user:read', 'user_json:read'])]
protected string $fullName; protected string $fullName;
/**
* @ORM\OneToMany(targetEntity="Chamilo\CoreBundle\Entity\SocialPost", mappedBy="sender", orphanRemoval=true)
*/
private Collection $sentSocialPosts;
/**
* @ORM\OneToMany(targetEntity="Chamilo\CoreBundle\Entity\SocialPost", mappedBy="userReceiver")
*/
private Collection $receivedSocialPosts;
/**
* @ORM\OneToMany(targetEntity="Chamilo\CoreBundle\Entity\SocialPostFeedback", mappedBy="user", orphanRemoval=true)
*/
private Collection $socialPostsFeedbacks;
public function __construct() public function __construct()
{ {
$this->skipResourceNode = false; $this->skipResourceNode = false;
@ -866,6 +881,9 @@ class User implements UserInterface, EquatableInterface, ResourceInterface, Reso
$this->dateOfBirth = new DateTime(); $this->dateOfBirth = new DateTime();
$this->expiresAt = new DateTime(); $this->expiresAt = new DateTime();
$this->passwordRequestedAt = new DateTime(); $this->passwordRequestedAt = new DateTime();
$this->sentSocialPosts = new ArrayCollection();
$this->receivedSocialPosts = new ArrayCollection();
$this->socialPostsFeedbacks = new ArrayCollection();
} }
public function __toString(): string public function __toString(): string
@ -2504,4 +2522,83 @@ class User implements UserInterface, EquatableInterface, ResourceInterface, Reso
return $friends->exists(fn (int $index, UserRelUser $userRelUser) => $userRelUser->getFriend() === $friend); return $friends->exists(fn (int $index, UserRelUser $userRelUser) => $userRelUser->getFriend() === $friend);
} }
/**
* @return Collection<int, SocialPost>
*/
public function getSentSocialPosts(): Collection
{
return $this->sentSocialPosts;
}
public function addSentSocialPost(SocialPost $sentSocialPost): self
{
if (!$this->sentSocialPosts->contains($sentSocialPost)) {
$this->sentSocialPosts[] = $sentSocialPost;
$sentSocialPost->setSender($this);
}
return $this;
}
public function removeSentSocialPost(SocialPost $sentSocialPost): self
{
if ($this->sentSocialPosts->removeElement($sentSocialPost)) {
// set the owning side to null (unless already changed)
if ($sentSocialPost->getSender() === $this) {
$sentSocialPost->setSender(null);
}
}
return $this;
}
/**
* @return Collection<int, SocialPost>
*/
public function getReceivedSocialPosts(): Collection
{
return $this->receivedSocialPosts;
}
public function addReceivedSocialPost(SocialPost $receivedSocialPost): self
{
if (!$this->receivedSocialPosts->contains($receivedSocialPost)) {
$this->receivedSocialPosts[] = $receivedSocialPost;
$receivedSocialPost->setUserReceiver($this);
}
return $this;
}
/**
* @return Collection<int, SocialPostFeedback>
*/
public function getSocialPostsFeedbacks(): Collection
{
return $this->socialPostsFeedbacks;
}
public function getSocialPostFeedbackBySocialPost(SocialPost $post): ?SocialPostFeedback
{
$filtered = $this
->getSocialPostsFeedbacks()
->filter(fn(SocialPostFeedback $postFeedback) => $postFeedback->getSocialPost() === $post);
if ($filtered->count() > 0) {
return $filtered->first();
}
return null;
}
public function addSocialPostFeedback(SocialPostFeedback $socialPostFeedback): self
{
if (!$this->socialPostsFeedbacks->contains($socialPostFeedback)) {
$this->socialPostsFeedbacks[] = $socialPostFeedback;
$socialPostFeedback->setUser($this);
}
return $this;
}
} }

@ -30,6 +30,7 @@ use Chamilo\CoreBundle\Repository\SequenceRepository;
use Chamilo\CoreBundle\Repository\SequenceResourceRepository; use Chamilo\CoreBundle\Repository\SequenceResourceRepository;
use Chamilo\CoreBundle\Repository\SessionRepository; use Chamilo\CoreBundle\Repository\SessionRepository;
use Chamilo\CoreBundle\Repository\SkillRepository; use Chamilo\CoreBundle\Repository\SkillRepository;
use Chamilo\CoreBundle\Repository\SocialPostRepository;
use Chamilo\CoreBundle\Repository\SysAnnouncementRepository; use Chamilo\CoreBundle\Repository\SysAnnouncementRepository;
use Chamilo\CoreBundle\Repository\TagRepository; use Chamilo\CoreBundle\Repository\TagRepository;
use Chamilo\CoreBundle\Repository\TrackExerciseRepository; use Chamilo\CoreBundle\Repository\TrackExerciseRepository;
@ -617,4 +618,9 @@ class Container
$em = $doctrine->getManager(); $em = $doctrine->getManager();
Database::setManager($em); Database::setManager($em);
} }
public static function getSocialPostRepository(): SocialPostRepository
{
return self::$container->get(SocialPostRepository::class);
}
} }

@ -74,10 +74,10 @@ final class Version20200821224242 extends AbstractMigrationChamilo
} }
if (!$table->hasForeignKey('FK_B6BD307F727ACA70')) { if (!$table->hasForeignKey('FK_B6BD307F727ACA70')) {
$this->addSql('CREATE INDEX IDX_B6BD307F727ACA70 ON message (parent_id)');
$this->addSql( $this->addSql(
'ALTER TABLE message ADD CONSTRAINT FK_B6BD307F727ACA70 FOREIGN KEY (parent_id) REFERENCES message (id);' 'ALTER TABLE message ADD CONSTRAINT FK_B6BD307F727ACA70 FOREIGN KEY (parent_id) REFERENCES message (id);'
); );
$this->addSql('CREATE INDEX IDX_B6BD307F727ACA70 ON message (parent_id)');
} }
$this->addSql('DELETE FROM message WHERE user_sender_id IS NULL OR user_sender_id = 0'); $this->addSql('DELETE FROM message WHERE user_sender_id IS NULL OR user_sender_id = 0');
@ -159,25 +159,86 @@ final class Version20200821224242 extends AbstractMigrationChamilo
$this->addSql('DROP INDEX idx_message_user_sender_user_receiver ON message'); $this->addSql('DROP INDEX idx_message_user_sender_user_receiver ON message');
} }
//ALTER TABLE message DROP user_receiver_id;
if (!$table->hasIndex('idx_message_type')) { if (!$table->hasIndex('idx_message_type')) {
$this->addSql('CREATE INDEX idx_message_type ON message (msg_type)'); $this->addSql('CREATE INDEX idx_message_type ON message (msg_type)');
} }
//$this->addSql('ALTER TABLE message CHANGE msg_status msg_status SMALLINT NOT NULL;'); //$this->addSql('ALTER TABLE message CHANGE msg_status msg_status SMALLINT NOT NULL;');
$table = $schema->hasTable('message_feedback'); $this->addSql("CREATE TABLE social_post (id BIGINT AUTO_INCREMENT NOT NULL, sender_id INT NOT NULL, user_receiver_id INT DEFAULT NULL, group_receiver_id INT DEFAULT NULL, parent_id BIGINT DEFAULT NULL, content LONGTEXT NOT NULL, type SMALLINT NOT NULL, status SMALLINT NOT NULL, send_date DATETIME NOT NULL COMMENT '(DC2Type:datetime)', updated_at DATETIME NOT NULL COMMENT '(DC2Type:datetime)', INDEX IDX_159BBFE9727ACA70 (parent_id), INDEX idx_social_post_sender (sender_id), INDEX idx_social_post_user (user_receiver_id), INDEX idx_social_post_group (group_receiver_id), INDEX idx_social_post_type (type), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB ROW_FORMAT = DYNAMIC");
if (false === $table) {
$this->addSql( $sql = "INSERT INTO social_post (id, sender_id, user_receiver_id, group_receiver_id, parent_id, content, type, status, send_date, updated_at)
'CREATE TABLE message_feedback (id BIGINT AUTO_INCREMENT NOT NULL, message_id BIGINT NOT NULL, user_id INT NOT NULL, liked TINYINT(1) DEFAULT 0 NOT NULL, disliked TINYINT(1) DEFAULT 0 NOT NULL, updated_at DATETIME NOT NULL, INDEX IDX_DB0F8049537A1329 (message_id), INDEX IDX_DB0F8049A76ED395 (user_id), INDEX idx_message_feedback_uid_mid (message_id, user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB ROW_FORMAT = DYNAMIC;' SELECT DISTINCT m.id,
); m.user_sender_id,
$this->addSql( m.user_receiver_id,
'ALTER TABLE message_feedback ADD CONSTRAINT FK_DB0F8049537A1329 FOREIGN KEY (message_id) REFERENCES message (id) ON DELETE CASCADE' m.group_id,
); m.parent_id,
$this->addSql( m.content,
'ALTER TABLE message_feedback ADD CONSTRAINT FK_DB0F8049A76ED395 FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE;' CASE m.msg_type
); WHEN 1 THEN 3
WHEN 8 THEN 2
WHEN 9 THEN 1
WHEN 10 THEN 1
WHEN 13 THEN 4
ELSE 1
END AS type,
CASE m.msg_type
WHEN 1 THEN 1
WHEN 8 THEN 1
WHEN 10 THEN 1
WHEN 13 THEN 1
WHEN 9 THEN 2
ELSE 2
END AS status,
m.send_date,
m.update_date
FROM message m
INNER JOIN message_feedback mf ON m.id = mf.message_id
WHERE m.msg_type IN (1, 8, 9, 10, 13)";
$this->addSql($sql);
$this->addSql('DELETE FROM social_post WHERE parent_id NOT IN (SELECT id FROM social_post)');
$this->addSql("ALTER TABLE social_post ADD CONSTRAINT FK_159BBFE9F624B39D FOREIGN KEY (sender_id) REFERENCES user (id)");
$this->addSql("ALTER TABLE social_post ADD CONSTRAINT FK_159BBFE964482423 FOREIGN KEY (user_receiver_id) REFERENCES user (id)");
$this->addSql("ALTER TABLE social_post ADD CONSTRAINT FK_159BBFE9E8EBF277 FOREIGN KEY (group_receiver_id) REFERENCES usergroup (id) ON DELETE CASCADE");
$this->addSql("ALTER TABLE social_post ADD CONSTRAINT FK_159BBFE9727ACA70 FOREIGN KEY (parent_id) REFERENCES social_post (id) ON DELETE CASCADE");
if ($schema->hasTable('message_feedback')) {
$this->addSql('DELETE FROM message_feedback WHERE user_id IS NULL OR user_id = 0');
$table = $schema->getTable('message_feedback');
if ($table->hasForeignKey('FK_DB0F8049537A1329')) {
$this->addSql('ALTER TABLE message_feedback DROP FOREIGN KEY FK_DB0F8049537A1329');
}
if ($table->hasIndex('IDX_DB0F8049537A1329')) {
$this->addSql('DROP INDEX IDX_DB0F8049537A1329 ON message_feedback');
}
if ($table->hasForeignKey('FK_DB0F8049A76ED395')) {
$this->addSql('ALTER TABLE message_feedback DROP FOREIGN KEY FK_DB0F8049A76ED395');
}
if ($table->hasIndex('IDX_DB0F8049A76ED395')) {
$this->addSql('DROP INDEX IDX_DB0F8049A76ED395 ON message_feedback');
} }
if ($table->hasIndex('idx_message_feedback_uid_mid')) {
$this->addSql('DROP INDEX idx_message_feedback_uid_mid ON message_feedback');
}
$this->addSql('ALTER TABLE message_feedback CHANGE message_id social_post_id BIGINT NOT NULL');
$this->addSql('RENAME TABLE message_feedback TO social_post_feedback');
$this->addSql("DELETE FROM social_post_feedback WHERE social_post_id NOT IN (SELECT id FROM social_post)");
} else {
$this->addSql("CREATE TABLE social_post_feedback (id BIGINT AUTO_INCREMENT NOT NULL, social_post_id BIGINT NOT NULL, user_id INT NOT NULL, liked TINYINT(1) DEFAULT '0' NOT NULL, disliked TINYINT(1) DEFAULT '0' NOT NULL, updated_at DATETIME NOT NULL COMMENT '(DC2Type:datetime)', INDEX IDX_DB7E436DC4F2D6B1 (social_post_id), INDEX IDX_DB7E436DA76ED395 (user_id), INDEX idx_social_post_uid_spid (social_post_id, user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB ROW_FORMAT = DYNAMIC");
}
$this->addSql('CREATE INDEX IDX_DB7E436DA76ED395 ON social_post_feedback (user_id)');
$this->addSql('ALTER TABLE social_post_feedback ADD CONSTRAINT FK_DB7E436DA76ED395 FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE');
$this->addSql('CREATE INDEX IDX_DB7E436DC4F2D6B1 ON social_post_feedback (social_post_id)');
$this->addSql('ALTER TABLE social_post_feedback ADD CONSTRAINT FK_DB7E436DC4F2D6B1 FOREIGN KEY (social_post_id) REFERENCES social_post (id) ON DELETE CASCADE');
$this->addSql('CREATE INDEX idx_social_post_uid_spid ON social_post_feedback (social_post_id, user_id)');
//ALTER TABLE message DROP user_receiver_id;
$this->addSql('DELETE FROM message_attachment WHERE message_id NOT IN (SELECT id FROM message)'); $this->addSql('DELETE FROM message_attachment WHERE message_id NOT IN (SELECT id FROM message)');

@ -0,0 +1,39 @@
<?php
namespace Chamilo\CoreBundle\Repository;
use Chamilo\CoreBundle\Entity\SocialPost;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Doctrine\Persistence\ManagerRegistry;
class SocialPostRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, SocialPost::class);
}
/**
* @throws OptimisticLockException
* @throws ORMException
*/
public function update(SocialPost $post)
{
$em = $this->getEntityManager();
$em->persist($post);
$em->flush();
}
/**
* @throws OptimisticLockException
* @throws ORMException
*/
public function delete(SocialPost $post)
{
$em = $this->getEntityManager();
$em->remove($post);
$em->flush();
}
}

@ -8,7 +8,6 @@ namespace Chamilo\Tests\CoreBundle\Repository;
use Chamilo\CoreBundle\Entity\Message; use Chamilo\CoreBundle\Entity\Message;
use Chamilo\CoreBundle\Entity\MessageAttachment; use Chamilo\CoreBundle\Entity\MessageAttachment;
use Chamilo\CoreBundle\Entity\MessageFeedback;
use Chamilo\CoreBundle\Entity\MessageRelUser; use Chamilo\CoreBundle\Entity\MessageRelUser;
use Chamilo\CoreBundle\Entity\MessageTag; use Chamilo\CoreBundle\Entity\MessageTag;
use Chamilo\CoreBundle\Entity\User; use Chamilo\CoreBundle\Entity\User;
@ -82,57 +81,6 @@ class MessageRepositoryTest extends AbstractApiTest
$this->assertSame(1, $testUser->getReceivedMessages()->count()); $this->assertSame(1, $testUser->getReceivedMessages()->count());
} }
public function testCreateMessageWithFeedback(): void
{
$em = $this->getEntityManager();
$messageRepo = self::getContainer()->get(MessageRepository::class);
$messageFeedbackRepo = $em->getRepository(MessageFeedback::class);
$admin = $this->getUser('admin');
$testUser = $this->createUser('test');
$message = (new Message())
->setTitle('hello')
->setContent('content')
->setMsgType(Message::MESSAGE_TYPE_INBOX)
->setSender($admin)
->addReceiver($testUser)
->setSendDate(new DateTime())
->setVotes(0)
->setGroup(null)
;
$messageRepo->update($message);
// 1. Message exists in the inbox.
$this->assertSame(1, $messageRepo->count([]));
$feedback = (new MessageFeedback())
->setMessage($message)
->setUser($testUser)
->setUpdatedAt(new DateTime())
->setDisliked(true)
->setLiked(true)
;
$em->persist($feedback);
$em->flush();
$em->clear();
$this->assertSame(1, $messageFeedbackRepo->count([]));
$this->assertNotNull($feedback->getUser());
$this->assertNotNull($feedback->getUpdatedAt());
$this->assertNotNull($feedback->getMessage());
/** @var Message $message */
$message = $messageRepo->find($message->getId());
$this->assertSame(1, $message->getLikes()->count());
$messageRepo->delete($message);
$this->assertSame(0, $messageRepo->count([]));
$this->assertSame(0, $messageFeedbackRepo->count([]));
}
public function testCreateMessageWithTags(): Message public function testCreateMessageWithTags(): Message
{ {
$em = $this->getEntityManager(); $em = $this->getEntityManager();

@ -0,0 +1,75 @@
<?php
/* For licensing terms, see /license.txt */
declare(strict_types=1);
namespace Chamilo\Tests\CoreBundle\Repository;
use Chamilo\CoreBundle\Entity\SocialPost;
use Chamilo\CoreBundle\Entity\SocialPostFeedback;
use Chamilo\CoreBundle\Repository\SocialPostRepository;
use Chamilo\Tests\AbstractApiTest;
use Chamilo\Tests\ChamiloTestTrait;
use DateTime;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Doctrine\Persistence\Mapping\MappingException;
class SocialPostRepositoryTest extends AbstractApiTest
{
use ChamiloTestTrait;
/**
* @throws OptimisticLockException
* @throws ORMException
* @throws MappingException
*/
public function testCreateMessageWithFeedback(): void
{
$em = $this->getEntityManager();
$socialPostRepo = self::getContainer()
->get(SocialPostRepository::class);
$socialPostFeedbackRepo = $em->getRepository(SocialPostFeedback::class);
$admin = $this->getUser('admin');
$testUser = $this->createUser('test');
$post = (new SocialPost())
->setContent('content')
->setSender($admin)
->setUserReceiver($testUser);
$socialPostRepo->update($post);
// 1. Message exists in the inbox.
$this->assertSame(1, $socialPostRepo->count([]));
$feedback = (new SocialPostFeedback())
->setSocialPost($post)
->setUser($testUser)
->setUpdatedAt(new DateTime())
->setDisliked(true)
->setLiked(true);
$em->persist($feedback);
$em->flush();
$em->clear();
$this->assertSame(1, $socialPostFeedbackRepo->count([]));
$this->assertNotNull($feedback->getUser());
$this->assertNotNull($feedback->getUpdatedAt());
$this->assertNotNull($feedback->getSocialPost());
$post = $socialPostRepo->find($post->getId());
$this->assertSame(
1,
$post->getLikes()
->count()
);
$socialPostRepo->delete($post);
$this->assertSame(0, $socialPostRepo->count([]));
$this->assertSame(0, $socialPostFeedbackRepo->count([]));
}
}
Loading…
Cancel
Save