Skip to content

Commit

Permalink
Merge branch 'main' into 4773-reset-password-and-invitation-expiry
Browse files Browse the repository at this point in the history
  • Loading branch information
cielf authored Nov 29, 2024
2 parents 1539558 + c9fad26 commit 7de90b8
Show file tree
Hide file tree
Showing 39 changed files with 791 additions and 204 deletions.
3 changes: 2 additions & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,7 @@ PLATFORMS
arm64-darwin-21
arm64-darwin-22
arm64-darwin-23
arm64-darwin-24
x86_64-darwin-20
x86_64-darwin-21
x86_64-darwin-22
Expand Down Expand Up @@ -798,4 +799,4 @@ DEPENDENCIES
webmock (~> 3.24)

BUNDLED WITH
2.5.22
2.5.23
4 changes: 2 additions & 2 deletions app/controllers/distributions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def index
.distributions
.includes(:partner, :storage_location, line_items: [:item])
.order('issued_at DESC')
.apply_filters(filter_params, helpers.selected_range)
.apply_filters(filter_params.except(:date_range), helpers.selected_range)
@paginated_distributions = @distributions.page(params[:page])
@items = current_organization.items.alphabetized
@item_categories = current_organization.item_categories
Expand Down Expand Up @@ -310,7 +310,7 @@ def daily_items(pick_ups)
def filter_params
return {} unless params.key?(:filters)

params.require(:filters).permit(:by_item_id, :by_item_category_id, :by_partner, :by_state, :by_location)
params.require(:filters).permit(:by_item_id, :by_item_category_id, :by_partner, :by_state, :by_location, :date_range)
end

def perform_inventory_check
Expand Down
29 changes: 25 additions & 4 deletions app/controllers/profiles_controller.rb
Original file line number Diff line number Diff line change
@@ -1,20 +1,41 @@
class ProfilesController < ApplicationController
def edit
@partner = current_organization.partners.find(params[:id])

@counties = County.in_category_name_order
@client_share_total = @partner.profile.client_share_total

if Flipper.enabled?("partner_step_form")
@sections_with_errors = []
render "profiles/step/edit"
else
render "edit"
end
end

def update
@counties = County.in_category_name_order
@partner = current_organization.partners.find(params[:id])
result = PartnerProfileUpdateService.new(@partner, edit_partner_params, edit_profile_params).call
if result.success?
redirect_to partner_path(@partner) + "#partner-information", notice: "#{@partner.name} updated!"
flash[:success] = "Details were successfully updated."
if Flipper.enabled?("partner_step_form")
if params[:save_review]
redirect_to partner_path(@partner) + "#partner-information"
else
redirect_to edit_profile_path
end
else
redirect_to partner_path(@partner) + "#partner-information"
end
else
flash[:error] = "Something didn't work quite right -- try again? %s " % result.error
render action: :edit
flash.now[:error] = "There is a problem. Try again: %s " % result.error
if Flipper.enabled?("partner_step_form")
error_keys = @partner.profile.errors.attribute_names
@sections_with_errors = Partners::SectionErrorService.sections_with_errors(error_keys)
render "profiles/step/edit"
else
render :edit
end
end
end

Expand Down
2 changes: 1 addition & 1 deletion app/controllers/storage_locations_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def index
@items = StorageLocation.items_inventoried(current_organization, @inventory)
@include_inactive_storage_locations = params[:include_inactive_storage_locations].present?
@storage_locations = current_organization.storage_locations.alphabetized
if @inventory && filter_params[:containing].present?
if filter_params[:containing].present?
containing_ids = @inventory.storage_locations.keys.select do |sl|
@inventory.quantity_for(item_id: filter_params[:containing], storage_location: sl).positive?
end
Expand Down
14 changes: 13 additions & 1 deletion app/helpers/historical_trends_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,18 @@ module HistoricalTrendsHelper

def last_12_months
current_month = Time.zone.now.month
MONTHS.rotate(current_month)
current_year = Time.zone.now.year
last_year = current_year - 1
return_array = MONTHS.rotate(current_month)
return_array.each_with_index do |month, index|
# Last current_month entries are in the current year, earlier entries are
# in the previous year.
return_array[index] = if index >= (MONTHS.length - current_month)
"#{month} #{current_year}"
else
"#{month} #{last_year}"
end
end
return_array
end
end
24 changes: 24 additions & 0 deletions app/jobs/backup_db_rds.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# to be called from Clock
module BackupDbRds
def self.run
logger = Logger.new($stdout)
logger.info("Performing dump of the database.")

current_time = Time.current.strftime("%Y%m%d%H%M%S")

logger.info("Copying the database...")
backup_filename = "#{current_time}.rds.dump"
system("PGPASSWORD='#{ENV["DIAPER_DB_PASSWORD"]}' pg_dump -Fc -v --host=#{ENV["DIAPER_DB_HOST"]} --username=#{ENV["DIAPER_DB_USERNAME"]} --dbname=#{ENV["DIAPER_DB_DATABASE"]} -f #{backup_filename}")

account_name = ENV["AZURE_STORAGE_ACCOUNT_NAME"]
account_key = ENV["AZURE_STORAGE_ACCESS_KEY"]

blob_client = Azure::Storage::Blob::BlobService.create(
storage_account_name: account_name,
storage_access_key: account_key
)

logger.info("Uploading #{backup_filename}")
blob_client.create_block_blob("backups", backup_filename, File.read(backup_filename))
end
end
1 change: 1 addition & 0 deletions app/jobs/reminder_deadline_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class ReminderDeadlineJob < ApplicationJob

def perform
remind_these_partners = Partners::FetchPartnersToRemindNowService.new.fetch
Rails.logger.info("Partners to remind: #{remind_these_partners.map(&:id)}")

remind_these_partners.each do |partner|
ReminderDeadlineMailer.notify_deadline(partner).deliver_later
Expand Down
10 changes: 10 additions & 0 deletions app/models/partners/item_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,15 @@ def request_unit_is_supported
errors.add(:request_unit, "is not supported")
end
end

def name_with_unit(quantity_override = nil)
if item
if Flipper.enabled?(:enable_packs) && request_unit.present?
"#{name} - #{request_unit.pluralize(quantity_override || quantity.to_i)}"
else
name
end
end
end
end
end
2 changes: 1 addition & 1 deletion app/queries/low_inventory_query.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class LowInventoryQuery
def self.call(organization)
inventory = View::Inventory.new(organization.id)
items = inventory.all_items
items = inventory.all_items.uniq(&:item_id)

low_inventory_items = []
items.each do |item|
Expand Down
56 changes: 28 additions & 28 deletions app/services/exports/export_request_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ class ExportRequestService
DELETED_ITEMS_COLUMN_HEADER = '<DELETED_ITEMS>'.freeze

def initialize(requests)
@requests = requests.includes(:partner)
@requests = requests.includes(:partner, {item_requests: :item})
end

def generate_csv
Expand Down Expand Up @@ -61,7 +61,25 @@ def item_headers
end

def compute_item_headers
item_names = items.pluck(:name)
# This reaches into the item, handling invalid deleted items
item_names = Set.new
all_item_requests.each do |item_request|
if item_request.item
item = item_request.item
item_names << item.name
if Flipper.enabled?(:enable_packs)
item.request_units.each do |unit|
item_names << "#{item.name} - #{unit.name.pluralize}"
end

# It's possible that the unit is no longer valid, so we'd
# add that individually
if item_request.request_unit.present?
item_names << "#{item.name} - #{item_request.request_unit.pluralize}"
end
end
end
end

# Adding this to handle cases in which a requested item
# has been deleted. Normally this wouldn't be neccessary,
Expand All @@ -75,38 +93,20 @@ def build_row_data(request)

row += Array.new(item_headers.size, 0)

request.request_items.each do |request_item|
item_name = fetch_item_name(request_item['item_id']) || DELETED_ITEMS_COLUMN_HEADER
request.item_requests.each do |item_request|
item_name = item_request.name_with_unit(0) || DELETED_ITEMS_COLUMN_HEADER
item_column_idx = headers_with_indexes[item_name]

if item_name == DELETED_ITEMS_COLUMN_HEADER
# Add to the deleted column for every item that
# does not match any existing Item.
row[item_column_idx] ||= 0
end
row[item_column_idx] += request_item['quantity']
row[item_column_idx] ||= 0
row[item_column_idx] += item_request.quantity.to_i
end

row
end

def fetch_item_name(item_id)
@item_name_to_id_map ||= items.inject({}) do |acc, item|
acc[item.id] = item.name
acc
end

@item_name_to_id_map[item_id]
end

def items
return @items if @items

item_ids = requests.flat_map do |request|
request.request_items.map { |item| item['item_id'] }
end

@items ||= Item.where(id: item_ids)
def all_item_requests
return @all_item_requests if @all_item_requests
@all_item_requests ||= Partners::ItemRequest.where(request: requests).includes(item: :request_units)
@all_item_requests
end
end
end
40 changes: 25 additions & 15 deletions app/services/historical_trend_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,36 @@ def initialize(organization_id, type)
@type = type
end

# Returns: [{:name=>"Adult Briefs (XXL)", :data=>[0, 0, 0, 0, 0, 0, 0, 0, 0, 416, 0, 0], :visible=>false}]
# :data contains quantity from 11 months ago to current month
def series
# Preload line_items with a single query to avoid N+1 queries.
items_with_line_items = @organization.items.active
.includes(:line_items)
.where(line_items: {itemizable_type: @type, created_at: 1.year.ago.beginning_of_month..Time.current})
.order(:name)
type_symbol = @type.tableize.to_sym # :distributions, :donations, :purchases
records_for_type = @organization.send(type_symbol)
.includes(items: :line_items)
.where(issued_at: 1.year.ago.beginning_of_month..Time.current)

month_offset = [*1..12].rotate(Time.zone.today.month)
default_dates = (1..12).index_with { |i| 0 }
array_of_items = []

items_with_line_items.each_with_object([]) do |item, array_of_items|
dates = default_dates.deep_dup
records_for_type.each do |record|
index = record.issued_at.month - Date.current.month - 1

item.line_items.each do |line_item|
month = line_item.created_at.month
index = month_offset.index(month) + 1
dates[index] = dates[index] + line_item.quantity
end
record.line_items.each do |line_item|
name = line_item.item.name
quantity = line_item.quantity
next if quantity.zero?

array_of_items << {name: item.name, data: dates.values, visible: false} unless dates.values.sum.zero?
existing_item = array_of_items.find { |item| item[:name] == name }
if existing_item
quantity_per_month = existing_item[:data]
quantity_per_month[index] += quantity
else
quantity_per_month = Array.new(12, 0)
quantity_per_month[index] += quantity
array_of_items << {name:, data: quantity_per_month, visible: false}
end
end
end

array_of_items.sort_by { |item| item[:name] }
end
end
34 changes: 7 additions & 27 deletions app/services/requests_total_items_service.rb
Original file line number Diff line number Diff line change
@@ -1,44 +1,24 @@
class RequestsTotalItemsService
def initialize(requests:)
@requests = requests
@requests = requests.includes(item_requests: {item: :request_units})
end

def calculate
return unless requests

request_items_array = []

request_items.each do |items|
items.each do |json|
request_items_array << [item_name(json['item_id']), json['quantity']]
end
totals = Hash.new(0)
item_requests.each do |item_request|
totals[item_request.name_with_unit] += item_request.quantity.to_i
end

request_items_array.inject({}) do |item, (quantity, total)|
item[quantity] ||= 0
item[quantity] += total.to_i
item
end
totals
end

private

attr_accessor :requests

def request_items
@request_items ||= requests.pluck(:request_items)
end

def request_items_ids
request_items.flat_map { |jitem| jitem.map { |item| item["item_id"] } }
end

def items_names
@items_names ||= Item.where(id: request_items_ids).as_json(only: [:id, :name])
end

def item_name(id)
item_found = items_names.find { |item| item["id"] == id }
item_found&.fetch('name') || '*Unknown Item*'
def item_requests
@item_requests ||= requests.flat_map(&:item_requests)
end
end
2 changes: 1 addition & 1 deletion app/views/audits/_form.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
</div>
<div class="row links">
<div class="col-xs-12 p-3">
<%= add_element_button "Add Another Item", container_selector: "#audit_line_items" do %>
<%= add_element_button "Add Another Item", container_selector: "#audit_line_items", id: "__add_line_item" do %>
<%= render 'line_items/line_item_fields', form: f, object: LineItem.new %>
<% end %>
</div>
Expand Down
8 changes: 3 additions & 5 deletions app/views/kits/_form.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,9 @@
<%= render 'line_items/line_item_fields', form: f %>
</div>
<div class="row links col-xs-12 justify-content-end">
<div class="col-xs-12">
<%= add_element_button "Add Another Item", container_selector: "#kit_line_items" do %>
<%= render 'line_items/line_item_fields', form: f, object: LineItem.new %>
<% end %>
</div>
<%= add_element_button "Add Another Item", container_selector: "#kit_line_items", id: "__add_line_item" do %>
<%= render 'line_items/line_item_fields', form: f, object: LineItem.new %>
<% end %>
</div>
</fieldset>

Expand Down
1 change: 1 addition & 0 deletions app/views/kits/new.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@
</section>

<%= render 'form' %>
<%= render partial: "barcode_items/barcode_modal" %>
2 changes: 1 addition & 1 deletion app/views/partner_mailer/application_approved.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<p>Hi <%= @partner.name %></p>

<p>
<%= @organization.name %> has approved your application.
You have been approved to make requests for essentials to <%= @organization.name %>.
<br>
<%= link_to "Check out your dashboard", partners_dashboard_url %>
</p>
Expand Down
2 changes: 1 addition & 1 deletion app/views/partner_mailer/application_approved.text.erb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Hi <%= @partner.name %>

<%= @organization.name %> has approved your application.
You have been approved to make requests for essentials to <%= @organization.name %>.

Check out your dashboard: <%= partners_dashboard_url %>
Loading

0 comments on commit 7de90b8

Please sign in to comment.