Skip to content

Commit

Permalink
Refactoring and changed set and show space to MB
Browse files Browse the repository at this point in the history
  • Loading branch information
Adrian Herrmann committed Jan 22, 2025
1 parent 8d6f98f commit 457f2cf
Show file tree
Hide file tree
Showing 11 changed files with 98 additions and 125 deletions.
12 changes: 6 additions & 6 deletions app/api/chemotion/admin_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,18 @@ class AdminAPI < Grape::API

namespace :usersDefault do
get do
default = User.find(1).available_space # first admin
{ users_available: default }
default = Admin.first.available_space / 1024 / 1024
{ available_user_space: default }
end
put do
params do
require :usersAvailable, type: Integer, desc: 'users default available space'
require :availableUserSpace, type: Integer, desc: 'users default available space'
end
User.find_each do |user|
user.available_space = if user.id == 1 # first admin
params[:usersAvailable]
user.available_space = if user.id == Admin.first.id
params[:availableUserSpace]
else
[user.available_space, params[:usersAvailable].to_i].max
[user.available_space, params[:availableUserSpace].to_i].max
end
user.save!
end
Expand Down
20 changes: 10 additions & 10 deletions app/javascript/src/apps/admin/AdminDashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ export default class AdminDashboard extends React.Component {
this.state = {
diskAvailable: 0,
diskPercentUsed: 0,
usersAvailable: 0,
availableUserSpace: 0,
showDiskInfo: false,
};
this.handleDiskspace = this.handleDiskspace.bind(this);
this.getUsersAvailable = this.getUsersAvailable.bind(this);
this.getAvailableUserSpace = this.getAvailableUserSpace.bind(this);
this.handleChange = this.handleChange.bind(this);
}

componentDidMount() {
this.handleDiskspace();
this.getUsersAvailable();
this.getAvailableUserSpace();
}

handleDiskspace() {
Expand All @@ -34,20 +34,20 @@ export default class AdminDashboard extends React.Component {

// eslint-disable-next-line class-methods-use-this
handleChange(event) {
AdminFetcher.setUsersAvailable(event.target.value);
AdminFetcher.setAvailableUserSpace(event.target.value * 1024 * 1024);
}

getUsersAvailable() {
AdminFetcher.getUsersAvailable()
getAvailableUserSpace() {
AdminFetcher.getAvailableUserSpace()
.then((result) => {
this.setState({
usersAvailable: result.users_available,
availableUserSpace: result.available_user_space,
});
});
}

renderDiskInfo() {
const { diskAvailable, diskPercentUsed, usersAvailable } = this.state;
const { diskAvailable, diskPercentUsed, availableUserSpace } = this.state;
const className = diskPercentUsed > 80 ? 'text-danger' : '';

return (
Expand All @@ -67,11 +67,11 @@ export default class AdminDashboard extends React.Component {
defaultValue={`${diskPercentUsed}%` || ''}
readOnly
/>
<InputGroup.Text>Default User Available (B)</InputGroup.Text>
<InputGroup.Text>Default User Available Space (MB)</InputGroup.Text>
<Form.Control
type="number"
min="0"
defaultValue={usersAvailable || ''}
defaultValue={availableUserSpace || ''}
onChange={this.handleChange}
/>
</InputGroup>
Expand Down
10 changes: 5 additions & 5 deletions app/javascript/src/apps/admin/UserManagement.js
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ export default class UserManagement extends React.Component {
last_name: this.u_lastname.value.trim(),
name_abbreviation: this.u_abbr.value.trim(),
type: this.u_type.value,
available_space: this.u_avail.value === '' ? 0 : this.u_avail.value
available_space: this.u_avail.value === '' ? 0 : this.u_avail.value * 1024 * 1024
})
.then((result) => {
if (result.error) {
Expand Down Expand Up @@ -445,7 +445,7 @@ export default class UserManagement extends React.Component {
if (this.u_type.value === 'Group') { // update available space for all users of group
AdminFetcher.updateUsersOfGroup({
id: user.id,
available_space: this.u_avail.value === '' ? 0 : this.u_avail.value
available_space: this.u_avail.value === '' ? 0 : this.u_avail.value * 1024 * 1024
})
.then((result) => JSON.parse(result))
.then((json) => {
Expand Down Expand Up @@ -1038,14 +1038,14 @@ export default class UserManagement extends React.Component {
</Form.Group>
<Form.Group as={Row} className="mb-3 ms-5" controlId="formControlAvail">
<Form.Label column sm="3" className="fs-6">
Available Space:
Available Space (MB):
</Form.Label>
<Col sm="7">
<Form.Control
type="number"
min="1"
name="u_avail"
defaultValue={user.available_space === 0 ? '' : user.available_space}
defaultValue={user.available_space === 0 ? '' : user.available_space / 1024 / 1024}
ref={(ref) => { this.u_avail = ref; }}
className="fs-6"
/>
Expand Down Expand Up @@ -1523,7 +1523,7 @@ export default class UserManagement extends React.Component {
</td>
<td className="col-md-2 py-3">
{g.available_space === 0 ? ''
: `${Math.round((g.used_space / g.available_space) * 100)}% of ${g.available_space}B`}
: `${Math.round((g.used_space / g.available_space) * 100)}% of ${g.available_space / 1024 / 1024}MB`}
</td>
<td className="col-md-2 py-3">
{g.current_sign_in_at}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class ResearchPlanDetailsAttachments extends Component {
this.confirmAttachmentImport = this.confirmAttachmentImport.bind(this);
this.showImportConfirm = this.showImportConfirm.bind(this);
this.hideImportConfirm = this.hideImportConfirm.bind(this);
this.checkUserQuota = this.checkUserQuota.bind(this);
this.isUserQuotaExceeded = this.isUserQuotaExceeded.bind(this);
}

componentDidMount() {
Expand Down Expand Up @@ -220,12 +220,13 @@ class ResearchPlanDetailsAttachments extends Component {
this.hideImportConfirm(attachment.id);
}

checkUserQuota() {
isUserQuotaExceeded() {
const { filteredAttachments } = this.state;
const totalSize = filteredAttachments.filter((attachment) => attachment.is_new && !attachment.is_deleted)
.reduce((acc, attachment) => acc + attachment.filesize, 0);
const { currentUser } = UserStore.getState();
return currentUser.available_space !== 0 && totalSize > (currentUser.available_space - currentUser.used_space);
return currentUser !== null && currentUser.available_space !== 0
&& totalSize > (currentUser.available_space - currentUser.used_space);
}

renderImageEditModal() {
Expand Down Expand Up @@ -368,7 +369,7 @@ class ResearchPlanDetailsAttachments extends Component {
)}
</div>
))}
<Alert variant="warning" show={this.checkUserQuota()}>
<Alert variant="warning" show={this.isUserQuotaExceeded()}>
Uploading attachments will fail; User quota will be exceeded.
</Alert>
</>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class ContainerDatasetModalContent extends Component {
this.handleAttachmentRemove = this.handleAttachmentRemove.bind(this);
this.handleAttachmentBackToInbox = this.handleAttachmentBackToInbox.bind(this);
this.classifyAttachments = this.classifyAttachments.bind(this);
this.checkUserQuota = this.checkUserQuota.bind(this);
this.isUserQuotaExceeded = this.isUserQuotaExceeded.bind(this);
this.state.attachmentGroups = this.classifyAttachments(props.datasetContainer.attachments);
}

Expand Down Expand Up @@ -468,7 +468,7 @@ export class ContainerDatasetModalContent extends Component {
);
}

checkUserQuota() {
isUserQuotaExceeded() {
const { filteredAttachments } = this.state;
const totalSize = filteredAttachments.filter((attachment) => attachment.is_new === true && !attachment.is_deleted)
.reduce((acc, attachment) => acc + attachment.filesize, 0);
Expand Down Expand Up @@ -649,7 +649,7 @@ export class ContainerDatasetModalContent extends Component {
&& renderGroup(attachmentGroups.Processed[groupName], `Processed: ${groupName}`, groupName))}
{attachmentGroups.Combined.length > 0 && renderGroup(attachmentGroups.Combined, 'Combined')}
</div>
<Alert variant="warning" show={this.checkUserQuota()}>
<Alert variant="warning" show={this.isUserQuotaExceeded()}>
Uploading attachments will fail; User quota will be exceeded.
</Alert>
</>
Expand Down
6 changes: 3 additions & 3 deletions app/javascript/src/fetchers/AdminFetcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default class AdminFetcher {
});
}

static getUsersAvailable() {
static getAvailableUserSpace() {
return fetch('/api/v1/admin/usersDefault', {
credentials: 'same-origin',
})
Expand All @@ -35,15 +35,15 @@ export default class AdminFetcher {
});
}

static setUsersAvailable(usersAvailable) {
static setAvailableUserSpace(availableUserSpace) {
return fetch('/api/v1/admin/usersDefault', {
credentials: 'same-origin',
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ usersAvailable }),
body: JSON.stringify({ availableUserSpace }),
});
}

Expand Down
4 changes: 2 additions & 2 deletions app/models/attachment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def delete_file_and_thumbnail
attachment_attacher.destroy
end

def check_user_quota
def user_quota_exceeded?
user = User.find(created_for.nil? ? created_by : created_for)
if (user.used_space + attachment_data['metadata']['size']) > user.available_space &&
!user.available_space.zero?
Expand All @@ -296,7 +296,7 @@ def attach_file
attachment_attacher.attach(File.open(file_path, binmode: true))
raise 'File to large' unless valid?

raise 'User quota exceeded' unless check_user_quota
raise 'User quota exceeded' unless user_quota_exceeded?

attachment_attacher.create_derivatives

Expand Down
8 changes: 4 additions & 4 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ def current_affiliations
'INNER JOIN user_affiliations ua ON ua.affiliation_id = affiliations.id',
).where(
'(ua.user_id = ?) and (ua.deleted_at ISNULL) and (ua.to ISNULL or ua.to > ?)',
id, Time.now
id, Time.zone.now
).order('ua.from DESC')
end

Expand Down Expand Up @@ -345,7 +345,7 @@ def update_matrix
sql = ApplicationRecord.send(:sanitize_sql_array, ['select generate_users_matrix(array[?])', id])
ApplicationRecord.connection.exec_query(sql)
end
rescue StandardError => e
rescue StandardError
log_error 'Error on update_matrix'
end

Expand All @@ -370,7 +370,7 @@ def self.gen_matrix(user_ids = nil)
end
ApplicationRecord.connection.exec_query(sql)
end
rescue StandardError => e
rescue StandardError
log_error 'Error on update_matrix'
end

Expand Down Expand Up @@ -447,7 +447,7 @@ def send_welcome_email
end

def set_default_avail_space
self.available_space = Admin.find(1).available_space # first admin
self.available_space = Admin.first.nil? ? 0 : Admin.first.available_space
save!
end

Expand Down
49 changes: 12 additions & 37 deletions db/functions/calculate_collection_space_v01.sql
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,17 @@ returns bigint
language plpgsql
as $function$
declare
used_space_samples bigint default 0;
used_space_reactions bigint default 0;
used_space_wellplates bigint default 0;
used_space_screens bigint default 0;
used_space_research_plans bigint default 0;
used_space bigint default 0;
element_types text[] := array['Sample', 'Reaction', 'Wellplate', 'Screen', 'ResearchPlan'];
element_table text;
element_space bigint;
begin
select sum(calculate_element_space(sample_id, 'Sample')) into used_space_samples
from collections_samples
where collection_id = collectionId;

used_space = COALESCE(used_space_samples,0);

select sum(calculate_element_space(reaction_id, 'Reaction')) into used_space_reactions
from collections_reactions
where collection_id = collectionId;

used_space = used_space + COALESCE(used_space_reactions,0);

select sum(calculate_element_space(wellplate_id, 'Wellplate')) into used_space_wellplates
from collections_wellplates
where collection_id = collectionId;

used_space = used_space + COALESCE(used_space_wellplates,0);

select sum(calculate_element_space(screen_id, 'Screen')) into used_space_screens
from collections_screens
where collection_id = collectionId;

used_space = used_space + COALESCE(used_space_screens,0);

select sum(calculate_element_space(research_plan_id, 'ResearchPlan')) into used_space_research_plans
from collections_research_plans
where collection_id = collectionId;

used_space = used_space + COALESCE(used_space_research_plans,0);

return COALESCE(used_space,0);
end;$function$;
foreach element_table in array element_types loop
execute format('select sum(calculate_element_space(id, $1)) from collections_%s where collection_id = $2', lower(element_table))
into element_space
using element_table, collectionId;
used_space := used_space + coalesce(element_space, 0);
end loop;
return coalesce(used_space, 0);
end;
$function$;
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ class SeedReportTemplates < ActiveRecord::Migration[4.2]
def change
ReportTemplate.reset_column_information
Attachment.reset_column_information
User.reset_column_information
seed_path = Rails.root.join('db', 'seeds', 'shared', 'report_templates.seed.rb')
load(seed_path) if File.exist?(seed_path)
end
end

Loading

0 comments on commit 457f2cf

Please sign in to comment.