# Family Plan Feature - Implementation Specification ## Implementation Status ### โ Phase 1: Database Foundation - COMPLETED - **3 Database tables created**: families, family_memberships, family_invitations - **4 Model classes implemented**: Family, FamilyMembership, FamilyInvitation, User extensions - **68 comprehensive tests written and passing**: Full test coverage for all models and associations - **Database migrations applied**: All tables created with proper indexes and constraints - **Business logic methods implemented**: User family ownership, account deletion protection, etc. **Ready for Phase 2**: Core Business Logic (Service Classes) --- ## Overview The Family Plan feature allows Dawarich users to create family groups, invite members, and share their latest location data within the family. This feature enhances the social aspect of location tracking while maintaining strong privacy controls. ### Key Features - Create and manage family groups - Invite members via email - Share latest location data within family - Role-based permissions (owner/member) - Privacy controls for location sharing - Email notifications and in-app notifications ### Business Rules - Maximum 5 family members per family (hardcoded constant) - One family per user (must leave current family to join another) - Family owners cannot delete their accounts - Invitation tokens expire after 7 days - Only latest position sharing (no historical data access) - Free for self-hosted instances, paid feature for Dawarich Cloud ## Database Schema ### 1. Family Model ```ruby class Family < ApplicationRecord # Table: families # Primary Key: id (UUID) self.primary_key = :id has_many :family_memberships, dependent: :destroy has_many :members, through: :family_memberships, source: :user has_many :family_invitations, dependent: :destroy belongs_to :creator, class_name: 'User' validates :name, presence: true, length: { maximum: 50 } validates :creator_id, presence: true MAX_MEMBERS = 5 end ``` **Columns:** - `id` (UUID, primary key) - `name` (string, not null) - `creator_id` (UUID, foreign key to users, not null) - `created_at` (datetime) - `updated_at` (datetime) ### 2. FamilyMembership Model ```ruby class FamilyMembership < ApplicationRecord # Table: family_memberships # Primary Key: id (UUID) self.primary_key = :id belongs_to :family belongs_to :user validates :family_id, presence: true validates :user_id, presence: true, uniqueness: true # One family per user validates :role, presence: true validates :status, presence: true enum role: { owner: 0, member: 1 } enum status: { active: 0, inactive: 1 } scope :active, -> { where(status: :active) } end ``` **Columns:** - `id` (UUID, primary key) - `family_id` (UUID, foreign key to families, not null) - `user_id` (UUID, foreign key to users, not null, unique) - `role` (integer, enum: owner=0, member=1, not null) - `status` (integer, enum: active=0, inactive=1, not null, default: active) - `location_sharing_enabled` (boolean, default: true) - `created_at` (datetime) - `updated_at` (datetime) ### 3. FamilyInvitation Model ```ruby class FamilyInvitation < ApplicationRecord # Table: family_invitations # Primary Key: id (UUID) self.primary_key = :id belongs_to :family belongs_to :invited_by, class_name: 'User' validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } validates :token, presence: true, uniqueness: true validates :expires_at, presence: true validates :status, presence: true enum status: { pending: 0, accepted: 1, expired: 2, cancelled: 3 } scope :active, -> { where(status: :pending).where('expires_at > ?', Time.current) } before_validation :generate_token, :set_expiry, on: :create EXPIRY_DAYS = 7 end ``` **Columns:** - `id` (UUID, primary key) - `family_id` (UUID, foreign key to families, not null) - `email` (string, not null) - `token` (string, not null, unique) - `expires_at` (datetime, not null) - `invited_by_id` (UUID, foreign key to users, not null) - `status` (integer, enum: pending=0, accepted=1, expired=2, cancelled=3, default: pending) - `created_at` (datetime) - `updated_at` (datetime) ### 4. User Model Modifications ```ruby # Add to existing User model has_one :family_membership, dependent: :destroy has_one :family, through: :family_membership has_many :created_families, class_name: 'Family', foreign_key: 'creator_id', dependent: :restrict_with_error has_many :sent_family_invitations, class_name: 'FamilyInvitation', foreign_key: 'invited_by_id', dependent: :destroy def in_family? family_membership&.active? end def family_owner? family_membership&.owner? end def can_delete_account? return true unless family_owner? family.members.count <= 1 end ``` ## Database Migrations ### 1. Create Families Table ```ruby class CreateFamilies < ActiveRecord::Migration[8.0] def change enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto') create_table :families, id: :uuid do |t| t.string :name, null: false, limit: 50 t.uuid :creator_id, null: false t.timestamps end add_foreign_key :families, :users, column: :creator_id add_index :families, :creator_id end end ``` ### 2. Create Family Memberships Table ```ruby class CreateFamilyMemberships < ActiveRecord::Migration[8.0] def change create_table :family_memberships, id: :uuid do |t| t.uuid :family_id, null: false t.uuid :user_id, null: false t.integer :role, null: false, default: 1 # member t.integer :status, null: false, default: 0 # active t.boolean :location_sharing_enabled, null: false, default: true t.timestamps end add_foreign_key :family_memberships, :families add_foreign_key :family_memberships, :users add_index :family_memberships, :family_id add_index :family_memberships, :user_id, unique: true # One family per user add_index :family_memberships, [:family_id, :role] end end ``` ### 3. Create Family Invitations Table ```ruby class CreateFamilyInvitations < ActiveRecord::Migration[8.0] def change create_table :family_invitations, id: :uuid do |t| t.uuid :family_id, null: false t.string :email, null: false t.string :token, null: false t.datetime :expires_at, null: false t.uuid :invited_by_id, null: false t.integer :status, null: false, default: 0 # pending t.timestamps end add_foreign_key :family_invitations, :families add_foreign_key :family_invitations, :users, column: :invited_by_id add_index :family_invitations, :family_id add_index :family_invitations, :email add_index :family_invitations, :token, unique: true add_index :family_invitations, :status add_index :family_invitations, :expires_at end end ``` ## Service Classes ### 1. Families::CreateService ```ruby module Families class CreateService include ActiveModel::Validations attr_reader :user, :name, :family validates :name, presence: true, length: { maximum: 50 } def initialize(user:, name:) @user = user @name = name end def call return false unless valid? return false if user.in_family? return false unless can_create_family? ActiveRecord::Base.transaction do create_family create_owner_membership send_notification end true rescue ActiveRecord::RecordInvalid false end private def can_create_family? return true if DawarichSettings.self_hosted? # Add cloud plan validation here user.active? && user.active_until&.future? end def create_family @family = Family.create!( name: name, creator: user ) end def create_owner_membership FamilyMembership.create!( family: family, user: user, role: :owner, status: :active ) end def send_notification Notifications::Create.new( user: user, kind: :info, title: 'Family Created', content: "You've successfully created the family '#{family.name}'" ).call end end end ``` ### 2. Families::InviteService ```ruby module Families class InviteService include ActiveModel::Validations attr_reader :family, :email, :invited_by, :invitation validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } def initialize(family:, email:, invited_by:) @family = family @email = email.downcase.strip @invited_by = invited_by end def call return false unless valid? return false unless can_invite? ActiveRecord::Base.transaction do create_invitation send_invitation_email send_notification end true rescue ActiveRecord::RecordInvalid false end private def can_invite? return false unless invited_by.family_owner? return false if family.members.count >= Family::MAX_MEMBERS return false if user_already_in_family? return false if pending_invitation_exists? true end def user_already_in_family? User.joins(:family_membership) .where(email: email, family_memberships: { status: :active }) .exists? end def pending_invitation_exists? family.family_invitations.active.where(email: email).exists? end def create_invitation @invitation = FamilyInvitation.create!( family: family, email: email, invited_by: invited_by ) end def send_invitation_email FamilyMailer.invitation(@invitation).deliver_later end def send_notification Notifications::Create.new( user: invited_by, kind: :info, title: 'Invitation Sent', content: "Family invitation sent to #{email}" ).call end end end ``` ### 3. Families::AcceptInvitationService ```ruby module Families class AcceptInvitationService attr_reader :invitation, :user def initialize(invitation:, user:) @invitation = invitation @user = user end def call return false unless can_accept? ActiveRecord::Base.transaction do leave_current_family if user.in_family? create_membership update_invitation send_notifications end true rescue ActiveRecord::RecordInvalid false end private def can_accept? return false unless invitation.pending? return false if invitation.expires_at < Time.current return false unless invitation.email == user.email return false if invitation.family.members.count >= Family::MAX_MEMBERS true end def leave_current_family Families::LeaveService.new(user: user).call end def create_membership FamilyMembership.create!( family: invitation.family, user: user, role: :member, status: :active ) end def update_invitation invitation.update!(status: :accepted) end def send_notifications # Notify the user Notifications::Create.new( user: user, kind: :info, title: 'Welcome to Family', content: "You've joined the family '#{invitation.family.name}'" ).call # Notify family owner Notifications::Create.new( user: invitation.family.creator, kind: :info, title: 'New Family Member', content: "#{user.email} has joined your family" ).call end end end ``` ### 4. Families::LeaveService ```ruby module Families class LeaveService attr_reader :user def initialize(user:) @user = user end def call return false unless user.in_family? return false if user.family_owner? && family_has_other_members? ActiveRecord::Base.transaction do handle_ownership_transfer if user.family_owner? deactivate_membership send_notification end true end private def family_has_other_members? user.family.members.count > 1 end def handle_ownership_transfer # If owner is leaving and no other members, family will be deleted via cascade # If owner tries to leave with other members, it is_expected.to be prevented in controller end def deactivate_membership user.family_membership.update!(status: :inactive) end def send_notification Notifications::Create.new( user: user, kind: :info, title: 'Left Family', content: "You've left the family" ).call end end end ``` ### 5. Families::LocationSharingService ```ruby module Families class LocationSharingService def self.family_locations(family) return [] unless family family.members .joins(:family_membership) .where(family_memberships: { location_sharing_enabled: true }) .map { |member| latest_location_for(member) } .compact end def self.latest_location_for(user) latest_point = user.points.order(timestamp: :desc).first return nil unless latest_point { user_id: user.id, email: user.email, latitude: latest_point.latitude, longitude: latest_point.longitude, timestamp: latest_point.timestamp, updated_at: Time.at(latest_point.timestamp) } end end end ``` ## Controllers ### 1. FamiliesController ```ruby class FamiliesController < ApplicationController before_action :authenticate_user! before_action :set_family, only: [:show, :edit, :update, :destroy, :leave] def index redirect_to family_path(current_user.family) if current_user.in_family? end def show authorize @family @members = @family.members.includes(:family_membership) @pending_invitations = @family.family_invitations.pending @family_locations = Families::LocationSharingService.family_locations(@family) end def new redirect_to family_path(current_user.family) if current_user.in_family? @family = Family.new end def create service = Families::CreateService.new( user: current_user, name: family_params[:name] ) if service.call redirect_to family_path(service.family), notice: 'Family created successfully!' else @family = Family.new(family_params) @family.errors.add(:base, 'Failed to create family') render :new, status: :unprocessable_entity end end def edit authorize @family end def update authorize @family if @family.update(family_params) redirect_to family_path(@family), notice: 'Family updated successfully!' else render :edit, status: :unprocessable_entity end end def destroy authorize @family if @family.members.count > 1 redirect_to family_path(@family), alert: 'Cannot delete family with members. Remove all members first.' else @family.destroy redirect_to families_path, notice: 'Family deleted successfully!' end end def leave authorize @family, :leave? service = Families::LeaveService.new(user: current_user) if service.call redirect_to families_path, notice: 'You have left the family' else redirect_to family_path(@family), alert: 'Cannot leave family. Transfer ownership first.' end end private def set_family @family = current_user.family redirect_to families_path unless @family end def family_params params.require(:family).permit(:name) end end ``` ### 2. FamilyMembershipsController ```ruby class FamilyMembershipsController < ApplicationController before_action :authenticate_user! before_action :set_family before_action :set_membership, only: [:show, :update, :destroy] def index authorize @family, :show? @members = @family.members.includes(:family_membership) end def show authorize @membership, :show? end def update authorize @membership if @membership.update(membership_params) redirect_to family_path(@family), notice: 'Settings updated successfully!' else redirect_to family_path(@family), alert: 'Failed to update settings' end end def destroy authorize @membership if @membership.owner? && @family.members.count > 1 redirect_to family_path(@family), alert: 'Transfer ownership before removing yourself' else @membership.update!(status: :inactive) redirect_to family_path(@family), notice: 'Member removed successfully' end end private def set_family @family = current_user.family redirect_to families_path unless @family end def set_membership @membership = @family.family_memberships.find(params[:id]) end def membership_params params.require(:family_membership).permit(:location_sharing_enabled) end end ``` ### 3. FamilyInvitationsController ```ruby class FamilyInvitationsController < ApplicationController before_action :authenticate_user!, except: [:show, :accept] before_action :set_family, except: [:show, :accept] before_action :set_invitation, only: [:show, :accept, :destroy] def index authorize @family, :show? @pending_invitations = @family.family_invitations.pending end def show # Public endpoint for invitation acceptance end def create authorize @family, :invite? service = Families::InviteService.new( family: @family, email: invitation_params[:email], invited_by: current_user ) if service.call redirect_to family_path(@family), notice: 'Invitation sent successfully!' else redirect_to family_path(@family), alert: 'Failed to send invitation' end end def accept authenticate_user! service = Families::AcceptInvitationService.new( invitation: @invitation, user: current_user ) if service.call redirect_to family_path(current_user.family), notice: 'Welcome to the family!' else redirect_to root_path, alert: 'Unable to accept invitation' end end def destroy authorize @family, :manage_invitations? @invitation.update!(status: :cancelled) redirect_to family_path(@family), notice: 'Invitation cancelled' end private def set_family @family = current_user.family redirect_to families_path unless @family end def set_invitation @invitation = FamilyInvitation.find_by!(token: params[:id]) end def invitation_params params.require(:family_invitation).permit(:email) end end ``` ## Pundit Policies ### 1. FamilyPolicy ```ruby class FamilyPolicy < ApplicationPolicy def show? user.family == record end def create? return false if user.in_family? return true if DawarichSettings.self_hosted? # Add cloud subscription checks here user.active? && user.active_until&.future? end def update? user.family == record && user.family_owner? end def destroy? user.family == record && user.family_owner? end def leave? user.family == record && !family_owner_with_members? end def invite? user.family == record && user.family_owner? end def manage_invitations? user.family == record && user.family_owner? end private def family_owner_with_members? user.family_owner? && record.members.count > 1 end end ``` ### 2. FamilyMembershipPolicy ```ruby class FamilyMembershipPolicy < ApplicationPolicy def show? user.family == record.family end def update? # Users can update their own settings return true if user == record.user # Family owners can update any member's settings user.family == record.family && user.family_owner? end def destroy? # Users can remove themselves (handled by family leave logic) return true if user == record.user # Family owners can remove other members user.family == record.family && user.family_owner? end end ``` ## Mailers ### FamilyMailer ```ruby class FamilyMailer < ApplicationMailer def invitation(invitation) @invitation = invitation @family = invitation.family @invited_by = invitation.invited_by @accept_url = family_invitation_url(@invitation.token) mail( to: @invitation.email, subject: "You've been invited to join #{@family.name} on Dawarich" ) end end ``` ### Email Templates #### `app/views/family_mailer/invitation.html.erb` ```erb
Hi there!
<%= @invited_by.email %> has invited you to join their family "<%= @family.name %>" on Dawarich.
By joining this family, you'll be able to:
<%= link_to "Accept Invitation", @accept_url, style: "background-color: #4F46E5; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;" %>
Note: This invitation will expire in 7 days.
If you don't have a Dawarich account yet, you'll be able to create one when you accept the invitation.
If you didn't expect this invitation, you can safely ignore this email.
Best regards,
The Dawarich Team
These actions cannot be undone
<%= @invitation.invited_by.email %> has invited you to join "<%= @invitation.family.name %>" on Dawarich.
This invitation is for <%= @invitation.email %>.
You're signed in as <%= current_user.email %>.
Please sign out and sign in with the correct account, or create a new account with the invited email.
This family invitation has expired or is no longer valid.
<%= link_to "Go to Dawarich", root_path, class: "btn btn-primary" %>