Skip to content

Commit

Permalink
c and u form conversion
Browse files Browse the repository at this point in the history
Adding test cases and code refactoing

lint error correction

lint error correction
  • Loading branch information
anu-jose-ibm committed Sep 11, 2023
1 parent e7ecd42 commit 2751540
Show file tree
Hide file tree
Showing 9 changed files with 211 additions and 24 deletions.
4 changes: 2 additions & 2 deletions app/controllers/ops_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ def explorer
edit_changed?
end
# do not show buttons, when settings_workers - it uses react form buttons
if @sb[:active_tab] == "settings_workers"
if ["settings_workers", "diagnostics_cu_repair"].include?(@sb[:active_tab])
@x_edit_buttons_locals = nil
end
render :layout => "application"
Expand Down Expand Up @@ -803,7 +803,7 @@ def handle_bottom_cell(nodetype, presenter, locals)
else
presenter.hide(:paging_div).hide(:form_buttons_div)
end
if @sb[:active_tab] == "settings_workers"
if ["settings_workers", "diagnostics_cu_repair"].include?(@sb[:active_tab])
presenter.hide(:form_buttons_div)
end
end
Expand Down
28 changes: 6 additions & 22 deletions app/controllers/ops_controller/diagnostics.rb
Original file line number Diff line number Diff line change
Expand Up @@ -239,38 +239,22 @@ def cu_repair_field_changed
def cu_repair
assert_privileges("ops_diagnostics")

return unless load_edit("curepair_edit__new", "replace_cell__explorer")

if @edit[:new][:end_date].to_time < @edit[:new][:start_date].to_time
add_flash(_("End Date cannot be earlier than Start Date"), :error)
if params[:end_date].to_time < params[:start_date].to_time
render :json => {:status => :error, :message => _("End Date cannot be earlier than Start Date")}
else
# converting string to time, and then converting into user selected timezone
from = "#{@edit[:new][:start_date]} #{@edit[:new][:start_hour]}:#{@edit[:new][:start_min]}:00".to_time.in_time_zone(@edit[:new][:timezone])
to = "#{@edit[:new][:end_date]} #{@edit[:new][:end_hour]}:#{@edit[:new][:end_min]}:00".to_time.in_time_zone(@edit[:new][:timezone])
from = "#{params[:start_date]} #{params[:start_hour]}:#{params[:start_min]}:00".to_time.in_time_zone(params[:timezone])
to = "#{params[:end_date]} #{params[:end_hour]}:#{params[:end_min]}:00".to_time.in_time_zone(params[:timezone])
selected_zone = Zone.find(x_node.split('-').last)
begin
Metric::Capture.perf_capture_gap_queue(from, to, selected_zone)
rescue => bang
# Push msg and error flag
add_flash(_("Error during 'C & U Gap Collection': %{message}") % {:message => bang.message}, :error)
render :json => {:status => :error, :message => _("Error during 'C & U Gap Collection': %{message}") % {:message => bang.message}}
else
@edit[:new][:start_date] = @edit[:new][:end_date] = ""
add_flash(_("C & U Gap Collection successfully initiated"))
render :json => {:status => :success, :message => _("C & U Gap Collection successfully initiated")}
end
end

render :update do |page|
page << javascript_prologue
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
page << "miqScrollTop();" if @flash_array.present?
page.replace_html("diagnostics_cu_repair", :partial => "diagnostics_cu_repair_tab")
page << "ManageIQ.calendar.calDateFrom = null;"
page << "ManageIQ.calendar.calDateTo = new Date();"
page << "miqBuildCalendar();"
page << "miqSparkle(false);"
# disable button
page << javascript_for_miq_button_visibility(false)
end
end

def log_collection_form_fields
Expand Down
8 changes: 8 additions & 0 deletions app/javascript/components/c-and-u-collections-form/helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/** Function to append 0 to beginning of a number if it is a single digit. */
const padStart = (number) => String(number).padStart(2, '0');

/** This function format the date. */
export const formatDate = (date) => {
const newDate = new Date(date[0]);
return `${padStart(newDate.getMonth() + 1)}/${padStart(newDate.getDate())}/${newDate.getFullYear()}`;
};
66 changes: 66 additions & 0 deletions app/javascript/components/c-and-u-collections-form/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import React, { useState, useEffect } from 'react';
import MiqFormRenderer from '@@ddf';
import createSchema from './schema';
import NotificationMessage from '../notification-message';
import { timeZoneData } from '../schedule-form/helper';
import { formatDate } from './helper';

const DiagnosticsCURepairForm = () => {
const [data, setData] = useState({
isLoading: true,
timezones: undefined,
response: undefined,
});

useEffect(() => {
API.get('/api').then(({ timezones }) => {
setData({
...data,
isLoading: false,
timezones: timeZoneData(timezones),
});
});
}, []);

const onSubmit = (values) => {
const paramsData = {
timezone: values.timezone,
start_date: formatDate(values.startDate),
end_date: formatDate(values.endDate),
};
http.post(`/ops/cu_repair?button=submit`, paramsData, { skipErrors: [400, 500] })
.then(({ status, message }) => {
setData({
...data,
isLoading: true,
response: { status, message },
});
setTimeout(() => {
setData({
...data,
response: undefined,
isLoading: false,
});
}, 1000);
});
};

const renderMessage = ({ status, message }) => <NotificationMessage type={status} message={message} />;

return (
<>
{ data.response && renderMessage(data.response) }
{ !data.isLoading && (
<MiqFormRenderer
schema={createSchema(data.timezones)}
onSubmit={onSubmit}
/>
)}
{
`${__('Note')} : ${__('Gap Collection is only available for VMware vSphere Infrastructures')}`
}
</>
);
};

export default DiagnosticsCURepairForm;
36 changes: 36 additions & 0 deletions app/javascript/components/c-and-u-collections-form/schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { componentTypes, validatorTypes } from '@@ddf';

const createSchema = (timezones) => ({
title: __('Collection Options'),
fields: [
{
component: componentTypes.SELECT,
id: 'timezone',
name: 'timezone',
label: __('Timezone'),
initialValue: 'UTC',
validate: [{ type: validatorTypes.REQUIRED }],
isRequired: true,
includeEmpty: true,
options: timezones,
},
{
component: 'date-picker',
id: 'startDate',
name: 'startDate',
label: __('Start Date'),
validate: [{ type: validatorTypes.REQUIRED }],
isRequired: true,
},
{
component: 'date-picker',
id: 'endDate',
name: 'endDate',
label: __('End Date'),
validate: [{ type: validatorTypes.REQUIRED }],
isRequired: true,
},
],
});

export default createSchema;
2 changes: 2 additions & 0 deletions app/javascript/packs/component-definitions-common.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ import StorageServiceForm from '../components/storage-service-form';
import VolumeMappingForm from '../components/volume-mapping-form';
import ZoneForm from '../components/zone-form';
import AnsiblePlayBookEditCatalogForm from '../components/ansible-playbook-edit-catalog-form';
import DiagnosticsCURepairForm from '../components/c-and-u-collections-form';

/**
* Add component definitions to this file.
Expand Down Expand Up @@ -331,3 +332,4 @@ ManageIQ.component.addReact('VolumeMappingForm', VolumeMappingForm);
ManageIQ.component.addReact('VmCommonRenameForm', VmCommonRenameForm);
ManageIQ.component.addReact('ZoneForm', ZoneForm);
ManageIQ.component.addReact('AnsiblePlayBookEditCatalogForm', AnsiblePlayBookEditCatalogForm);
ManageIQ.component.addReact('DiagnosticsCURepairForm', DiagnosticsCURepairForm);
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`DiagnosticsCURepairForm Component Should add a record from DiagnosticsCURepair form 1`] = `
<Provider
store={
Object {
"asyncReducers": Object {
"FormButtons": [Function],
"notificationReducer": [Function],
},
"dispatch": [Function],
"getState": [Function],
"injectReducers": [Function],
"replaceReducer": [Function],
"subscribe": [Function],
Symbol(observable): [Function],
}
}
>
<DiagnosticsCURepairForm>
Note : Gap Collection is only available for VMware vSphere Infrastructures
</DiagnosticsCURepairForm>
</Provider>
`;

exports[`DiagnosticsCURepairForm Component Should render a new DiagnosticsCURepair form 1`] = `
<Provider
store={
Object {
"asyncReducers": Object {
"FormButtons": [Function],
"notificationReducer": [Function],
},
"dispatch": [Function],
"getState": [Function],
"injectReducers": [Function],
"replaceReducer": [Function],
"subscribe": [Function],
Symbol(observable): [Function],
}
}
>
<DiagnosticsCURepairForm>
Note : Gap Collection is only available for VMware vSphere Infrastructures
</DiagnosticsCURepairForm>
</Provider>
`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import React from 'react';
import toJson from 'enzyme-to-json';
import fetchMock from 'fetch-mock';
import { act } from 'react-dom/test-utils';

import { mount } from '../helpers/mountForm';
import DiagnosticsCURepairForm from '../../components/c-and-u-collections-form';
import { formatDate } from '../../components/c-and-u-collections-form/helper';

describe('DiagnosticsCURepairForm Component', () => {
afterEach(() => {
fetchMock.reset();
fetchMock.restore();
});
it('Should render a new DiagnosticsCURepair form', async() => {
let wrapper;
await act(async() => {
wrapper = mount(<DiagnosticsCURepairForm />);
});
wrapper.update();
expect(toJson(wrapper)).toMatchSnapshot();
});

it('Should add a record from DiagnosticsCURepair form', async(done) => {
const paramsData = {
timezone: 'UTC',
start_date: formatDate('12/12/2023'),
end_date: formatDate('12/01/2023'),
};
const timezones = [
{ name: 'International Date Line West', description: '(GMT-12:00) International Date Line West' },
{ name: 'American Samoa', description: '(GMT-11:00) American Samoa' },
{ name: 'Midway Island', description: '(GMT-11:00) Midway Island' },
{ name: 'Hawaii', description: '(GMT-10:00) Hawaii' },
{ name: 'Alaska', description: '(GMT-09:00) Alaska' },
];
fetchMock.getOnce('/api', { timezones });
fetchMock.postOnce('/api/instances/1850//ops/cu_repair?button=submit/', paramsData);
const wrapper = mount(<DiagnosticsCURepairForm />);
expect(toJson(wrapper)).toMatchSnapshot();
done();
});
});
1 change: 1 addition & 0 deletions app/views/ops/_diagnostics_cu_repair_tab.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<%= react('DiagnosticsCURepairForm') =%>

0 comments on commit 2751540

Please sign in to comment.