Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add filter command #54

Merged
merged 2 commits into from
Mar 18, 2024
Merged
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
58 changes: 58 additions & 0 deletions src/main/java/seedu/address/logic/commands/FilterCommand.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package seedu.address.logic.commands;

import static java.util.Objects.requireNonNull;

import seedu.address.commons.util.ToStringBuilder;
import seedu.address.logic.Messages;
import seedu.address.model.Model;
import seedu.address.model.person.PersonContainsKeywordsPredicate;

/**
* Finds and lists all persons in address book whose name contains any of the argument keywords.
Copy link

Choose a reason for hiding this comment

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

Some typo in the java doc comments. Should be 'whose department or tags'

* Keyword matching is case insensitive.
*/
public class FilterCommand extends Command {

public static final String COMMAND_WORD = "filter";

public static final String MESSAGE_USAGE = COMMAND_WORD + ": Filters all persons by the given departments or tags"
+ "the specified keywords (case-insensitive) and displays them as a list with index numbers.\n"
+ "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
+ "Example: " + COMMAND_WORD + " alice bob charlie";

private final PersonContainsKeywordsPredicate predicate;

public FilterCommand(PersonContainsKeywordsPredicate predicate) {
this.predicate = predicate;
}

@Override
public CommandResult execute(Model model) {
requireNonNull(model);
model.updateFilteredPersonList(predicate);
return new CommandResult(
String.format(Messages.MESSAGE_PERSONS_LISTED_OVERVIEW, model.getFilteredPersonList().size()));
}

@Override
public boolean equals(Object other) {
if (other == this) {
return true;

Check warning on line 40 in src/main/java/seedu/address/logic/commands/FilterCommand.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/seedu/address/logic/commands/FilterCommand.java#L40

Added line #L40 was not covered by tests
}

// instanceof handles nulls
if (!(other instanceof FilterCommand)) {
return false;

Check warning on line 45 in src/main/java/seedu/address/logic/commands/FilterCommand.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/seedu/address/logic/commands/FilterCommand.java#L45

Added line #L45 was not covered by tests
}

FilterCommand otherFilterCommand = (FilterCommand) other;
return predicate.equals(otherFilterCommand.predicate);
}

@Override
public String toString() {
return new ToStringBuilder(this)
.add("predicate", predicate)
.toString();

Check warning on line 56 in src/main/java/seedu/address/logic/commands/FilterCommand.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/seedu/address/logic/commands/FilterCommand.java#L54-L56

Added lines #L54 - L56 were not covered by tests
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import seedu.address.logic.commands.DeleteCommand;
import seedu.address.logic.commands.EditCommand;
import seedu.address.logic.commands.ExitCommand;
import seedu.address.logic.commands.FilterCommand;
import seedu.address.logic.commands.FindCommand;
import seedu.address.logic.commands.HelpCommand;
import seedu.address.logic.commands.ListCommand;
Expand Down Expand Up @@ -77,6 +78,9 @@ public Command parseCommand(String userInput) throws ParseException {
case HelpCommand.COMMAND_WORD:
return new HelpCommand();

case FilterCommand.COMMAND_WORD:
return new FilterCommandParser().parse(arguments);

default:
logger.finer("This user input caused a ParseException: " + userInput);
throw new ParseException(MESSAGE_UNKNOWN_COMMAND);
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/seedu/address/logic/parser/FilterCommandParser.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package seedu.address.logic.parser;

import static seedu.address.logic.Messages.MESSAGE_INVALID_COMMAND_FORMAT;

import java.util.Arrays;

import seedu.address.logic.commands.FilterCommand;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.person.PersonContainsKeywordsPredicate;

/**
* Parses input arguments and creates a new FilterCommand object
*/
public class FilterCommandParser implements Parser<FilterCommand> {

/**
* Parses the given {@code String} of arguments in the context of the FilterCommand
* and returns a FilterCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public FilterCommand parse(String args) throws ParseException {
String trimmedArgs = args.trim();
if (trimmedArgs.isEmpty()) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, FilterCommand.MESSAGE_USAGE));
}

String[] nameKeywords = trimmedArgs.split("\\s+");

return new FilterCommand(new PersonContainsKeywordsPredicate(Arrays.asList(nameKeywords)));
}

}
4 changes: 2 additions & 2 deletions src/main/java/seedu/address/model/person/Department.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class Department {
public Department(String department) {
requireNonNull(department);
checkArgument(isValidDepartment(department), MESSAGE_CONSTRAINTS);
this.department = department;
this.department = department.toUpperCase();
}

/**
Expand Down Expand Up @@ -57,7 +57,7 @@ public int hashCode() {
* Format state as text for viewing.
*/
public String toString() {
return '{' + department + '}';
return '{' + department.toUpperCase() + '}';
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ public NameContainsKeywordsPredicate(List<String> keywords) {
public boolean test(Person person) {
return keywords.stream()
.anyMatch(keyword -> person.getName().fullName.toLowerCase().replaceAll("\\s", "")
.contains(keyword.toLowerCase())
|| person.getTags().toString().toLowerCase().contains(keyword.toLowerCase()));
.contains(keyword.toLowerCase()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package seedu.address.model.person;

import java.util.List;
import java.util.function.Predicate;

import seedu.address.commons.util.ToStringBuilder;

/**
* Tests that a {@code Person}'s {@code Name} matches any of the keywords given.
Copy link

Choose a reason for hiding this comment

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

Javadoc typos

*/
public class PersonContainsKeywordsPredicate implements Predicate<Person> {
private final List<String> keywords;

public PersonContainsKeywordsPredicate(List<String> keywords) {
this.keywords = keywords;
}

@Override
public boolean test(Person person) {
return keywords.stream()
.anyMatch(keyword -> person.getDepartment().toString().toLowerCase().replaceAll("\\s", "")
.contains(keyword.toLowerCase())
|| person.getTags().toString().toLowerCase().contains(keyword.toLowerCase()));
}

@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}

// instanceof handles nulls
if (!(other instanceof PersonContainsKeywordsPredicate)) {
return false;
}

PersonContainsKeywordsPredicate otherPersonContainsKeywordsPredicate = (PersonContainsKeywordsPredicate) other;
return keywords.equals(otherPersonContainsKeywordsPredicate.keywords);
}

@Override
public String toString() {
return new ToStringBuilder(this).add("keywords", keywords).toString();
}
}
51 changes: 51 additions & 0 deletions src/test/java/seedu/address/logic/commands/FilterCommandTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package seedu.address.logic.commands;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static seedu.address.logic.Messages.MESSAGE_PERSONS_LISTED_OVERVIEW;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.address.testutil.TypicalPersons.CARL;
import static seedu.address.testutil.TypicalPersons.DANIEL;
import static seedu.address.testutil.TypicalPersons.getTypicalAddressBook;

import java.util.Arrays;
import java.util.Collections;

import org.junit.jupiter.api.Test;

import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.UserPrefs;
import seedu.address.model.person.PersonContainsKeywordsPredicate;

class FilterCommandTest {

private Model model = new ModelManager(getTypicalAddressBook(), new UserPrefs());
private Model expectedModel = new ModelManager(getTypicalAddressBook(), new UserPrefs());

@Test
public void execute_zeroKeywords_noPersonFound() {
String expectedMessage = String.format(MESSAGE_PERSONS_LISTED_OVERVIEW, 0);
PersonContainsKeywordsPredicate predicate = preparePredicate(" ");
FilterCommand command = new FilterCommand(predicate);
expectedModel.updateFilteredPersonList(predicate);
assertCommandSuccess(command, model, expectedMessage, expectedModel);
assertEquals(Collections.emptyList(), model.getFilteredPersonList());
}

@Test
public void execute_multipleKeywords_multiplePersonsFound() {
String expectedMessage = String.format(MESSAGE_PERSONS_LISTED_OVERVIEW, 2);
PersonContainsKeywordsPredicate predicate = preparePredicate("Marketing Production");
FilterCommand command = new FilterCommand(predicate);
expectedModel.updateFilteredPersonList(predicate);
assertCommandSuccess(command, model, expectedMessage, expectedModel);
assertEquals(Arrays.asList(CARL, DANIEL), model.getFilteredPersonList());
Copy link

Choose a reason for hiding this comment

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

Great work on testing the scenario of filtering based on multiple keywords.

}

/**
* Parses {@code userInput} into a {@code NameContainsKeywordsPredicate}.
*/
private PersonContainsKeywordsPredicate preparePredicate(String userInput) {
return new PersonContainsKeywordsPredicate(Arrays.asList(userInput.split("\\s+")));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@
import seedu.address.logic.commands.EditCommand;
import seedu.address.logic.commands.EditCommand.EditPersonDescriptor;
import seedu.address.logic.commands.ExitCommand;
import seedu.address.logic.commands.FilterCommand;
import seedu.address.logic.commands.FindCommand;
import seedu.address.logic.commands.HelpCommand;
import seedu.address.logic.commands.ListCommand;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.person.NameContainsKeywordsPredicate;
import seedu.address.model.person.Person;
import seedu.address.model.person.PersonContainsKeywordsPredicate;
import seedu.address.testutil.EditPersonDescriptorBuilder;
import seedu.address.testutil.PersonBuilder;
import seedu.address.testutil.PersonUtil;
Expand Down Expand Up @@ -76,6 +78,14 @@ public void parseCommand_find() throws Exception {
assertEquals(new FindCommand(new NameContainsKeywordsPredicate(keywords)), command);
}

@Test
public void parseCommand_filter() throws Exception {
List<String> keywords = Arrays.asList("foo", "bar", "baz");
FilterCommand command = (FilterCommand) parser.parseCommand(
FilterCommand.COMMAND_WORD + " " + keywords.stream().collect(Collectors.joining(" ")));
assertEquals(new FilterCommand(new PersonContainsKeywordsPredicate(keywords)), command);
}

@Test
public void parseCommand_help() throws Exception {
assertTrue(parser.parseCommand(HelpCommand.COMMAND_WORD) instanceof HelpCommand);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package seedu.address.logic.parser;

import static seedu.address.logic.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure;

import org.junit.jupiter.api.Test;

import seedu.address.logic.commands.FilterCommand;

public class FilterCommandParserTest {

private FilterCommandParser parser = new FilterCommandParser();

@Test
public void parse_emptyArg_throwsParseException() {
assertParseFailure(parser, " ", String.format(MESSAGE_INVALID_COMMAND_FORMAT, FilterCommand.MESSAGE_USAGE));
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,6 @@ public void test_nameContainsKeywords_returnsTrue() {
// Keywords with substrings
predicate = new NameContainsKeywordsPredicate(Collections.singletonList("ice"));
assertTrue(predicate.test(new PersonBuilder().withName("Alice Bob").build()));

// Keywords match tags
predicate = new NameContainsKeywordsPredicate(Arrays.asList("12345", "[email protected]", "friend", "Street"));
assertTrue(predicate.test(new PersonBuilder().withName("Alice").withPhone("12345")
.withEmail("[email protected]").withAddress("Main Street").withTags("friend").build()));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package seedu.address.model.person;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.jupiter.api.Test;

import seedu.address.testutil.PersonBuilder;

class PersonContainsKeywordsPredicateTest {

@Test
public void equals() {
List<String> firstPredicateKeywordList = Collections.singletonList("first");
List<String> secondPredicateKeywordList = Arrays.asList("first", "second");

PersonContainsKeywordsPredicate firstPredicate = new PersonContainsKeywordsPredicate(firstPredicateKeywordList);
PersonContainsKeywordsPredicate secondPredicate =
new PersonContainsKeywordsPredicate(secondPredicateKeywordList);

// same object -> returns true
assertTrue(firstPredicate.equals(firstPredicate));

// same values -> returns true
PersonContainsKeywordsPredicate firstPredicateCopy =
new PersonContainsKeywordsPredicate(firstPredicateKeywordList);
assertTrue(firstPredicate.equals(firstPredicateCopy));

// different types -> returns false
assertFalse(firstPredicate.equals(1));

// null -> returns false
assertFalse(firstPredicate.equals(null));

// different person -> returns false
assertFalse(firstPredicate.equals(secondPredicate));
}

@Test
public void test_nameContainsKeywords_returnsTrue() {
// One keyword
PersonContainsKeywordsPredicate predicate =
new PersonContainsKeywordsPredicate(Collections.singletonList("Finance"));
assertTrue(predicate.test(new PersonBuilder().withDepartment("Finance").build()));

// Multiple keywords
predicate = new PersonContainsKeywordsPredicate(Arrays.asList("Quantitative", "Finance"));
assertTrue(predicate.test(new PersonBuilder().withDepartment("Quantitative Finance").build()));

// Only one matching keyword
predicate = new PersonContainsKeywordsPredicate(Arrays.asList("Finance", "Marketing"));
assertTrue(predicate.test(new PersonBuilder().withDepartment("Quantitative Finance").build()));

// Mixed-case keywords
predicate = new PersonContainsKeywordsPredicate(Arrays.asList("finAnce", "quaNtitative"));
assertTrue(predicate.test(new PersonBuilder().withDepartment("Quantitative Finance").build()));

// Keywords without spacing
predicate = new PersonContainsKeywordsPredicate(Collections.singletonList("quantitativefinance"));
assertTrue(predicate.test(new PersonBuilder().withDepartment("Quantitative Finance").build()));

// Keywords with substrings
predicate = new PersonContainsKeywordsPredicate(Collections.singletonList("nan"));
assertTrue(predicate.test(new PersonBuilder().withDepartment("Quantitative Finance").build()));
}

@Test
public void test_nameDoesNotContainKeywords_returnsFalse() {
// Zero keywords
NameContainsKeywordsPredicate predicate = new NameContainsKeywordsPredicate(Collections.emptyList());
assertFalse(predicate.test(new PersonBuilder().withDepartment("Finance").build()));

// Non-matching keyword
predicate = new NameContainsKeywordsPredicate(Arrays.asList("Marketing"));
assertFalse(predicate.test(new PersonBuilder().withDepartment("Finance").build()));

// Keywords match phone, email and address, but does not match department
predicate = new NameContainsKeywordsPredicate(Arrays.asList("12345", "[email protected]", "Main", "Street"));
assertFalse(predicate.test(new PersonBuilder().withName("Alice").withPhone("12345")
.withEmail("[email protected]").withAddress("Main Street").withDepartment("Finance").build()));
}

@Test
public void toStringMethod() {
List<String> keywords = List.of("keyword1", "keyword2");
PersonContainsKeywordsPredicate predicate = new PersonContainsKeywordsPredicate(keywords);

String expected = PersonContainsKeywordsPredicate.class.getCanonicalName() + "{keywords=" + keywords + "}";
assertEquals(expected, predicate.toString());
}
}
Loading