Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ SLACK_USER_OAUTH_TOKEN=your_user_oauth_token_here

# Sailors' log slack app for slack channel notifications
SAILORS_LOG_SLACK_SIGNING_SECRET=your_signing_secret_here
SLACK_SAILORS_LOG_BOT_OAUTH_TOKEN=your_bot_oauth_token_here
SAILORS_LOG_SLACK_BOT_OAUTH_TOKEN=your_bot_oauth_token_here

# You can leave this alone if you're using the provided docker setup!
DATABASE_URL=your_database_url_here
Expand Down
23 changes: 21 additions & 2 deletions app/controllers/settings/goals_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ def show = render_goals
def create
@goal = @user.goals.build(goal_params)
if @goal.save
GoalCompletionCheckJob.schedule_for(@user.id)
redirect_to my_settings_goals_path, notice: "Goal created."
else
flash.now[:error] = @goal.errors.full_messages.to_sentence
Expand All @@ -14,6 +15,7 @@ def create
def update
@goal = @user.goals.find(params[:goal_id])
if @goal.update(goal_params)
GoalCompletionCheckJob.schedule_for(@user.id)
redirect_to my_settings_goals_path, notice: "Goal updated."
else
flash.now[:error] = @goal.errors.full_messages.to_sentence
Expand All @@ -34,15 +36,32 @@ def render_goals(status: :ok, goal_form: nil)
end

def section_props
{ programming_goals: programming_goals_props, options: { goals: goal_options } }
{
programming_goals: programming_goals_props,
options: { goals: goal_options },
notification_options: {
email_available: @user.email_addresses.exists?,
slack_available: @user.slack_uid.present?
}
}
end

def goal_params = params.require(:goal).permit(:period, :target_seconds, languages: [], projects: [])
def goal_params
params.require(:goal).permit(
:period,
:target_seconds,
:notify_by_email,
:notify_by_slack,
languages: [],
projects: []
)
end

def goal_form_props(goal, mode)
{ open: true, mode: mode, goal_id: goal.id&.to_s,
period: goal.period, target_seconds: goal.target_seconds,
languages: goal.languages, projects: goal.projects,
notify_by_email: goal.notify_by_email, notify_by_slack: goal.notify_by_slack,
errors: goal.errors.full_messages }
end
end
50 changes: 50 additions & 0 deletions app/javascript/pages/Users/Settings/Goals.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { router } from "@inertiajs/svelte";
import { secondsToDisplay } from "../../../utils";
import Button from "../../../components/Button.svelte";
import CheckboxField from "../../../components/CheckboxField.svelte";
import Modal from "../../../components/Modal.svelte";
import MultiSelectCombobox from "../../../components/MultiSelectCombobox.svelte";
import Select from "../../../components/Select.svelte";
Expand Down Expand Up @@ -35,6 +36,7 @@
subheading,
programming_goals,
options,
notification_options,
errors,
goal_form,
}: GoalsPageProps = $props();
Expand All @@ -52,6 +54,8 @@
let selectedPeriod = $state<ProgrammingGoal["period"]>(defaultPeriod());
let selectedLanguages = $state<string[]>([]);
let selectedProjects = $state<string[]>([]);
let notifyByEmail = $state(false);
let notifyBySlack = $state(false);
let submitting = $state(false);

$effect(() => {
Expand All @@ -62,6 +66,8 @@
setFromSeconds(goal_form.target_seconds || 1800);
selectedLanguages = goal_form.languages || [];
selectedProjects = goal_form.projects || [];
notifyByEmail = goal_form.notify_by_email ?? false;
notifyBySlack = goal_form.notify_by_slack ?? false;
editingGoal =
goal_form.mode === "edit" && goal_form.goal_id
? ((programming_goals || []).find((g) => g.id === goal_form.goal_id) ??
Expand All @@ -83,6 +89,15 @@
return parts.join(" AND ") || "All programming activity";
}

function notificationSubtitle(goal: ProgrammingGoal) {
const channels = [];
if (goal.notify_by_email) channels.push("email");
if (goal.notify_by_slack) channels.push("Slack");
return channels.length > 0
? `Completion notification: ${channels.join(" and ")}`
: "Completion notifications off";
}

function setFromSeconds(seconds: number) {
targetUnit = seconds % 3600 === 0 ? "hours" : "minutes";
targetAmount = targetUnit === "hours" ? seconds / 3600 : seconds / 60;
Expand All @@ -94,6 +109,8 @@
setFromSeconds(options.goals.preset_target_seconds[0] || 1800);
selectedLanguages = [];
selectedProjects = [];
notifyByEmail = false;
notifyBySlack = false;
goalModalOpen = true;
}

Expand All @@ -103,6 +120,8 @@
setFromSeconds(goal.target_seconds);
selectedLanguages = [...goal.languages];
selectedProjects = [...goal.projects];
notifyByEmail = goal.notify_by_email;
notifyBySlack = goal.notify_by_slack;
goalModalOpen = true;
}

Expand Down Expand Up @@ -137,6 +156,8 @@
target_seconds: currentTargetSeconds,
languages: selectedLanguages,
projects: selectedProjects,
notify_by_email: notifyByEmail,
notify_by_slack: notifyBySlack,
},
};
if (editingGoal) {
Expand Down Expand Up @@ -195,6 +216,9 @@
<p class="mt-1 truncate text-xs text-muted">
{scopeSubtitle(goal)}
</p>
<p class="mt-1 text-xs text-muted">
{notificationSubtitle(goal)}
</p>
</div>
<div class="flex items-center gap-2">
<Button
Expand Down Expand Up @@ -318,6 +342,32 @@
/>
</div>

<fieldset class="space-y-3 rounded-md border border-surface-200 p-4">
<legend class="px-1 text-sm font-semibold text-surface-content">
Notify me when I reach this goal
</legend>
<CheckboxField
name="goal[notify_by_email]"
bind:checked={notifyByEmail}
label="Email"
description={notification_options.email_available
? "Send a completion email to your linked email address."
: "Link an email address before enabling email notifications."}
disabled={!notification_options.email_available}
includeHidden={false}
/>
<CheckboxField
name="goal[notify_by_slack]"
bind:checked={notifyBySlack}
label="Slack"
description={notification_options.slack_available
? "Send a direct message from the Sailor's Log app."
: "Connect your Slack account before enabling Slack notifications."}
disabled={!notification_options.slack_available}
includeHidden={false}
/>
</fieldset>

{#if modalErrors.length > 0}
<p
class="rounded-md border border-red/40 bg-red/10 px-3 py-2 text-xs text-red"
Expand Down
8 changes: 8 additions & 0 deletions app/javascript/pages/Users/Settings/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ export type ProgrammingGoal = {
target_seconds: number;
languages: string[];
projects: string[];
notify_by_email: boolean;
notify_by_slack: boolean;
};

type GoalForm = {
Expand All @@ -90,6 +92,8 @@ type GoalForm = {
target_seconds: number;
languages: string[];
projects: string[];
notify_by_email: boolean;
notify_by_slack: boolean;
errors: string[];
};

Expand Down Expand Up @@ -281,6 +285,10 @@ export type PrivacyPageProps = SettingsCommonProps & {
export type GoalsPageProps = SettingsCommonProps & {
programming_goals: ProgrammingGoal[];
options: GoalsOptionsProps;
notification_options: {
email_available: boolean;
slack_available: boolean;
};
goal_form?: GoalForm | null;
};

Expand Down
43 changes: 43 additions & 0 deletions app/jobs/goal_completion_check_job.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class GoalCompletionCheckJob < ApplicationJob
queue_as :latency_10s

include GoodJob::ActiveJobExtensions::Concurrency

def self.schedule_for(user_id)
goals = Goal.where(user_id: user_id)
return unless goals.where(notify_by_email: true).or(goals.where(notify_by_slack: true)).exists?

perform_later(user_id)
end

good_job_control_concurrency_with(
total_limit: 1, key: -> { "goal_completion_check_job_#{arguments.first}" }
)

Comment on lines +14 to +16

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Concurrency drops completion checks

If heartbeat processing overlaps for one user, the per-user total_limit discards later checks while the accepted check can run before the threshold-crossing heartbeat is visible, causing the completed goal to receive no notification until another heartbeat schedules a check.

Context Used: AGENTS.md (source)

Knowledge Base Used:

Prompt To Fix With AI
This is a comment left during a code review.
Path: app/jobs/goal_completion_check_job.rb
Line: 14-16

Comment:
**Concurrency drops completion checks**

If heartbeat processing overlaps for one user, the per-user `total_limit` discards later checks while the accepted check can run before the threshold-crossing heartbeat is visible, causing the completed goal to receive no notification until another heartbeat schedules a check.

**Context Used:** AGENTS.md ([source](https://github.com/hackclub/hackatime/blob/main/AGENTS.md))

**Knowledge Base Used:**
- [Background Jobs Infrastructure (GoodJob)](https://app.greptile.com/mahadk/-/custom-context/knowledge-base/hackclub/hackatime/-/docs/background-jobs-infra.md)
- [Heartbeat Ingest](https://app.greptile.com/mahadk/-/custom-context/knowledge-base/hackclub/hackatime/-/docs/heartbeat-ingest.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

def perform(user_id)
user = User.find_by(id: user_id)
return if user.nil? || user.pending_deletion?

goals = user.goals.where(notify_by_email: true).or(user.goals.where(notify_by_slack: true))
return if goals.empty?

ProgrammingGoalsProgressService.new(user: user, goals: goals).call.each do |progress|
next unless progress[:complete]

notification = GoalCompletionNotification.create_or_find_by!(
goal_id: progress[:id],
period: progress[:period],
period_started_at: Time.zone.parse(progress[:period_start])
) do |record|
record.target_seconds = progress[:target_seconds]
record.tracked_seconds = progress[:tracked_seconds]
record.languages = progress[:languages]
record.projects = progress[:projects]
end

goal = notification.goal
GoalCompletionEmailJob.perform_later(notification.id) if goal.notify_by_email? && notification.email_delivered_at.nil?
GoalCompletionSlackJob.perform_later(notification.id) if goal.notify_by_slack? && notification.slack_delivered_at.nil?
end
end
end
26 changes: 26 additions & 0 deletions app/jobs/goal_completion_email_job.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class GoalCompletionEmailJob < ApplicationJob
queue_as :latency_10s

include GoodJob::ActiveJobExtensions::Concurrency

good_job_control_concurrency_with(
total_limit: 1, key: -> { "goal_completion_email_job_#{arguments.first}" }
)

def perform(notification_id)
notification = GoalCompletionNotification.find(notification_id)
return if notification.email_delivered_at.present?

goal = notification.goal
return unless goal.notify_by_email?

user = goal.user
return if user.pending_deletion?

recipient_email = user.email_addresses.order(:id).pick(:email)
return if recipient_email.blank?

GoalCompletionMailer.reached(notification, recipient_email: recipient_email).deliver_now
notification.update!(email_delivered_at: Time.current)
Comment on lines +23 to +24

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Delivery state permits duplicates

When external delivery succeeds but the subsequent delivered_at update fails or the worker stops before it commits, a retry or later completion check sees a nil marker and sends the notification again, causing duplicate email; the Slack job has the same ordering problem.

Context Used: AGENTS.md (source)

Knowledge Base Used: Background Jobs Infrastructure (GoodJob)

Prompt To Fix With AI
This is a comment left during a code review.
Path: app/jobs/goal_completion_email_job.rb
Line: 23-24

Comment:
**Delivery state permits duplicates**

When external delivery succeeds but the subsequent `delivered_at` update fails or the worker stops before it commits, a retry or later completion check sees a nil marker and sends the notification again, causing duplicate email; the Slack job has the same ordering problem.

**Context Used:** AGENTS.md ([source](https://github.com/hackclub/hackatime/blob/main/AGENTS.md))

**Knowledge Base Used:** [Background Jobs Infrastructure (GoodJob)](https://app.greptile.com/mahadk/-/custom-context/knowledge-base/hackclub/hackatime/-/docs/background-jobs-infra.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

end
end
39 changes: 39 additions & 0 deletions app/jobs/goal_completion_slack_job.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class GoalCompletionSlackJob < ApplicationJob
queue_as :latency_10s

include GoodJob::ActiveJobExtensions::Concurrency

good_job_control_concurrency_with(
total_limit: 1, key: -> { "goal_completion_slack_job_#{arguments.first}" }
)

def perform(notification_id)
notification = GoalCompletionNotification.find(notification_id)
return if notification.slack_delivered_at.present?

goal = notification.goal
return unless goal.notify_by_slack?

user = goal.user
return if user.pending_deletion? || user.slack_uid.blank?

duration = ApplicationController.helpers.short_time_simple(notification.target_seconds)
scope = notification_scope(notification)
message = ":tada: You reached your #{notification.period} coding goal of *#{duration}*#{scope}!"
response = HTTP.auth("Bearer #{ENV['SAILORS_LOG_SLACK_BOT_OAUTH_TOKEN']}")
.post("https://slack.com/api/chat.postMessage", json: { channel: user.slack_uid, text: message })
data = JSON.parse(response.body)
raise "Failed to send goal completion Slack notification: #{data["error"]}" unless data["ok"]

notification.update!(slack_delivered_at: Time.current)
end

private

def notification_scope(notification)
filters = []
filters << "#{notification.languages.to_sentence} coding" if notification.languages.any?
filters << notification.projects.to_sentence if notification.projects.any?
filters.any? ? " for #{filters.join(" in ")}" : ""
end
end
16 changes: 16 additions & 0 deletions app/mailers/goal_completion_mailer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class GoalCompletionMailer < ApplicationMailer
helper :application

def reached(notification, recipient_email:)
@notification = notification
@user = notification.goal.user
@target_duration = ApplicationController.helpers.short_time_simple(notification.target_seconds)
@tracked_duration = ApplicationController.helpers.short_time_simple(notification.tracked_seconds)
@goals_url = my_settings_goals_url

mail(
to: recipient_email,
subject: "You reached your #{notification.period} Hackatime goal!"
)
end
end
5 changes: 4 additions & 1 deletion app/models/goal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class Goal < ApplicationRecord
MAX_GOALS = 5

belongs_to :user
has_many :completion_notifications, class_name: "GoalCompletionNotification", dependent: :destroy

before_validation :normalize_fields

Expand All @@ -30,7 +31,9 @@ def as_programming_goal_payload
period: period,
target_seconds: target_seconds,
languages: languages,
projects: projects
projects: projects,
notify_by_email: notify_by_email,
notify_by_slack: notify_by_slack
}
end

Expand Down
8 changes: 8 additions & 0 deletions app/models/goal_completion_notification.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class GoalCompletionNotification < ApplicationRecord
belongs_to :goal

validates :period, inclusion: { in: Goal::PERIODS }
validates :period_started_at, presence: true
validates :target_seconds, :tracked_seconds,
numericality: { only_integer: true, greater_than_or_equal_to: 0 }
end
2 changes: 2 additions & 0 deletions app/models/heartbeat.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ class Heartbeat < ApplicationRecord
before_save :set_fields_hash!
before_save :set_time_epoch!
after_commit :schedule_dashboard_rollup_refresh, on: %i[create update destroy]
after_commit :schedule_goal_completion_check, on: %i[create update]

include Heartbeatable
include TimeRangeFilterable
Expand Down Expand Up @@ -79,4 +80,5 @@ def set_time_epoch!
end

def schedule_dashboard_rollup_refresh = DashboardRollupRefreshJob.schedule_for(user_id)
def schedule_goal_completion_check = GoalCompletionCheckJob.schedule_for(user_id)
end
Loading