Ash framework Relationships based role

Hi I would like to know if this is possible

I have a user Resource with this attribures

defmodule PapiShampu.Crm.User do
  use Ash.Resource,
    domain: PapiShampu.Crm,
    data_layer: AshPostgres.DataLayer

  postgres do
    table "users"
    repo PapiShampu.RepoApp
  end

  actions do
    defaults [:read, :destroy, :create, :update]
  end

  attributes do
    uuid_v7_primary_key :id

    attribute :role, :atom do
      constraints one_of: [:client, :admin, :employee, :provider]

      default :client

      allow_nil? false
    end

    attribute :first_name, :string
    attribute :last_name, :string
    attribute :dni, :string
    attribute :account_id, :uuid_v7

    create_timestamp :created_at
    update_timestamp :updated_at
  end

  relationships do
    has_one :contact_info, PapiShampu.Auth.Account do
      domain PapiShampu.Auth
    end

    has_many :addresses, PapiShampu.Crm.Address
    has_many :bills, PapiShampu.Crm.Bill
    has_many :sales, PapiShampu.Crm.Sale

    many_to_many :stores, PapiShampu.Crm.Store do
      through PapiShampu.Crm.StoreUser
      source_attribute_on_join_resource :store_id
      destination_attribute_on_join_resource :user_id
    end

    belongs_to :account, PapiShampu.Auth.Account do
      domain PapiShampu.Auth
    end
  end
end

And I want to add into sale resource a relationship based on the role like this

defmodule PapiShampu.Crm.Sale do
  use Ash.Resource,
    domain: PapiShampu.Crm,
    data_layer: AshPostgres.DataLayer

  postgres do
    table "sales"
    repo PapiShampu.RepoApp
  end

  attributes do
    uuid_v7_primary_key :id
    attribute :payment_id, :uuid_v7
    attribute :employee_id, :uuid_v7
    attribute :client_id, :uuid_v7
    attribute :bill_id, :uuid_v7
    attribute :store_id, :uuid_v7

    create_timestamp :created_at
    update_timestamp :updated_at
  end

  relationships do
    many_to_many :products, PapiShampu.Crm.Product do
      through PapiShampu.Crm.SaleProduct

      source_attribute_on_join_resource :sale_id
      destination_attribute_on_join_resource :product_id
    end

    belongs_to :payment, PapiShampu.Crm.Payment

    belongs_to :employee, PapiShampu.Crm.User do
      filter expr(:role == :employee)
    end

    belongs_to :client, PapiShampu.Crm.User do
      filter expr(:role == :client)
    end

    belongs_to :bill, PapiShampu.Crm.Bill

    belongs_to :store, PapiShampu.Crm.Store
  end
end

Is this a correct way?

Yep, something like that should work.

1 Like