BananaCrystal / email-templates

This repository contains in-house email templates that serve as structure for our emails. Each template can be updated and modified to fit requirements.
MIT License
0 stars 0 forks source link

chats_controller.rb #34

Open geekelo opened 1 month ago

geekelo commented 1 month ago
module Api::V1
  class P2pTrades::ChatsController < Api::BaseController
    before_action :find_trade

    def index
      @chats = @trade.chats.includes(:attachment_attachment)
      render json: @chats, each_serializer: P2pChatSerializer
    end

    def create
      @chat = @trade.chats.new(chat_params)

      if @chat.save
        broadcast_message
        P2pApi::Chat::CreateJob.perform_later(@chat)

        render json: @chat, serializer: P2pChatSerializer
      else
        errors = ResourceErrors.format(@chat)

        render json: { errors: errors }, status: :bad_request
      end
    end

    def upload_attachment
      @chat = @trade.chats.new(chat_params)

      @chat.attachment.attach(params[:file]) if params[:file].present?

      if @chat.save
        broadcast_message
        P2pApi::Chat::UploadAttachmentJob.perform_later(@chat)

        render json: @chat, serializer: P2pChatSerializer
      else
        errors = ResourceErrors.format(@chat)

        render json: { errors: errors }, status: :bad_request
      end
    end

    def update_read_messages
      @chats = @trade.chats.where(id: params[:chat_ids])
      if @chats.any? && @chats.update(is_read: true, read_at: Time.zone.now)
        P2pApi::Chat::UpdateJob.perform_later(@trade, @chats.pluck(:chat_id))
      end

      head :ok
    end

    private

    def broadcast_message
      ActionCable.server.broadcast("p2p_chat_channel_#{@trade.id}",
                                   message: chat_params[:message],
                                   profile_id: current_user.profile.id,
                                   trade_id: @trade.id,
                                   id: @chat.id,
                                   created_at: @chat.created_at,
                                   attachment_url: @chat.attachment.attached? ? rails_blob_url(@chat.attachment) : nil)
    end

    def chat_params
      params.permit(:message, :trade_id).merge(profile_id: current_user.profile.id)
    end

    def find_trade
      @trade = P2pTrade.find(params[:trade_id])
    end
  end
end
geekelo commented 1 month ago

Here's a detailed breakdown of your P2pTrades::ChatsController within the Api::V1 namespace:

Controller Overview

The P2pTrades::ChatsController handles chat-related actions for a peer-to-peer (P2P) trade system. It provides functionality to manage chats associated with trades, including creating chats, uploading attachments, and updating message statuses.

Actions

  1. index:

    • Purpose: Retrieves and lists all chats associated with a specific trade.
    • Details:
      • Uses @trade.chats.includes(:attachment_attachment) to fetch chats with their attachments.
      • Renders the chats using P2pChatSerializer.
  2. create:

    • Purpose: Creates a new chat message for the trade.
    • Details:
      • Builds a new chat message with @trade.chats.new(chat_params).
      • If the chat is saved successfully:
      • Calls broadcast_message to broadcast the new chat message via ActionCable.
      • Enqueues a background job P2pApi::Chat::CreateJob to process the chat asynchronously.
      • If saving fails, returns a 400 Bad Request with errors.
  3. upload_attachment:

    • Purpose: Creates a chat message with an attachment.
    • Details:
      • Similar to create, but also handles file attachment:
      • Attaches the file if params[:file].present?.
      • Enqueues a background job P2pApi::Chat::UploadAttachmentJob to process the attachment asynchronously.
      • Returns a 400 Bad Request with errors if saving fails.
  4. update_read_messages:

    • Purpose: Updates the status of specified chat messages to "read".
    • Details:
      • Finds chats by IDs provided in params[:chat_ids].
      • Updates is_read to true and sets read_at to the current time.
      • Enqueues a background job P2pApi::Chat::UpdateJob to process the update asynchronously.
      • Responds with 200 OK on success.

Private Methods

  1. broadcast_message:

    • Purpose: Broadcasts the newly created or updated chat message to a specific channel.
    • Details:
      • Uses ActionCable to broadcast the message to "p2p_chat_channel_#{@trade.id}".
      • Includes message content, profile ID, trade ID, chat ID, creation timestamp, and attachment URL if present.
  2. chat_params:

    • Purpose: Permits and prepares chat parameters for strong parameter validation.
    • Details:
      • Permits :message and :trade_id, and merges profile_id from the current user.
  3. find_trade:

    • Purpose: Finds and sets the trade based on params[:trade_id].
    • Details:
      • Fetches the trade using P2pTrade.find(params[:trade_id]).

Summary

This controller leverages both immediate and background processing to handle chat operations efficiently and ensures that updates are broadcasted in real-time.