defmodule DaProductApp.Groups.Group do use Ecto.Schema import Ecto.Changeset alias DaProductApp.Brands.Brand schema "groups" do field :name, :string field :code, :string field :description, :string field :status, :string, default: "active" field :phone_number, :string field :registered, :string field :mcc_code, :string field :params, :map field :transaction_currency, :string field :settlement_currency, :string has_many :brands, Brand timestamps() end def changeset(group, attrs) do group |> cast(attrs, [:name, :code, :description, :status, :phone_number, :registered, :mcc_code, :params, :transaction_currency, :settlement_currency]) |> validate_required([:name, :code]) |> validate_length(:code, min: 2, max: 50) |> validate_length(:name, min: 2, max: 255) |> unique_constraint(:code) end end defmodule DaProductApp.Groups do import Ecto.Query alias DaProductApp.Repo alias DaProductApp.Groups.Group alias DaProductApp.Brands.Brand alias DaProductApp.Store def create_or_update_from_params(params) do mcc_code = get_in(params, ["merchantInfo", "merchantMCC"]) group_code = get_in(params, ["merchantInfo", "referenceMerchantId"]) group_name = get_in(params, ["merchantInfo", "merchantDisplayName"]) phone_number = params["phone_number"] # or get_in(params, ["phone_number"]) # Check if group with this mcc_code exists case Repo.get_by(Group, mcc_code: mcc_code) do nil -> # Create group group_changeset = Group.changeset(%Group{}, %{ name: group_name, code: group_code, phone_number: phone_number, registered: params["registered"] || "no", mcc_code: mcc_code, params: params }) case Repo.insert(group_changeset) do {:ok, group} -> # Create brand brand_code = group_code <> "_brand" brand_name = group_name <> " Brand" brand_changeset = Brand.changeset(%Brand{}, %{ code: brand_code, name: brand_name, group_id: group.id }) {:ok, brand} = Repo.insert(brand_changeset) # Create store store_code = get_in(params, ["storeInfo", "referenceStoreId"]) store_name = get_in(params, ["storeInfo", "storeName"]) store_changeset = Store.changeset(%Store{}, %{ code: store_code, name: store_name, brand_id: brand.id, neo_merchant_id: group_code }) Repo.insert(store_changeset) {:ok, :created} {:error, changeset} -> {:error, changeset} end _group -> # Group with this mcc_code already exists, ignore {:ok, :ignored} end end end