lodash#uniqBy JavaScript Examples
The following examples show how to use
lodash#uniqBy.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* 新增一个历史记录
* @param {object} tab - tab 信息
*/
addHistory(tab) {
const { history = [] } = this.state;
const newHistory = uniqBy([tab, ...history], (t) => t.key);
if (newHistory.length > 8) {
newHistory.pop();
}
storeHistory(history);
this.setState({
history: newHistory,
});
}
Example #2
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* setTableRowForms - 设置行缓存
* @param {!object} node - 表格行this对象
* @param {object} record - 行数据
*/
@Bind()
setTableRowForms(node, record) {
if (isEmpty(this.tableRowForms)) {
this.tableRowForms = []; // new Map();
}
// this.tableRowForms = this.tableRowForms.set(record.key, node);
this.tableRowForms = uniqBy(
this.tableRowForms.concat({ key: record.key, row: node.props.form }),
'key'
);
}
Example #3
Source File: Company.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* 设置选中
* @param {Array} rows 选中的行
*/
@Bind()
setSelectRows(rows) {
this.setState({
checkedList: uniqBy(rows, 'id'),
});
}
Example #4
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
@Bind()
add() {
const { menuDataSource = {} } = this.props;
const { tableDataSource = [], editingRows } = this.state;
const item = {
_status: 'create',
key: uuidv4(),
type: 'ps',
level: menuDataSource.level,
enabledFlag: 1,
newSubnodeFlag: 1,
editDetailFlag: 1,
parentId: menuDataSource.id,
};
this.setState({
editingRows: uniqBy(editingRows.concat(item), 'key'),
tableDataSource: [item].concat(tableDataSource),
});
}
Example #5
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
onPermissionsModalOk(selectedRows) {
// const { dispatch } = this.props;
const { dataSource } = this.state;
this.setState({
dataSource: {
...dataSource,
permissions: uniqBy(dataSource.permissions.concat(selectedRows), 'id'),
},
});
this.setState({
permissionsModalVisible: false,
permissionsModalDataSource: [],
permissionsModalPagination: {},
});
}
Example #6
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
onPermissionsModalOk(selectedRows) {
// const { dispatch } = this.props;
const { dataSource } = this.state;
this.setState({
dataSource: {
...dataSource,
permissions: uniqBy(dataSource.permissions.concat(selectedRows), 'id'),
},
});
this.setState({
permissionsModalVisible: false,
permissionsModalDataSource: [],
permissionsModalPagination: {},
});
}
Example #7
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
addPermissions() {
const { handleQueryPermissions = (e) => e } = this.props;
const { getFieldsValue = (e) => e } = this.editForm;
const { level } = getFieldsValue();
if (!isEmpty(level)) {
this.setState({
permissionsModalVisible: true,
});
handleQueryPermissions({ level, page: 0, size: 10 }).then((res) => {
if (res) {
const { dataSource, pagination } = res;
const { permissionsModalDataSource = [] } = this.state;
this.setState({
permissionsModalDataSource: uniqBy(dataSource.concat(permissionsModalDataSource), 'id'),
permissionsModalPagination: pagination,
});
}
});
}
}
Example #8
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* 查询微服务
*/
@Bind()
queryMicroservice(startTime, endTime) {
fetchMicroservice().then((data) => {
if (data && !data.failed) {
if (!isEmpty(data)) {
const handledData = uniqBy(
data.map((item) => ({ name: item.name.split(':')[1] })),
'name'
);
this.setState({
microserviceList: handledData,
currentService: handledData[0],
});
this.querySingleApiInvokeCount(startTime, endTime, handledData[0]);
}
}
});
}
Example #9
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* 新增一个历史记录
* @param {object} tab - tab 信息
*/
addHistory(tab) {
const { history = [] } = this.state;
const newHistory = uniqBy([tab, ...history], (t) => t.key);
if (newHistory.length > 8) {
newHistory.pop();
}
storeHistory(history);
this.setState({
history: newHistory,
});
}
Example #10
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* 新增一个历史记录
* @param {object} tab - tab 信息
*/
addHistory(tab) {
const { history = [] } = this.state;
const newHistory = uniqBy([tab, ...history], (t) => t.key);
if (newHistory.length > 8) {
newHistory.pop();
}
setSession(menuHistorySessionKey, history);
this.setState({
history: newHistory,
});
}
Example #11
Source File: Editor.js From hzero-front with Apache License 2.0 | 6 votes |
@Bind()
handleSqlOk() {
const { form, rangeSqlidExclList, dispatch } = this.props;
form.validateFields(['SQLID', { force: true }], (err, value) => {
if (!err) {
const data = {
sqlId: value.SQLID,
};
const newData = uniqBy([...rangeSqlidExclList, data], 'sqlId');
dispatch({
type: 'permission/updateState',
payload: {
rangeSqlidExclList: newData,
},
});
this.setState({
sqlVisible: false,
});
}
});
}
Example #12
Source File: Editor.js From hzero-front with Apache License 2.0 | 6 votes |
onSelectTenant(record) {
const { dispatch, rangeTenantExclList } = this.props;
const newData = uniqBy([...rangeTenantExclList, record], 'tenantId');
dispatch({
type: 'permission/updateState',
payload: {
rangeTenantExclList: newData,
},
});
}
Example #13
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* 打开发送模态框
*
* @memberof List
*/
@Bind()
handleOpenSendModal(record) {
const { dispatch } = this.props;
dispatch({
type: 'sendConfig/fetchLangType',
payload: { tenantId: record.tenantId, messageCode: record.messageCode },
});
let anotherServerList = [];
const tempServerList = [];
if (record.typeCode) {
tempServerList.push({ typeMeaning: record.typeMeaning, typeCode: record.typeCode });
}
if (!isEmpty(record.serverList)) {
anotherServerList = uniqBy(
record.serverList.map((item) => ({
typeMeaning: item.typeMeaning,
typeCode: item.typeCode,
})),
'typeCode'
);
}
this.setState({
visible: true,
tableRecord: { ...record },
enableService: [...tempServerList, ...anotherServerList],
});
}
Example #14
Source File: index.js From thecrucibletracker with MIT License | 6 votes |
componentDidMount(prevProps, prevState, snapshot) {
if (!this.props.user) {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
Promise.all([
fetch(`/api/decks/${this.props.deckID}/games`).then((response) => response.json()),
]).then((values) => {
const toUnix = (date) => (new Date(date).getTime()) / 1000;
let games = values[0];
games = uniqBy(games, (game) => {
if (game.crucible_game_id) return game.crucible_game_id;
return game.id;
});
games = games.sort((a, b) => toUnix(b.date) - toUnix(a.date));
this.setState({
games,
});
});
return;
}
fetchForUser(this.props.user, this.props.deckID)
.then(({ games, gameSummaries }) => {
this.setState({
games,
gameSummaries,
});
});
fetch(`/api/users/${this.props.user}/awards`)
.then((res) => res.json())
.then(({ awards }) => {
this.setState({ awards });
});
}
Example #15
Source File: Editor.js From hzero-front with Apache License 2.0 | 6 votes |
onSelectService(record) {
const { dispatch, rangeServiceNameExclList } = this.props;
const data = {
serviceName: record.serviceCode,
};
const newData = uniqBy([...rangeServiceNameExclList, data], 'serviceName');
dispatch({
type: 'permission/updateState',
payload: {
rangeServiceNameExclList: newData,
},
});
}
Example #16
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
@Bind()
save(record, form) {
const { handleSave = (e) => e, handleCreate = (e) => e, menuDataSource = {} } = this.props;
const { processingRowKeys = [] } = this.state;
const { validateFields = (e) => e } = form;
const defaultCode = menuDataSource.code;
const codePrefix = `${defaultCode}.ps.`;
validateFields((err, values) => {
if (isEmpty(err)) {
const newRecord = {
...record,
...values,
icon: 'link',
};
this.setState({
processingRowKeys: uniqBy(processingRowKeys.concat(record.key)),
});
if (record._status === 'create') {
newRecord.code = `${codePrefix}${values.code}`;
handleCreate(newRecord, () => {
this.fetchDataSource();
// this.cancel(record);
this.setState({
processingRowKeys: processingRowKeys.filter((o) => o !== record.key),
});
});
} else {
handleSave(newRecord, () => {
this.fetchDataSource();
this.cancel(record);
this.setState({
processingRowKeys: processingRowKeys.filter((o) => o !== record.key),
});
});
}
} else {
setTimeout(() => {
this.forceUpdate();
}, 23);
}
});
}
Example #17
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
/**
* 选中或取消复制的内容的菜单
* @param {object} record - 当前行数据
* @param {boolean} selected - 是否选中
*/
handleMenuRowSelect(record, selected) {
const { dataSource } = this.props;
const { menuSelectedRowKeys, menuSelectedRows } = this.state;
if (record.id === dataSource.currentId) return; // 复制的节点必须勾选
if (selected) {
// 子节点被勾选时,其父节点必须已经被勾选,否则会造成断层
const targetParent = menuSelectedRowKeys.includes(record.parentId);
if (!targetParent) return;
}
const setIdList = [];
const setRowList = [];
let nextRows = [];
const getSubSetIdList = (collections = []) => {
collections.forEach((n) => {
setIdList.push(n.id);
if (selected) {
setRowList.push(n);
}
if (!isEmpty(n.subMenus)) {
getSubSetIdList(n.subMenus);
}
});
};
if (!isEmpty(record.subMenus)) {
getSubSetIdList(record.subMenus);
}
setIdList.push(record.id);
const filteredRowKeys = filter(menuSelectedRowKeys, (item) => !setIdList.includes(item));
if (selected) {
setRowList.push(record);
nextRows = uniqBy(menuSelectedRows.concat(setRowList), 'id');
} else {
nextRows = filter(menuSelectedRows, (item) => filteredRowKeys.includes(item.id));
}
// menuSelectedRows中存储的是打平的树形数据 不含subMenus
const nextExportSelectedRows = nextRows.map((row) => {
const nextRow = { ...row };
const { subMenus, ...rest } = nextRow;
const newValue = { ...rest };
return newValue;
});
this.setState({
menuSelectedRowKeys: selected ? menuSelectedRowKeys.concat(setIdList) : filteredRowKeys,
menuSelectedRows: nextExportSelectedRows,
});
}
Example #18
Source File: Company.js From hzero-front with Apache License 2.0 | 5 votes |
/**
* 选中父级后同时选中子集
* @param {*Object} record 当前操作的行
* @param {*boolean} selected 选中标记
* @param {*Array} selectedRows 已经选中行数据
*/
@Bind()
selectChilds(record = {}, selected, selectedRows) {
const { loading } = this.props;
const { updateLoading, originList } = this.state;
if (updateLoading || loading) return;
this.setState({
updateLoading: true,
});
let grandsonList = [];
const childType = this.findChildType(record.typeCode);
const childLists = originList.filter(
(list) => list.parentId === record.dataId && list.typeCode && list.typeCode === childType
);
childLists.map((childList) => {
const grandsonType = this.findChildType(childList.typeCode);
grandsonList = unionWith(
grandsonList,
originList.filter(
(list) =>
list.parentId === childList.dataId && list.typeCode && list.typeCode === grandsonType
)
);
return grandsonList;
});
let rows;
if (selected) {
rows = unionWith(unionWith(selectedRows, childLists), grandsonList);
} else {
rows = pullAllBy(pullAllBy(selectedRows, childLists, 'dataId'), grandsonList, 'dataId');
}
this.setState(
{
checkedList: uniqBy(rows, 'id'),
},
() => {
this.handleSaveCompany();
}
);
}
Example #19
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
@Bind()
edit(record) {
const { editingRows } = this.state;
this.setState({
editingRows: uniqBy(editingRows.concat({ ...record }), 'key'),
});
}
Example #20
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
add() {
const { editingRows, dataSource } = this.state;
const { roleDatasource = {} /* , resourceLevel = [] */ } = this.props;
const item = { key: uuidv4() };
// if (roleDatasource.tenantId === 0) {
// item.organizationId = roleDatasource.tenantId;
// item.tenantName = roleDatasource.tenantName;
// // item.assignLevel = 'site';
// // item.assignLevelMeaning = getCodeMeaning('site', resourceLevel);
// // item.assignLevelValue = 0;
// // item.assignLevelValueMeaning = roleDatasource.tenantName;
// }
if (roleDatasource.level === 'site') {
item.assignLevel = 'organization';
item.assignLevelValue = roleDatasource.tenantId;
item.assignLevelValueMeaning = roleDatasource.tenantName;
// 之前的逻辑
// item.organizationId = roleDatasource.tenantId;
// item.tenantName = roleDatasource.tenantName;
// item.assignLevel = 'organization';
// // item.assignLevelMeaning = getCodeMeaning('site', resourceLevel);
// item.assignLevelValue = 0;
// // item.assignLevelValueMeaning = roleDatasource.tenantName;
}
if (!isNil(roleDatasource.parentRoleAssignUnitId)) {
item.assignLevel = 'org';
}
if (currentTenantId !== 0 && VERSION_IS_OP) {
item.organizationId = roleDatasource.tenantId;
item.tenantName = roleDatasource.tenantName;
item.assignLevel = 'organization';
// item.assignLevelMeaning = getCodeMeaning('site', resourceLevel);
item.assignLevelValue = 0;
// item.assignLevelValueMeaning = roleDatasource.tenantName;
}
this.setState({
dataSource: [item].concat(dataSource),
editingRows: uniqBy(editingRows.concat(item), 'key'),
});
}
Example #21
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
/**
* 选中或取消选中导出的菜单
* @param {object} record - 当前行数据
* @param {boolean} selected - 是否选中
*/
@Bind()
handleExportRowSelect(record, selected) {
const { exportSelectedRowKeys, exportSelectedRows } = this.state;
// 目前只能通过rootNode为true,或parentId=0来判断为根节点。只有根节点为类型为根目录才可以勾选
if (selected && !record.rootNode) {
// 子节点被勾选时,其父节点必须已经被勾选,否则会造成断层
const targetParent = exportSelectedRowKeys.includes(record.parentId);
if (!targetParent) return;
}
const setIdList = [];
const setRowList = [];
let nextRows = [];
const getSubSetIdList = (collections = []) => {
collections.forEach((n) => {
setIdList.push(n.id);
if (selected) {
setRowList.push(n);
}
if (!isEmpty(n.subMenus)) {
getSubSetIdList(n.subMenus);
}
});
};
if (!isEmpty(record.subMenus)) {
getSubSetIdList(record.subMenus);
}
setIdList.push(record.id);
const filteredRowKeys = filter(exportSelectedRowKeys, (item) => !setIdList.includes(item));
if (selected) {
setRowList.push(record);
nextRows = uniqBy(exportSelectedRows.concat(setRowList), 'id');
} else {
nextRows = filter(exportSelectedRows, (item) => filteredRowKeys.includes(item.id));
}
// exportSelectedRows中存储的是打平的树形数据 不含subMenus
const nextExportSelectedRows = nextRows.map((row) => {
const nextRow = { ...row };
const { subMenus, ...rest } = nextRow;
const newValue = { ...rest };
return newValue;
});
this.setState({
exportSelectedRowKeys: selected ? exportSelectedRowKeys.concat(setIdList) : filteredRowKeys,
exportSelectedRows: nextExportSelectedRows,
});
}
Example #22
Source File: RequestsContainer.js From covidsos with MIT License | 5 votes |
fetchRequests() {
const {type} = this.state;
const isAuthorisedUser = isAuthorisedUserLoggedIn();
let url = isAuthorisedUser ? config.adminAllRequests : config.pendingRequests;
if (type) {
switch (type) {
case 'new':
url = config.newRequests;
break;
case 'in-progress':
url = config.inProgressRequests;
break;
case 'completed':
url = isAuthorisedUser ? config.adminCompletedRequests : config.completedRequests;
break;
default:
url = isAuthorisedUser ? config.adminPendingRequests : config.pendingRequests;
break;
}
}
makeApiCall(url, 'GET', {}, (response) => {
let allRequests = [];
if (type || !isAuthorisedUser) {
allRequests = this.addToArray(allRequests, response, type);
} else {
allRequests = this.addToArray(allRequests, response.unverified_requests, 'new');
allRequests = this.addToArray(allRequests, response.assigned_requests, 'in-progress');
allRequests = this.addToArray(allRequests, response.pending_requests, 'pending');
allRequests = this.addToArray(allRequests, response.completed_requests, 'completed');
}
let filterData = {
source: uniq(map(allRequests, 'source')),
city: uniq(map(allRequests, 'city')),
managed_by: uniqBy(
map(allRequests, ({managed_by, managed_by_id}) => ({managed_by, managed_by_id})),
'managed_by_id')
}
allRequests = this.sortRequestsByTime(allRequests);
this.setState({allRequests, requestsToDisplay: allRequests, filterData, isLoading: false});
}, false);
}
Example #23
Source File: fetch.js From thecrucibletracker with MIT License | 5 votes |
fetchGamesAndSummariesForUser = (user, deckID) => {
let pathGames = `${apiPath}/users/${user}/games`;
let pathGameSummaries = `${apiPath}/users/${user}/game-summaries`;
if (deckID) {
pathGames = `${apiPath}/users/${user}/decks/${deckID}/games`;
pathGameSummaries = `${apiPath}/users/${user}/decks/${deckID}/game-summaries`;
}
return Promise.all([
fetch(pathGames).then((response) => response.json()),
fetch(pathGameSummaries).then((response) => response.json()),
])
.then((values) => {
let games = values[0];
let gameSummaries = values[1];
if (deckID) {
games = games.filter((g) => (g.winner === user && g.winner_deck_id === deckID) || (g.loser === user && g.loser_deck_id === deckID));
}
const toUnix = (date) => (new Date(date).getTime()) / 1000;
games = uniqBy(games, (game) => {
if (game.crucible_game_id) return game.crucible_game_id;
return game.id;
});
games = games.filter((game) => game.winner !== game.loser);
games = games.filter((game) => game.turns > 2);
games = games.sort((a, b) => toUnix(b.date) - toUnix(a.date));
gameSummaries = gameSummaries.filter((summary) => games.find((game) => game.id === summary.game_id));
gameSummaries = uniqBy(gameSummaries, 'game_id');
return {
games,
gameSummaries,
};
});
}
Example #24
Source File: fetch.js From thecrucibletracker with MIT License | 5 votes |
fetchForUser = (user, deckID) => {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
let pathGames = `${apiPath}/users/${user}/games`;
let pathGameSummaries = `${apiPath}/users/${user}/game-summaries`;
let pathGameTimelines = `${apiPath}/users/${user}/game-timelines`;
if (deckID) {
pathGames = `${apiPath}/users/${user}/decks/${deckID}/games`;
pathGameSummaries = `${apiPath}/users/${user}/decks/${deckID}/game-summaries`;
pathGameTimelines = `${apiPath}/users/${user}/decks/${deckID}/game-timelines`;
}
return Promise.all([
fetch(pathGames).then((response) => response.json()),
fetch(pathGameSummaries).then((response) => response.json()),
fetch(pathGameTimelines).then((response) => response.json()),
])
.then((values) => {
let games = values[0];
let gameSummaries = values[1];
let gameTimelines = values[2];
if (deckID) {
games = games.filter((g) => (g.winner === user && g.winner_deck_id === deckID) || (g.loser === user && g.loser_deck_id === deckID));
}
const toUnix = (date) => (new Date(date).getTime()) / 1000;
games = uniqBy(games, (game) => {
if (game.crucible_game_id) return game.crucible_game_id;
return game.id;
});
games = games.filter((game) => game.winner !== game.loser);
games = games.filter((game) => game.turns > 2);
games = games.sort((a, b) => toUnix(b.date) - toUnix(a.date));
gameSummaries = gameSummaries.filter((summary) => games.find((game) => game.id === summary.game_id));
gameTimelines = gameTimelines.filter((timeline) => games.find((game) => game.id === timeline.game_id));
// A bug leaves us with duplicate summaries and timelines. Is there duplicate 'events'?
gameSummaries = uniqBy(gameSummaries, 'game_id');
gameTimelines = uniqBy(gameTimelines, 'game_id');
return {
games,
gameSummaries,
gameTimelines,
};
});
}
Example #25
Source File: index.js From thecrucibletracker with MIT License | 5 votes |
fetchForUser = (user, deckID) => {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const pathGames = `${api.endpoint}/users/${user}/decks/${deckID}/games`;
const pathGameSummaries = `${api.endpoint}/users/${user}/decks/${deckID}/game-summaries`;
return Promise.all([
fetch(pathGames).then((response) => response.json()),
fetch(pathGameSummaries).then((response) => response.json()),
])
.then(async (values) => {
let games = values[0];
let gameSummaries = values[1];
if (deckID) {
games = games.filter((g) => (g.winner === user && g.winner_deck_id === deckID) || (g.loser === user && g.loser_deck_id === deckID));
}
const toUnix = (date) => (new Date(date).getTime()) / 1000;
games = uniqBy(games, (game) => {
if (game.crucible_game_id) return game.crucible_game_id;
return game.id;
});
games = games.filter((game) => game.winner !== game.loser);
games = games.filter((game) => game.turns > 2);
games = games.sort((a, b) => toUnix(b.date) - toUnix(a.date));
gameSummaries = gameSummaries.filter((summary) => games.find((game) => game.id === summary.game_id));
// A bug leaves us with duplicate summaries and timelines. Is there duplicate 'events'?
gameSummaries = uniqBy(gameSummaries, 'game_id');
const deckUUIDMap = {};
games.forEach(({ winner_deck_id, loser_deck_id }) => {
deckUUIDMap[winner_deck_id] = true;
deckUUIDMap[loser_deck_id] = true;
});
const deckUUIDs = Object.keys(deckUUIDMap);
return {
games,
gameSummaries,
};
});
}
Example #26
Source File: index.js From holo-schedule with MIT License | 5 votes |
uniqRightBy = (array, ...args) => reverse(uniqBy(reverse([...array]), ...args))
Example #27
Source File: AddStudentToActivityBatch.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
AddEditActivityBatches = props => {
const classes = useStyles();
const [formState, setFormState] = useState({
dataToShow: [],
students: [],
studentsFilter: [],
filterDataParameters: {},
isFilterSearch: false,
/** Pagination and sortinig data */
isDataLoading: false,
pageSize: "",
totalRows: "",
page: "",
pageCount: "",
sortAscending: true,
streams: []
});
const [selectedStudents, setSeletedStudent] = useState([]);
const { activity, activityBatch } = props;
const ACTIVITY_BATCH_STUDENTS =
strapiConstants.STRAPI_DB_URL +
strapiConstants.STRAPI_ACTIVITY +
`/${activity}/` +
strapiConstants.STRAPI_STUDENTS;
const ACTIVITY_CREATE_BATCH_URL =
strapiConstants.STRAPI_DB_URL +
strapiConstants.STRAPI_ACTIVITY_BATCH_URL +
`/${activityBatch}/` +
strapiConstants.STRAPI_ADD_STUDENTS;
useEffect(() => {
serviceProviders
.serviceProviderForGetRequest(ACTIVITY_BATCH_STUDENTS)
.then(res => {
setFormState(formState => ({
...formState,
studentsFilter: res.data.result,
streams: getStreams(res.data.result)
}));
})
.catch(error => {
console.log("error", error);
});
getStudents(10, 1);
}, []);
/** This seperate function is used to get the Activity Batches data*/
const getStudents = async (pageSize, page, params = null) => {
if (params !== null && !formUtilities.checkEmpty(params)) {
let defaultParams = {
page: page,
pageSize: pageSize
};
Object.keys(params).map(key => {
return (defaultParams[key] = params[key]);
});
params = defaultParams;
} else {
params = {
page: page,
pageSize: pageSize
};
}
setFormState(formState => ({
...formState,
isDataLoading: true
}));
await serviceProviders
.serviceProviderForGetRequest(ACTIVITY_BATCH_STUDENTS, params)
.then(res => {
formState.dataToShow = [];
setFormState(formState => ({
...formState,
students: res.data.result,
dataToShow: res.data.result,
pageSize: res.data.pageSize,
totalRows: res.data.rowCount,
page: res.data.page,
pageCount: res.data.pageCount,
isDataLoading: false,
streams: getStreams(res.data.result)
}));
})
.catch(error => {
console.log("error", error);
});
};
const getStreams = data => {
const streams = data.map(student => student.individual.stream);
return uniqBy(streams, stream => stream.id);
};
/** Search filter is called when we select filters and click on search button */
const searchFilter = async (perPage = formState.pageSize, page = 1) => {
if (!formUtilities.checkEmpty(formState.filterDataParameters)) {
formState.isFilterSearch = true;
await getStudents(perPage, page, formState.filterDataParameters);
}
};
const clearFilter = () => {
setFormState(formState => ({
...formState,
isFilterSearch: false,
/** Clear all filters */
filterDataParameters: {},
/** Turns on the spinner */
isDataLoading: true
}));
/**Need to confirm this thing for resetting the data */
restoreData();
};
const restoreData = () => {
getStudents(formState.pageSize, 1);
};
const handleChangeAutoComplete = (filterName, event, value) => {
if (value === null) {
delete formState.filterDataParameters[filterName];
//restoreData();
} else {
formState.filterDataParameters[filterName] = value["id"];
}
};
const handleRowChange = ({ selectedRows }) => {
const studentIds = selectedRows.map(student => student.id);
setSeletedStudent(studentIds);
};
/** Pagination */
const handlePerRowsChange = async (perPage, page) => {
/** If we change the now of rows per page with filters supplied then the filter should by default be applied*/
if (formUtilities.checkEmpty(formState.filterDataParameters)) {
await getStudents(perPage, page);
} else {
if (formState.isFilterSearch) {
await searchFilter(perPage, page);
} else {
await getStudents(perPage, page);
}
}
};
const handlePageChange = async page => {
if (formUtilities.checkEmpty(formState.filterDataParameters)) {
await getStudents(formState.pageSize, page);
} else {
if (formState.isFilterSearch) {
await searchFilter(formState.pageSize, page);
} else {
await getStudents(formState.pageSize, page);
}
}
};
const handleAddStudent = () => {
let postData = {
students: selectedStudents
};
serviceProviders
.serviceProviderForPostRequest(ACTIVITY_CREATE_BATCH_URL, postData)
.then(res => {
setSeletedStudent([]);
props.getLatestData();
props.closeModal();
})
.catch(error => {
setSeletedStudent([]);
props.closeModal();
});
};
const handleFilterChange = event => {
setFormState(formState => ({
...formState,
filterDataParameters: {
...formState.filterDataParameters,
[event.target.name]: event.target.value
}
}));
event.persist();
};
/** Columns to show in table */
const column = [
{
name: "Student Name",
sortable: true,
cell: row => `${row.individual.first_name} ${row.individual.last_name}`
},
{ name: "Stream", sortable: true, selector: "individual.stream.name" },
{ name: "Mobile No.", sortable: true, selector: "phone" }
];
return (
<Dialog
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={props.showModal}
onClose={() => props.closeModal()}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={props.showModal}>
<div className={classes.paper}>
<Typography variant={"h2"} className={classes.textMargin}>
{genericConstants.ADD_STUDENT_TO_ACTIVITY_BATCH}
</Typography>
<div className={classes.editDialogue}>
<Grid item xs={12}>
<Grid>
<Grid item xs={12} className={classes.formgrid}>
<Card className={styles.filterButton}>
<CardContent className={classes.Cardtheming}>
<Grid
className={classes.filterOptions}
container
spacing={1}
>
<Grid item className={classes.paddingDate}>
<Autocomplete
id="stream-dropdown"
options={formState.streams}
className={classes.autoCompleteField}
getOptionLabel={option => option.name}
onChange={(event, value) =>
handleChangeAutoComplete(
ACTIVITY_BATCH_STREAM_FILTER,
event,
value
)
}
renderInput={params => (
<TextField
{...params}
label="Stream"
className={classes.autoCompleteField}
variant="outlined"
/>
)}
/>
</Grid>
<Grid item className={classes.paddingDate}>
<TextField
label="Student Name"
placeholder="Student Name"
variant="outlined"
value={
formState.filterDataParameters[
ACTIVITY_BATCH_STUDENT_FILTER
] || ""
}
name={ACTIVITY_BATCH_STUDENT_FILTER}
className={classes.autoCompleteField}
onChange={handleFilterChange}
/>
</Grid>
<Grid item className={classes.paddingDate}>
<TextField
label="Mobile Number"
placeholder="Mobile Number"
variant="outlined"
value={
formState.filterDataParameters[
ACTIVITY_BATCH_MOBILE_FILTER
] || ""
}
name={ACTIVITY_BATCH_MOBILE_FILTER}
className={classes.autoCompleteField}
onChange={handleFilterChange}
/>
</Grid>
{/* </Grid> */}
<Grid item className={classes.filterButtonsMargin}>
<YellowButton
variant="contained"
color="primary"
disableElevation
onClick={event => {
event.persist();
searchFilter();
}}
>
{genericConstants.SEARCH_BUTTON_TEXT}
</YellowButton>
</Grid>
<Grid item className={classes.filterButtonsMargin}>
<GrayButton
variant="contained"
color="primary"
onClick={clearFilter}
disableElevation
>
{genericConstants.RESET_BUTTON_TEXT}
</GrayButton>
</Grid>
</Grid>
</CardContent>
</Card>
{formState.dataToShow ? (
<Table
data={formState.dataToShow}
column={column}
defaultSortField="name"
defaultSortAsc={formState.sortAscending}
progressPending={formState.isDataLoading}
paginationTotalRows={formState.totalRows}
paginationRowsPerPageOptions={[10, 20, 50]}
onChangeRowsPerPage={handlePerRowsChange}
onChangePage={handlePageChange}
onSelectedRowsChange={handleRowChange}
noDataComponent="No eligible student data found"
/>
) : (
<Spinner />
)}
<Card className={styles.noBorderNoShadow}>
<CardContent>
<Grid container spacing={2}>
<Grid item className={classes.filterButtonsMargin}>
<YellowButton
type="submit"
color="primary"
variant="contained"
onClick={handleAddStudent}
disabled={selectedStudents.length <= 0}
>
{genericConstants.ADD_STUDENT_TO_ACTIVITY_BATCH}
</YellowButton>
</Grid>
</Grid>
</CardContent>
</Card>
</Grid>
</Grid>
</Grid>
</div>
</div>
</Fade>
</Dialog>
);
}
Example #28
Source File: ListTable.js From hzero-front with Apache License 2.0 | 4 votes |
/**
* render
* @returns React.element
*/
render() {
const { loading, dataSource, pagination, onChange, tenantRoleLevel, path } = this.props;
const columns = [
!tenantRoleLevel && {
title: intl.get('entity.tenant.tag').d('租户'),
dataIndex: 'tenantName',
width: 150,
},
{
title: intl.get('hmsg.sendConfig.model.sendConfig.messageCode').d('消息代码'),
dataIndex: 'messageCode',
width: 200,
},
{
title: intl.get('hmsg.sendConfig.model.sendConfig.messageName').d('消息名称'),
dataIndex: 'messageName',
},
{
title: intl.get('hmsg.sendConfig.model.sendConfig.typeMeaning').d('启用服务'),
dataIndex: 'typeMeaning',
width: 420,
render: (val, record) => {
let types = [];
if (!isEmpty(record.serverList)) {
const list = record.serverList.map((item) => ({
typeCode: item.typeCode,
typeMeaning: item.typeMeaning,
}));
types = uniqBy(list, 'typeCode');
}
return <span>{types && types.map((item) => this.typeMeaningRender(item))}</span>;
},
},
// {
// title: intl.get('hmsg.sendConfig.model.sendConfig.receiveConfigCode').d('接收配置编码'),
// dataIndex: 'receiveCode',
// width: 120,
// },
tenantRoleLevel &&
!VERSION_IS_OP && {
title: intl.get('hmsg.common.view.source').d('来源'),
width: 120,
dataIndex: 'tenantId',
render: (_, record) => {
const tenantId = getCurrentOrganizationId();
return tenantId.toString() === record.tenantId.toString() ? (
<Tag color="green">{intl.get('hzero.common.custom').d('自定义')}</Tag>
) : (
<Tag color="orange">{intl.get('hzero.common.predefined').d('预定义')}</Tag>
);
},
},
{
title: intl.get('hzero.common.status').d('状态'),
dataIndex: 'enabledFlag',
width: 100,
render: enableRender,
},
{
title: intl.get('hzero.common.button.action').d('操作'),
dataIndex: 'operator',
width: 200,
fixed: 'right',
render: (val, record) => {
const operators = [];
const tenantId = getCurrentOrganizationId();
if (!tenantRoleLevel || tenantId.toString() === record.tenantId.toString()) {
operators.push(
{
key: 'edit',
ele: (
<ButtonPermission
type="text"
permissionList={[
{
code: `${path}.button.edit`,
type: 'button',
meaning: '消息发送配置-编辑',
},
]}
onClick={() => this.editOption(record)}
>
{intl.get('hzero.common.button.edit').d('编辑')}
</ButtonPermission>
),
len: 2,
title: intl.get('hzero.common.button.edit').d('编辑'),
},
{
key: 'delete',
ele: (
<Popconfirm
placement="topRight"
title={intl.get('hzero.common.message.confirm.delete').d('是否删除此条记录?')}
onConfirm={() => this.deleteOption(record)}
>
<ButtonPermission
type="text"
permissionList={[
{
code: `${path}.button.delete`,
type: 'button',
meaning: '消息发送配置-删除',
},
]}
>
{intl.get('hzero.common.button.delete').d('删除')}
</ButtonPermission>
</Popconfirm>
),
len: 2,
title: intl.get('hzero.common.button.delete').d('删除'),
}
);
if (record.enabledFlag && record.serverList && record.serverList.length !== 0) {
operators.push({
key: 'testSend',
ele: (
<ButtonPermission
type="text"
permissionList={[
{
code: `${path}.button.testSend`,
type: 'button',
meaning: '消息发送配置-测试发送',
},
]}
onClick={() => this.sendOption(record)}
>
{intl.get('hmsg.sendConfig.view.title.testSend').d('测试发送')}
</ButtonPermission>
),
len: 4,
title: intl.get('hmsg.sendConfig.view.title.testSend').d('测试发送'),
});
}
}
if (
tenantId.toString() !== record.tenantId.toString() &&
tenantRoleLevel &&
!VERSION_IS_OP
) {
operators.push({
key: 'copy',
ele: (
<a onClick={() => this.handleCopy(record)}>
{intl.get('hzero.common.button.copy').d('复制')}
</a>
),
len: 2,
title: intl.get('hzero.common.button.copy').d('复制'),
});
}
return operatorRender(operators);
},
},
].filter(Boolean);
return (
<Table
bordered
rowKey="tempServerId"
loading={loading}
columns={columns}
scroll={{ x: tableScrollWidth(columns) }}
dataSource={dataSource}
pagination={pagination}
onChange={(page) => onChange(page)}
/>
);
}
Example #29
Source File: List.js From hzero-front with Apache License 2.0 | 4 votes |
@Bind()
handleOpenModal(record, dataIndex, tls = {}) {
const { languageType = [] } = this.props;
const { currentRecord } = this.state;
// 当前如果是第一次打开,那么_tls就取当前record的数据,否则取state中的currentRecord
const { _tls = {} } = currentRecord.$form ? currentRecord : record;
let data = {};
const dataSource = [];
const formItemData = [];
/**
* 字段FormItem从info接口中取
*/
const formI = tls[dataIndex];
Object.keys(formI).forEach((r, ri) => {
Object.values(formI).forEach((res, resi) => {
if (ri === resi) {
formItemData.push({
lang: r,
value: '',
});
}
});
});
// if (record !== currentRecord || dataIndex !== stateDataIndex) {
/**
* 获取到当前字段JSON
*/
Object.keys(_tls).forEach((item, index) => {
if (item === dataIndex) {
Object.values(_tls).forEach((i, d) => {
if (index === d) {
data = i;
}
});
}
});
/**
* 将当前字段JSON处理为数组,此时的字段含有字段和字段值
*/
Object.keys(data).forEach((r, ri) => {
Object.values(data).forEach((res, resi) => {
if (ri === resi) {
dataSource.push({
lang: r,
value: res,
});
}
});
});
/**
* 将formItem和dataSource合并到一起,防止出现没有FormItem的情况
*/
const newData = uniqBy([...dataSource, ...formItemData], 'lang');
/**
* 将数据与语言值集对比,添加meaning
*/
const newModalData = [];
const types = languageType.map((l) => l.code);
languageType.forEach((k) => {
newData.forEach((j) => {
if (k.code === j.lang) {
newModalData.push({
...j,
meaning: k.meaning,
});
} else if (!types.includes(j.lang)) {
newModalData.push(j);
}
});
});
const filterModalData = uniqBy(newModalData, 'lang');
const flag = isEmpty(currentRecord.$form);
this.setState({
visible: true,
modalData: filterModalData,
dataIndex,
currentRecord: flag ? record : currentRecord,
});
// } else {
// this.setState({
// visible: true,
// dataIndex,
// });
// }
}