= CRM Book - Developer Guide
:toc:
:toc-title:
:toc-placement: preamble
:sectnums:
:imagesDir: images
:stylesDir: stylesheets
:xrefstyle: full
ifdef::env-github[]
:tip-caption: :bulb:
:note-caption: :information_source:
endif::[]
:repoURL: https://github.com/CS2103JAN2018-F11-B1/main

By: `CS2103-F11-B1`      Since: `Jan 2018`      Licence: `MIT`

== Setting up

=== Prerequisites

. *JDK `1.8.0_60`* or later
+
[NOTE]
Having any Java 8 version is not enough. +
This app will not work with earlier versions of Java 8.
+

. *IntelliJ* IDE
+
[NOTE]
IntelliJ by default has Gradle and JavaFx plugins installed. +
Do not disable them. If you have disabled them, go to `File` > `Settings` > `Plugins` to re-enable them.


=== Setting up the project in your computer

. Fork this repo, and clone the fork to your computer
. Open IntelliJ (if you are not in the welcome screen, click `File` > `Close Project` to close the existing project dialog first)
. Set up the correct JDK version for Gradle
.. Click `Configure` > `Project Defaults` > `Project Structure`
.. Click `New...` and find the directory of the JDK
. Click `Import Project`
. Locate the `build.gradle` file and select it. Click `OK`
. Click `Open as Project`
. Click `OK` to accept the default settings
. Open a console and run the command `gradlew processResources` (Mac/Linux: `./gradlew processResources`). It should finish with the `BUILD SUCCESSFUL` message. +
This will generate all resources required by the application and tests.

=== Verifying the setup

. Run the `seedu.address.MainApp` and try a few commands
. <<Testing,Run the tests>> to ensure they all pass.

=== Configurations to do before writing code

==== Configuring the coding style

This project follows https://github.com/oss-generic/process/blob/master/docs/CodingStandards.adoc[oss-generic coding standards]. IntelliJ's default style is mostly compliant with ours but it uses a different import order from ours. To rectify,

. Go to `File` > `Settings...` (Windows/Linux), or `IntelliJ IDEA` > `Preferences...` (macOS)
. Select `Editor` > `Code Style` > `Java`
. Click on the `Imports` tab to set the order

* For `Class count to use import with '\*'` and `Names count to use static import with '*'`: Set to `999` to prevent IntelliJ from contracting the import statements
* For `Import Layout`: The order is `import static all other imports`, `import java.\*`, `import javax.*`, `import org.\*`, `import com.*`, `import all other imports`. Add a `<blank line>` between each `import`

Optionally, you can follow the <<UsingCheckstyle#, UsingCheckstyle.adoc>> document to configure Intellij to check style-compliance as you write code.

==== Updating documentation to match your fork

After forking the repo, links in the documentation will still point to the `se-edu/addressbook-level4` repo. If you plan to develop this as a separate product (i.e. instead of contributing to the `se-edu/addressbook-level4`) , you should replace the URL in the variable `repoURL` in `DeveloperGuide.adoc` and `UserGuide.adoc` with the URL of your fork.

==== Setting up CI

Set up Travis to perform Continuous Integration (CI) for your fork. See <<UsingTravis#, UsingTravis.adoc>> to learn how to set it up.

After setting up Travis, you can optionally set up coverage reporting for your team fork (see <<UsingCoveralls#, UsingCoveralls.adoc>>).

[NOTE]
Coverage reporting could be useful for a team repository that hosts the final version but it is not that useful for your personal fork.

Optionally, you can set up AppVeyor as a second CI (see <<UsingAppVeyor#, UsingAppVeyor.adoc>>).

[NOTE]
Having both Travis and AppVeyor ensures your App works on both Unix-based platforms and Windows-based platforms (Travis is Unix-based and AppVeyor is Windows-based)

==== Getting started with coding

When you are ready to start coding,

1. Get some sense of the overall design by reading <<Design-Architecture>>.
2. Take a look at <<GetStartedProgramming>>.

== Design

[[Design-Architecture]]
=== Architecture

.Architecture Diagram
image::Architecture.png[width="600"]

The *_Architecture Diagram_* given above explains the high-level design of the App. Given below is a quick overview of each component.

[TIP]
The `.pptx` files used to create diagrams in this document can be found in the link:{repoURL}/docs/diagrams/[diagrams] folder. To update a diagram, modify the diagram in the pptx file, select the objects of the diagram, and choose `Save as picture`.

`Main` has only one class called link:{repoURL}/src/main/java/seedu/address/MainApp.java[`MainApp`]. It is responsible for,

* At app launch: Initializes the components in the correct sequence, and connects them up with each other.
* At shut down: Shuts down the components and invokes cleanup method where necessary.

<<Design-Commons,*`Commons`*>> represents a collection of classes used by multiple other components. Two of those classes play important roles at the architecture level.

* `EventsCenter` : This class (written using https://github.com/google/guava/wiki/EventBusExplained[Google's Event Bus library]) is used by components to communicate with other components using events (i.e. a form of _Event Driven_ design)
* `LogsCenter` : Used by many classes to write log messages to the App's log file.

The rest of the App consists of four components.

* <<Design-Ui,*`UI`*>>: The UI of the App.
* <<Design-Logic,*`Logic`*>>: The command executor.
* <<Design-Model,*`Model`*>>: Holds the data of the App in-memory.
* <<Design-Storage,*`Storage`*>>: Reads data from, and writes data to, the hard disk.

Each of the four components

* Defines its _API_ in an `interface` with the same name as the Component.
* Exposes its functionality using a `{Component Name}Manager` class.

For example, the `Logic` component (see the class diagram given below) defines it's API in the `Logic.java` interface and exposes its functionality using the `LogicManager.java` class.

.Class Diagram of the Logic Component
image::LogicClassDiagram.png[width="800"]

[discrete]
==== Events-Driven nature of the design

The _Sequence Diagram_ below shows how the components interact for the scenario where the user issues the command `delete 1`.

.Component interactions for `delete 1` command (part 1)
image::SDforDeletePerson.png[width="800"]

[NOTE]
Note how the `Model` simply raises a `AddressBookChangedEvent` when the CRM Book data are changed, instead of asking the `Storage` to save the updates to the hard disk.

The diagram below shows how the `EventsCenter` reacts to that event, which eventually results in the updates being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time.

.Component interactions for `delete 1` command (part 2)
image::SDforDeletePersonEventHandling.png[width="800"]

[NOTE]
Note how the event is propagated through the `EventsCenter` to the `Storage` and `UI` without `Model` having to be coupled to either of them. This is an example of how this Event Driven approach helps us reduce direct coupling between components.

The sections below give more details of each component.

[[Design-Ui]]
=== UI component

.Structure of the UI Component
image::UiClassDiagram.png[width="800"]

*API* : link:{repoURL}/src/main/java/seedu/address/ui/Ui.java[`Ui.java`]

The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay`, `PersonListPanel`, `StatusBarFooter`, `BrowserPanel` etc. All these, including the `MainWindow`, inherit from the abstract `UiPart` class.

The `UI` component uses JavaFx UI framework. The layout of these UI parts are defined in matching `.fxml` files that are in the `src/main/resources/view` folder. For example, the layout of the link:{repoURL}/src/main/java/seedu/address/ui/MainWindow.java[`MainWindow`] is specified in link:{repoURL}/src/main/resources/view/MainWindow.fxml[`MainWindow.fxml`]

The `UI` component,

* Executes user commands using the `Logic` component.
* Binds itself to some data in the `Model` so that the UI can auto-update when data in the `Model` change.
* Responds to events raised from various parts of the App and updates the UI accordingly.

[[Design-Logic]]
=== Logic component

[[fig-LogicClassDiagram]]
.Structure of the Logic Component
image::LogicClassDiagram.png[width="800"]

.Structure of Commands in the Logic Component. This diagram shows finer details concerning `XYZCommand` and `Command` in <<fig-LogicClassDiagram>>
image::LogicCommandClassDiagram.png[width="800"]

*API* :
link:{repoURL}/src/main/java/seedu/address/logic/Logic.java[`Logic.java`]

.  `Logic` uses the `AddressBookParser` class to parse the user command.
.  This results in a `Command` object which is executed by the `LogicManager`.
.  The command execution can affect the `Model` (e.g. adding a person) and/or raise events.
.  The result of the command execution is encapsulated as a `CommandResult` object which is passed back to the `Ui`.

Given below is the Sequence Diagram for interactions within the `Logic` component for the `execute("delete 1")` API call.

.Interactions Inside the Logic Component for the `delete 1` Command
image::DeletePersonSdForLogic.png[width="800"]

[[Design-Model]]
=== Model component

.Structure of the Model Component
image::ModelClassDiagram.png[width="800"]

*API* : link:{repoURL}/src/main/java/seedu/address/model/Model.java[`Model.java`]

The `Model`,

* stores a `UserPref` object that represents the user's preferences.
* stores the CRM Book data.
* exposes an unmodifiable `ObservableList<Person>` that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change.
* does not depend on any of the other three components.

[[Design-Storage]]
=== Storage component

.Structure of the Storage Component
image::StorageClassDiagram.png[width="800"]

*API* : link:{repoURL}/src/main/java/seedu/address/storage/Storage.java[`Storage.java`]

The `Storage` component,

* can save `UserPref` objects in json format and read it back.
* can save the CRM Book data in xml format and read it back.

[[Design-Commons]]
=== Common classes

Classes used by multiple components are in the `seedu.addressbook.commons` package.

== Implementation

This section describes some noteworthy details on how certain features are implemented.

// tag::undoredo[]
=== Undo/Redo feature
==== Current Implementation

The undo/redo mechanism is facilitated by an `UndoRedoStack`, which resides inside `LogicManager`. It supports undoing and redoing of commands that modifies the state of the CRM Book (e.g. `add`, `edit`). Such commands will inherit from `UndoableCommand`.

`UndoRedoStack` only deals with `UndoableCommands`. Commands that cannot be undone will inherit from `Command` instead. The following diagram shows the inheritance diagram for commands:

image::LogicCommandClassDiagram.png[width="800"]

As you can see from the diagram, `UndoableCommand` adds an extra layer between the abstract `Command` class and concrete commands that can be undone, such as the `DeleteCommand`. Note that extra tasks need to be done when executing a command in an _undoable_ way, such as saving the state of the CRM Book before execution. `UndoableCommand` contains the high-level algorithm for those extra tasks while the child classes implements the details of how to execute the specific command. Note that this technique of putting the high-level algorithm in the parent class and lower-level steps of the algorithm in child classes is also known as the https://www.tutorialspoint.com/design_pattern/template_pattern.htm[template pattern].

Commands that are not undoable are implemented this way:
[source,java]
----
public class ListCommand extends Command {
    @Override
    public CommandResult execute() {
        // ... list logic ...
    }
}
----

With the extra layer, the commands that are undoable are implemented this way:
[source,java]
----
public abstract class UndoableCommand extends Command {
    @Override
    public CommandResult execute() {
        // ... undo logic ...

        executeUndoableCommand();
    }
}

public class DeleteCommand extends UndoableCommand {
    @Override
    public CommandResult executeUndoableCommand() {
        // ... delete logic ...
    }
}
----

Suppose that the user has just launched the application. The `UndoRedoStack` will be empty at the beginning.

The user executes a new `UndoableCommand`, `delete 5`, to delete the 5th person in the CRM Book. The current state of the CRM Book is saved before the `delete 5` command executes. The `delete 5` command will then be pushed onto the `undoStack` (the current state is saved together with the command).

image::UndoRedoStartingStackDiagram.png[width="800"]

As the user continues to use the program, more commands are added into the `undoStack`. For example, the user may execute `add n/David ...` to add a new person.

image::UndoRedoNewCommand1StackDiagram.png[width="800"]

[NOTE]
If a command fails its execution, it will not be pushed to the `UndoRedoStack` at all.

The user now decides that adding the person was a mistake, and decides to undo that action using `undo`.

We will pop the most recent command out of the `undoStack` and push it back to the `redoStack`. We will restore the CRM Book to the state before the `add` command executed.

image::UndoRedoExecuteUndoStackDiagram.png[width="800"]

[NOTE]
If the `undoStack` is empty, then there are no other commands left to be undone, and an `Exception` will be thrown when popping the `undoStack`.

The following sequence diagram shows how the undo operation works:

image::UndoRedoSequenceDiagram.png[width="800"]

The redo does the exact opposite (pops from `redoStack`, push to `undoStack`, and restores the CRM Book to the state after the command is executed).

[NOTE]
If the `redoStack` is empty, then there are no other commands left to be redone, and an `Exception` will be thrown when popping the `redoStack`.

The user now decides to execute a new command, `clear`. As before, `clear` will be pushed into the `undoStack`. This time the `redoStack` is no longer empty. It will be purged as it no longer make sense to redo the `add n/David` command (this is the behavior that most modern desktop applications follow).

image::UndoRedoNewCommand2StackDiagram.png[width="800"]

Commands that are not undoable are not added into the `undoStack`. For example, `list`, which inherits from `Command` rather than `UndoableCommand`, will not be added after execution:

image::UndoRedoNewCommand3StackDiagram.png[width="800"]

The following activity diagram summarize what happens inside the `UndoRedoStack` when a user executes a new command:

image::UndoRedoActivityDiagram.png[width="650"]

==== Design Considerations

===== Aspect: Implementation of `UndoableCommand`

* **Alternative 1 (current choice):** Add a new abstract method `executeUndoableCommand()`
** Pros: We will not lose any undone/redone functionality as it is now part of the default behaviour. Classes that deal with `Command` do not have to know that `executeUndoableCommand()` exist.
** Cons: Hard for new developers to understand the template pattern.
* **Alternative 2:** Just override `execute()`
** Pros: Does not involve the template pattern, easier for new developers to understand.
** Cons: Classes that inherit from `UndoableCommand` must remember to call `super.execute()`, or lose the ability to undo/redo.

===== Aspect: How undo & redo executes

* **Alternative 1 (current choice):** Saves the entire CRM Book.
** Pros: Easy to implement.
** Cons: May have performance issues in terms of memory usage.
* **Alternative 2:** Individual command knows how to undo/redo by itself.
** Pros: Will use less memory (e.g. for `delete`, just save the person being deleted).
** Cons: We must ensure that the implementation of each individual command are correct.


===== Aspect: Type of commands that can be undone/redone

* **Alternative 1 (current choice):** Only include commands that modifies the CRM Book (`add`, `clear`, `edit`).
** Pros: We only revert changes that are hard to change back (the view can easily be re-modified as no data are * lost).
** Cons: User might think that undo also applies when the list is modified (undoing filtering for example), * only to realize that it does not do that, after executing `undo`.
* **Alternative 2:** Include all commands.
** Pros: Might be more intuitive for the user.
** Cons: User have no way of skipping such commands if he or she just want to reset the state of the address * book and not the view.
**Additional Info:** See our discussion  https://github.com/se-edu/addressbook-level4/issues/390#issuecomment-298936672[here].


===== Aspect: Data structure to support the undo/redo commands

* **Alternative 1 (current choice):** Use separate stack for undo and redo
** Pros: Easy to understand for new Computer Science student undergraduates to understand, who are likely to be * the new incoming developers of our project.
** Cons: Logic is duplicated twice. For example, when a new command is executed, we must remember to update * both `HistoryManager` and `UndoRedoStack`.
* **Alternative 2:** Use `HistoryManager` for undo/redo
** Pros: We do not need to maintain a separate stack, and just reuse what is already in the codebase.
** Cons: Requires dealing with commands that have already been undone: We must remember to skip these commands. Violates Single Responsibility Principle and Separation of Concerns as `HistoryManager` now needs to do two * different things.
// end::undoredo[]

// tag::remark[]
=== Remark feature
==== Current Implementation

To record more detailed information of a person, a new command `RemarkCommand` is implemented.

The `RemarkCommand` inherits from `UndoableCommands` since it is reasonable to make remark command execute in an _undoable_ way.

`RemarkCommand` which is undoable is implemented this way:
[source,java]
----
public class RemarkCommand extends UndoableCommand {
    @Override
    public CommandResult executeUndoableCommand() {
        // ... remark logic ...
    }
}
----
The following diagram shows the inheritance diagram for `RemarkCommand`.

image::RemarkCommandDiagram.png[width="300"]

The model `Person` is modified to have a new field `Remark`.

The default value of the remark field of a person is an empty string.
A user is not able to assign a remark to a person when adding the person. Therefore, all people in the CRM Book is originally without any remark by default.

The implementation of this command is much like the `EditCommand`.
For example, when a user type `remark 2 r\Likes to swim`. Then the remark field of the 2nd person in the current list will be changed to `Likes to swim`. It’s similar to editing a person’s phone number or address.

The sequence diagram is shown below:

image::RemarkCommandSequenceDiagram.png[width="1000"]

==== Design Considerations

===== Aspect: Implementation of `RemarkCommand`

* **Alternative 1 (current choice):** Add a new `remark` command
** Pros: Treat it as a command may be easy to understand. Only a few people needs a remark.
** Cons: Cannot add a person with remark.
* **Alternative 2:** Just make it a part of `EditCommand` and `AddCommand`
** Pros: Only need to add remark field to every related class. We can add a person with remark.
** Cons: We may have to type too many things when adding a person. Also, some people don’t have any remark.
// end::remark[]

// tag::colortag[]
=== Color Tag feature
==== Current Implementation

To allow easy identification of different tags, a color tag feature is introduced.

A string array is declared in PersonCard.java to include a set of colors for tags.
[source,java]
----
//In PersonCard.java
private static final String[] TAG_COLORS =
        { "blue", "cyan", "green", "magenta", "orange", "pink", "red", "yellow", "teal", "brown" };
----

These colors are defined, with their background color and text color spelled out, in the all the different theme CSS files.

A hash code of the tag name is used to select a color for the tag such that it would remain consistent between different runs of the software.
[source,java]
----
//In PersonCard.java
private String getTagColorFor(String tagName) {
    return TAG_COLORS[Math.abs(tagName.hashCode()) % TAG_COLORS.length];
}

//In PersonCard.java
private void initTags(Person person) {
    person.getTags().forEach(tag -> {
        Label tagLabel = new Label(tag.tagName);
        tagLabel.getStyleClass().add(getTagColorFor(tag.tagName));
        tags.getChildren().add(tagLabel);
    });
}
----
==== Design Considerations

===== Aspect: Implementation of color tags

* **Alternative 1 (current choice):** Assign a color from a predefined list based on tag name
** Pros: No additional commands are needed to generate a color for the tags.
** Cons: User cannot choose a color for the tag.
* **Alternative 2:** Allow user to set a color for the tag
** Pros: Allows more freedom for user customization.
** Cons: Takes more time to implement color tags.
// end::colortag[]

// tag::autocomplete[]
=== Auto-Complete feature
==== Current Implementation

To allow fast typing of commands, auto-complete of commands is implemented.

Auto-complete is implemented through the TextFields feature of ControlsFX.
[source,java]
----
//In CommandBox.java
TextFields.bindAutoCompletion(commandTextField, Messages.AUTOCOMPLETE_FIELD);
----
All the command keywords are included in the AUTOCOMPLETE_FIELD string array.
[source,java]
----
//In Messages.java
public static final String[] AUTOCOMPLETE_FIELD = {
    //all command keywords
    };
----
In addition to all the command keywords, a COMMAND_AUTO_COMPLETE string, with both command word and prefixes, is also included for add command.
[source,java]
----
//In AddCommand.java
public static final String COMMAND_AUTO_COMPLETE = COMMAND_WORD + " " + PREFIX_NAME + " "
        + PREFIX_PHONE + " " + PREFIX_EMAIL + " " + PREFIX_ADDRESS + " " + PREFIX_TAG;
----
==== Design Considerations

===== Aspect: Implementation of Auto-complete

* **Alternative 1 (current choice):** All the commands that contain the typed input are shown. ie. When "a" is typed, both "add" and "clear" will be shown.
** Pros: Allow new user to quickly learn the different command words.
** Cons: When there are a lot of commands, efficiency of auto-complete decreases as user would have too many options to choose from.
* **Alternative 2:** Only commands with the same sequence as the typed input are shown. ie. When "a" is typed, only "add" will be shown.
** Pros: Higher efficiency of auto-complete.
** Cons: New user might find this difficult to use as they are unfamillar with the command words.
// end::autocomplete[]

// tag::leadcontact[]
=== Leads and Contacts feature
==== Current Implementation

People in the CRM Book were stored under a single class with no options for differentiating between two types of classes.

To implement a CRM Book, Leads and Contacts must be differentiated so that they can each hold different fields like a proper CRM Book. To do so, they currently extend the Person class so that all existing functionality associated with Persons will work with both Leads an Contacts. Unique fields will be given their own classes like the original generic fields like Name and Address.

In a CRM Book, users start by adding Leads, who are people they have not sold to yet. As they begin selling, the people who they have sold to become Contacts.

Many existing commands like `AddCommand` have been modified to fit the new paradigm so that it only adds Leads.

A new conversion command `ConvertCommand` has been added to convert Leads into Contacts. The Sequence Diagram is shown:

image::ConvertSequenceDiagram1.png[width="650"]

The `ConvertCommand` class calls the `convertPerson method` in the `ModelManager` class and the Sequence Diagram for the resulting steps are shown below.

image::ConvertSequenceDiagram2.png[width="650"]

When the user has selected a Contact instead of a Lead, an error is thrown with this code:

[source,java]
----
public class ConvertCommand extends UndoableCommand {
    @Override
    protected void preprocessUndoableCommand() throws CommandException {
        // ... get list of Persons ...
        try {
            oldLead = (Lead) lastShownList.get(index.getZeroBased());
        } catch (ClassCastException cce) {
            throw new CommandException(MESSAGE_NOT_CONVERTED);
        }
        newContact = createContact(oldLead);
    }
}
----

It keeps the name, phone, email, address, remarks and tags through the conversion. The company is converted if it exists into an Account. The converted date is set in the Contact.


==== Design Considerations

===== Aspect: Implementation of Leads and Contacts

* **Alternative 1 (current choice):** Extend the existing Person class
** Pros: We will not lose any functionality associated with the Person class.
** Cons: Declarations of Person variables may confuse new developers even as a general class for Leads and Contacts.
* **Alternative 2:** Create two new classes Leads and Contacts
** Pros: Clearly differentiates Leads and Contacts throughout the codebase.
** Cons: We would have to rewrite most objects to take into account the two new classes.


===== Aspect: How conversion will work

* **Alternative 1:** Just convert the basic information. Let user fill in other fields themselves.
** Pros: Easy to implement.
** Cons: User must do extra work.
* **Alternative 2:** Smartly detect which fields can be converted and then do so.
** Pros: User will only need to fix some mistakes in the conversion.
** Cons: Smart detection and conversion needs work to do.
// end::leadcontact[]

// tag::linkedinlogin[]
=== LinkedIn Login Feature
==== Current Implementation

The linkedInLogin mechanism is handled largely by the oAuth2Client interacting with the browser window, which the user will interact with in order to give LinkedIn their username, password, as well as granting the application permission for use.

When the `linkedIn_login` command is called, a `ShowBrowserRequestEvent` will be fired by `LinkedInLoginCommand(Class)` and picked up by the MainWindow.

[source,java]
@Override
    public CommandResult execute() {
        EventsCenter.getInstance().post(new ShowBrowserRequestEvent());
        return new CommandResult(MESSAGE_SUCCESS);
    }

The MainWindow in turn will call the `OAuth2Client(Class)` which will fire up the browser awaiting an authorization code from LinkedIn that will be sent after the user has successfully logged in and granted the CRM Book permission.

[source, java]
@Subscribe
    private void handleLinkedInAuthenticationEvent(ShowBrowserRequestEvent event) {
        logger.info(LogsCenter.getEventHandlingLogMessage(event));
        handleLinkedInAuthentication();
    }

[source, java]
public void handleLinkedInAuthentication() {
    try {
        Oauth2Client.authenticateWithLinkedIn();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

[source, java]
public static void authenticateWithLinkedIn() throws IOException {
    ...
    String urlString = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id="
        + clientId + "&redirect_uri=" + redirectUri + "&state=...";
    bWindow = new BrowserWindow(urlString);
    bWindow.show();
}

Once this has happened, we fire a `HideBrowserRequestEvent` in order to close the browser properly.

The `Decrypter` will then be fired so that we do not store the app secret in plain text. This decision to use a Decrypter class is in the comments section of the Decrypter class, and duplicated here for convenience to the reader.

[source, java]
 // Decrypts the s for use for OAuth
 // While this is not an ideal situation, LinkedIn's OAuth API does not have a client-side authentication flow.
 // This means that it will always require the app s for purposes of authentication.
 // Because of this, building a native (desktop) app that authenticates with LinkedIn is not ideal.
 // However, a number of sites have agreed that if you have to store the key in the code, then obscuring it to make
 // it slightly more difficult for a potential hacker to get it is best. (They will need to run the app rather than
 // just reading the plain text version)
 // This is especially so because a LinkedIn S is not especially valuable, since anyone can create a LinkedIn app.
 // Furthermore the chances of competitors abusing the secret to disable this application is minimal, since it is
 // ultimately, a school project.

[source, java]
public void handleHideBrowser() {
    Oauth2Client.closeBrowser();
    Oauth2Client.getLinkedInS();
}

After the CRM Book has received the authorization code and the app secret from the decrypter, they are sent back to LinkedIn to request for an AccessToken. Once the AccessToken has been received, the user is considered to be successfully logged in, and the accessToken can be used by the CRM Book to make requests to LinkedIn on behalf of the user. The accessToken is also stored in the config.json file for future usage.

[source, java]
config.setAppSecret(accessToken);
ConfigUtil.saveConfig(config, config.DEFAULT_CONFIG_FILE);

The following sequence diagram shows how the linkedIn_login feature works. As seen, it is an events-driven design.

image::LinkedInLoginSequenceDiagram.png[width="800"]

==== Design Considerations
===== Aspect: Storing the LinkedIn App Secret

* **Alternative 1 (current choice):** Slightly encrypting the App Secret
** Pros: Easy to implement, not trivial for attackers to get by scanning the source code.
** Cons: App secret can be derived if the attacker runs the source code
* **Alternative 2:** Store the App Secret in another server, and requesting it with an authentication code
** Pros: Higher security, app secret not stored on GitHub
** Cons: Significantly harder to implement. Requires user to have a username and password for the server not stored on GitHub.
* **Alternative 3:** Store the App Secret in plain text
** Pros: Much easier to code and implement
** Cons: Bad security, secret will likely end up in a paste database somewhere in the internet
// end::linkedinlogin[]

// tag::linkedinshare[]
=== Share to LinkedIn Feature
==== Current Implementation

When the linkedin_share command is executed, it will call the Config class to get a current copy of the configurations used by the Application. It will also set the boolean value of postSuccess to false. This boolean value will be used to determine if we managed to successfully post to LinkedIn.

[source, java]
public static void postToLinkedIn() {
    Config config = Config.setupConfig();
    postSuccess = false;

Next, we create a JSON Object that LinkedIn requires, specifying the visibility (privacy) of the post, and the actual content of the post. By default, we set the visibility to be 'anyone', or in Facebook terms, 'Public'. An overview on LinkedIn's share API can be found at https://developer.linkedin.com/docs/share-on-linkedin

With the JSON Object and the access_token taken from the user's configuration file, we create a HttpPost Object and HttpClient Object, send it to LinkedIn, and analyze the response. In particular, if the response contains an updateUrl, it means that the post has been successfully posted, and we update the boolean value of postSuccess to true.

[source, java]
HttpPost httppost = getHttpPostObject(jsonToSend, accessToken);
HttpClient httpclient = getHttpClientObject();
JSONObject linkedInResponse = sendHttpRequestToLinkedIn(httppost, httpclient);
logger.info("LinkedIn Response is : " + linkedInResponse.toString());
if (linkedInResponse.has("updateUrl") || linkedInResponse.has("updateURL")) {
    //if has updateURL then it successfully got posted
    logger.info("Post has been successfully posted");
    postSuccess = true;
}

Finally we use the postSuccess value to determine if we send a success or failed message to the user.

The following sequence diagram shows how the command works

image::LinkedInShareSequenceDiagram.png[width="800"]

==== Design Considerations
===== Aspect: Allowing salesperson to set privacy level of their post

* **Alternative 1 (current choice):** Only option is 'anyone'
** Pros: Salesperson always wants to share to as many people as possible. Reduces complexity of command and/or save on a command to set a default level of visibility.
** Cons: Salesperson is limited to only posting public posts using CRM Book
* **Alternative 2:** Allow salesperson to set a default visibility option using another command
** Pros: Salesperson has greater flexibility in setting the visibility type of their post.
** Cons: Have to write a new command that may not be used.
* **Alternative 3:** Allow salesperson to specify visibility in share command
** Pros: Salesperson has the greatest level flexibility in setting the visibility type of their post.
** Cons: Increases complexity of the command
// end::linkedinshare[]

// tag::settingGoogleLocation[]
=== Saving a location for Google Maps
==== Current Implementation

To save a location in Google Maps, it does not matter whether CRM Book already has a pre-existing address. Rather, we always overwrite the config file to be updated with the latest address.

[source, java]
Config initializedConfig = Config.setupConfig();
initializedConfig.setUserLocation(address.toString());

The following sequence diagram shows how the command works

image::SaveGoogleLocationSequenceDiagram.png[width="800"]
// end::settingGoogleLocation[]

// tag::viewDirections[]
=== View directions to a Client's office
==== Current Implementation

The current implementation of this feature is the same as when a person card is changed (Like the select command). The difference is that if the config file states that a user's office location has been set, then load Google maps instead of doing a Google Search.

[source, java]
@Subscribe
private void handlePersonPanelSelectionChangedEvent(PersonPanelSelectionChangedEvent event) {
    getConfig();
    logger.info(LogsCenter.getEventHandlingLogMessage(event));
    //if person has no home location set
    if (config.getUserLocation() == null || config.getUserLocation().length() == 0) {
        logger.info("No office location set, doing Google search");
        loadPersonPage(event.getNewSelection().person);
    } else {
        String url = generateUrl(config.getUserLocation(), event.getNewSelection().person.getAddress().toString());
        logger.info("Office location set, Load Google Maps. URL IS " + url);
        loadPage(url);
    }
}

The following sequence diagram shows how this feature works. The select command is used only if the user activated it via commandline. However, clicking on another person card without using the select command will work as well.

image::LoadGoogleMapsSequenceDiagram.png[width="800"]

// end::viewDirections[]

// tag::bulkimport[]
=== Bulk Import Feature
==== Current Implementation

To add a large number of persons to the CRM Book at the same time, a new command `ImportCommand` is implemented.

The `ImportCommand` inherits from `Command`. It is implemented this way:
[source, java]
----
public class ImportCommand extends Command {
    @Override
    public CommandResult execute() {
        // … import logic …
    }
}
----

When an `ImportCommand` is called, the corresponding CSV file will be processed. Then persons will be added to CRM Book automatically like what a `AddCommand` can do but without manual typing.

The sequence diagram is shown below:

image::ImportCommandSequenceDiagram.png[width="1000"]

==== Design Considerations

===== Aspect: CSV file format

* **Alternative 1 (current choice):** Requires the CSV file to follow the given format
** Pros: Easy to implement. No need to analyze too much about the file.
** Cons: More work for users.
* **Alternative 2:** Allow attributes not in order and allow different names for attributes
** Pros: Hard to detect and implement.
** Cons: More flexible to users. Can help users save time.
// end::bulkimport[]


=== Logging

We are using `java.util.logging` package for logging. The `LogsCenter` class is used to manage the logging levels and logging destinations.

* The logging level can be controlled using the `logLevel` setting in the configuration file (See <<Implementation-Configuration>>)
* The `Logger` for a class can be obtained using `LogsCenter.getLogger(Class)` which will log messages according to the specified logging level
* Currently log messages are output through: `Console` and to a `.log` file.

*Logging Levels*

* `SEVERE` : Critical problem detected which may possibly cause the termination of the application
* `WARNING` : Can continue, but with caution
* `INFO` : Information showing the noteworthy actions by the App
* `FINE` : Details that is not usually noteworthy but may be useful in debugging e.g. print the actual list instead of just its size

[[Implementation-Configuration]]
=== Configuration

Certain properties of the application can be controlled (e.g App name, logging level) through the configuration file (default: `config.json`).

// tag::alias[]
=== Alias Commands feature
==== Current Implementation

A command can be performed by typing in its alias rather than the word. +
The following is an example of implementing the alias command for the list command: +
[source, java]
----
public class ListCommand extends Command {

    public static final String COMMAND_WORD = "list";
    //@@author Sheikh-Umar
    public static final String COMMAND_ALIAS = "l";
    //@@author

    public static final String MESSAGE_SUCCESS = "Listed all Leads and Contacts";


    @Override
    public CommandResult execute() {
        model.updateFilteredPersonList(PREDICATE_SHOW_ALL_PERSONS);
        return new CommandResult(MESSAGE_SUCCESS);
    }
}
----

The alias command for all other commands will follow a similar implementation. +

==== Design Considerations
===== Aspect: How to implement the alias command for all commands
The feature is implemented by adding the alias of the command into its respective java document, and updating the AddressBookParser java document. +
The feature is implemented this way to utilise the command java documents that are available as opposed to creating a new java document for a certain alias. +

This feature is implemented to allow a user to enter a command without specifying the entire word of the command. +
// end::alias[]

// tag::duplicate[]
=== Identifying a Duplicate feature
==== Current Implementation
The CRM Book will ensure that every Lead and Contact stored is a non-duplicate. +

The feature is implemented by checking the phone number and email address of a new Lead with all of the phone numbers and email addresses of all leads and contacts currently in the CRM-Book. +

The feature will be implemented on the add command because the current application detects duplicates at the add command. +
The following is how the feature will be implemented: +
[source, java]
----
public boolean contains(Person toCheck) {
        requireNonNull(toCheck);
        for (int i = 0; i < internalList.size(); i++) {
            Person current = internalList.get(i);
            if (current.getPhone().equals(toCheck.getPhone())
                    || current.getEmail().equals(toCheck.getEmail())) {
                return true;
            }
        }
        return false;
    }
----

The phone number and email address of a Lead will be checked in the list of all Leads and Contacts.
If either the phone number of email address of the Lead to be added is found in the list,
the CRM application will display a message that the lead is a duplicate and will reject this lead.

The following activity diagram shows how the operation of identifying a duplicate lead works:

image::DetectDuplicateActivityDiagram.png[width="800"]

==== Design Considerations
===== Aspect: How to implement identifying a duplicate
* **Alternative 1 (current choice):** Iterate through all Leads and Contacts in CRM-Book.
** Pros: Search will be performed in linear time, and enhances an existing portion of code.
// end::duplicate[]

// tag::addparentcompanytag[]
=== Adding a Parent Company tag feature [Coming in v2.0]
==== Current Implementation
It is possible that the user may want to keep track of the companies associated with the Leads and Contacts in the CRM Book.
For example, Skype and Nokia are two different companies whose parent company is Microsoft.
Hence, every Lead and Contact will have an additional tag named after the parent company if their company has a parent company.
The following activity diagram illustrates how this will be implemented:

image::AddParentCompanyTagActivityDiagram.png[width="800"]

==== Design Considerations
===== Aspect: How adding a Parent Company tag feature works
* **Alternative 1 (current choice):** If the user updated the Company of a Lead or Contact, the CRM Book determines if this company has a parent company using a Google search.
If yes, it automatically adds a tag to this Lead or Contact labelled as the parent company of the company of the Lead or Contact.
// end::addparentcompanytag[]

// tag::display[]
=== Displaying Lead list and Contact list feature
==== Current Implementation
The CRM Book will be able to list out all Leads and Contacts separately.

The feature is implemented by checking on the type of the persons already stored in the CRM, and displaying all persons that match the keyword (either Lead or Contact) that the user enters. +

The feature is implemented through the DisplayCommand, which is based on FindCommand.
Hence, the DisplayCommand will operate similarly as the FindCommand, with the only difference being the DisplayCommand searches for all Leads or Contacts already in the CRM Book. +

The `DisplayCommand` inherits from `Command`. It is implemented this way:
[source, java]
----
public class DisplayCommand extends Command {
    @Override
    public CommandResult execute() {
        // … import logic …
    }
}
----

The following activity diagram shows how the operation of displaying the Leads or Contacts list works:

image::DisplayListOfACertainTypeActivityDiagram.png[width="800"]

==== Design Considerations
===== Aspect: How displaying Lead list and Contact list works

* **Alternative 1 (current choice):** Iterate through the CRM Book for persons that match the keyword that user entered just like the FindCommand.
** Pros: Iteration will be performed in linear time, and utilises the functionality of the FindCommand.
// end::display[]

// tag::findbyphonenumberandemailaddress[]
=== Enhancement of Find Command feature
==== Reason for Implementation
The user may want to search for Leads and Contacts based on phone numbers and email addresses rather than names.

==== Current Implementation
The CRM Book currently searches for a Lead or Contact based on their name.

This command can be further improved by being able to find phone numbers and email addresses. +

The following is how the feature will be implemented:
[source, java]
----
public boolean test(Person person) {
         return keywords.stream().anyMatch(keyword -> StringUtil.containsWordIgnoreCase(person.getName().fullName, keyword)                .anyMatch(keyword -> StringUtil.containsWordIgnoreCase(person.getName().fullName, keyword)
                        || StringUtil.containsWordIgnoreCase(person.getPhone().value, keyword)
                        || StringUtil.containsWordIgnoreCase(person.getEmail().value, keyword));
     }
 }
----

The phone number and email address that the user entered will be checked in the list of all Leads and Contacts.
If either the phone number of email address is found in the list,
the CRM Book will display the Leads and/or Contacts that match the keywords entered.
If not, the CRM Book will display zero Leads and Contacts found.

==== Design Considerations
===== Aspect: How to implement finding phone numbers and email addresses
* **Alternative 1 (current choice):** Edit the current search implementation to include finding phone numbers and email addresses.
** Pros: Search will be performed in linear time, and utilises an existing portion of code.
// end::findbyphonenumberandemailaddress[]

// tag::changeTheme[]
=== Change Theme feature
==== Reason for implementation
CRM Book users are expected to spent long period of time on the software and under different light settings. Change theme allows users to switch between light and dark theme. This would prevent eye fatigue.

==== Current implementation
The sequence diagram below shows the interactions of change theme command within the logic component.

image::ChangeThemeLogicComponentSequenceDiagram.png[width="800"]

The sequence diagram below shows the interactions between different components of CRM Book for change theme command.

image::ChangeThemeHighLevelSequenceDiagrams.png[width="800"]

Every change theme command will post a ChangeThemeRequestEvent to EventCenter. When this event is handled, the UI will be updated to display the chosen theme. In addition, the themeFilePath in user prefs is updated with the chosen theme file path.
Currently, there are three themes, namely blue, light and dark. The CSS files of these themes are referenced in Theme class as strings.
The following piece of code demonstrates how the CSS files are referenced in Theme class:
----
//in Theme.java
    public static final String DEFAULT_THEME_FILE_PATH = "/view/BlueTheme.css";
    public static final String DARK_THEME_FILE_PATH = "/view/DarkTheme.css";
    public static final String LIGHT_THEME_FILE_PATH = "/view/LightTheme.css";
----

There is a method in Theme class to convert theme name into theme file path.
----
//in Theme.java
    public String convertThemeToFilePath() {
            switch (this.theme) {
            case DARK_THEME:
                return DARK_THEME_FILE_PATH;
            //other cases
            }
        }
----
This method is used to check if the chosen theme is equals to the current theme by comparing the file path of the chosen theme with the file path in user prefs.

If the chosen theme is not equals to the current theme, the ChangeThemeRequestEvent will be handle in MainWindow class.
----
//in MainWindow.java
public void handleChangeTheme(String theme) {
        String fullPath = getFullPath(this.themeFilePath);
        primaryStage.getScene().getStylesheets().remove(fullPath);

        switch (theme) {
        case Theme.LIGHT_THEME:
            this.themeFilePath = Theme.LIGHT_THEME_FILE_PATH;
            break;
        case Theme.DARK_THEME:
            this.themeFilePath = Theme.DARK_THEME_FILE_PATH;
            break;
        case Theme.BLUE_THEME:
            this.themeFilePath = Theme.BLUE_THEME_FILE_PATH;
            break;
        default:
            //this will not happen
        }

        prefs.getGuiSettings().setThemeFilePath(this.themeFilePath);
        fullPath = getFullPath(this.themeFilePath);
        primaryStage.getScene().getStylesheets().add(fullPath);
    }
----
This method updates the theme file path in the primary scene in 3 steps: +

. Removes the current theme file path from primary scene.
. Updates the theme file path
. Adds the new theme file path into primary scene.

In addition, the updated theme file path is written into user prefs. +

A switch case statement is used to update the new theme file path. This implementation allows easy extension of the feature; i.e. when a new theme is created, it can be easily added as a case.

// end::changeTheme[]

== Documentation

We use asciidoc for writing documentation.

[NOTE]
We chose asciidoc over Markdown because asciidoc, although a bit more complex than Markdown, provides more flexibility in formatting.

=== Editing Documentation

See <<UsingGradle#rendering-asciidoc-files, UsingGradle.adoc>> to learn how to render `.adoc` files locally to preview the end result of your edits.
Alternatively, you can download the AsciiDoc plugin for IntelliJ, which allows you to preview the changes you have made to your `.adoc` files in real-time.

=== Publishing Documentation

See <<UsingTravis#deploying-github-pages, UsingTravis.adoc>> to learn how to deploy GitHub Pages using Travis.

=== Converting Documentation to PDF format

We use https://www.google.com/chrome/browser/desktop/[Google Chrome] for converting documentation to PDF format, as Chrome's PDF engine preserves hyperlinks used in webpages.

Here are the steps to convert the project documentation files to PDF format.

.  Follow the instructions in <<UsingGradle#rendering-asciidoc-files, UsingGradle.adoc>> to convert the AsciiDoc files in the `docs/` directory to HTML format.
.  Go to your generated HTML files in the `build/docs` folder, right click on them and select `Open with` -> `Google Chrome`.
.  Within Chrome, click on the `Print` option in Chrome's menu.
.  Set the destination to `Save as PDF`, then click `Save` to save a copy of the file in PDF format. For best results, use the settings indicated in the screenshot below.

.Saving documentation as PDF files in Chrome
image::chrome_save_as_pdf.png[width="300"]

[[Testing]]
== Testing

=== Running Tests

There are three ways to run tests.

[TIP]
The most reliable way to run tests is the 3rd one. The first two methods might fail some GUI tests due to platform/resolution-specific idiosyncrasies.

*Method 1: Using IntelliJ JUnit test runner*

* To run all tests, right-click on the `src/test/java` folder and choose `Run 'All Tests'`
* To run a subset of tests, you can right-click on a test package, test class, or a test and choose `Run 'ABC'`

*Method 2: Using Gradle*

* Open a console and run the command `gradlew clean allTests` (Mac/Linux: `./gradlew clean allTests`)

[NOTE]
See <<UsingGradle#, UsingGradle.adoc>> for more info on how to run tests using Gradle.

*Method 3: Using Gradle (headless)*

Thanks to the https://github.com/TestFX/TestFX[TestFX] library we use, our GUI tests can be run in the _headless_ mode. In the headless mode, GUI tests do not show up on the screen. That means the developer can do other things on the Computer while the tests are running.

To run tests in headless mode, open a console and run the command `gradlew clean headless allTests` (Mac/Linux: `./gradlew clean headless allTests`)

=== Types of tests

We have two types of tests:

.  *GUI Tests* - These are tests involving the GUI. They include,
.. _System Tests_ that test the entire App by simulating user actions on the GUI. These are in the `systemtests` package.
.. _Unit tests_ that test the individual components. These are in `seedu.address.ui` package.
.  *Non-GUI Tests* - These are tests not involving the GUI. They include,
..  _Unit tests_ targeting the lowest level methods/classes. +
e.g. `seedu.address.commons.StringUtilTest`
..  _Integration tests_ that are checking the integration of multiple code units (those code units are assumed to be working). +
e.g. `seedu.address.storage.StorageManagerTest`
..  Hybrids of unit and integration tests. These test are checking multiple code units as well as how the are connected together. +
e.g. `seedu.address.logic.LogicManagerTest`


=== Troubleshooting Testing
**Problem: `HelpWindowTest` fails with a `NullPointerException`.**

* Reason: One of its dependencies, `UserGuide.html` in `src/main/resources/docs` is missing.
* Solution: Execute Gradle task `processResources`.

== Dev Ops

=== Build Automation

See <<UsingGradle#, UsingGradle.adoc>> to learn how to use Gradle for build automation.

=== Continuous Integration

We use https://travis-ci.org/[Travis CI] and https://www.appveyor.com/[AppVeyor] to perform _Continuous Integration_ on our projects. See <<UsingTravis#, UsingTravis.adoc>> and <<UsingAppVeyor#, UsingAppVeyor.adoc>> for more details.

=== Coverage Reporting

We use https://coveralls.io/[Coveralls] to track the code coverage of our projects. See <<UsingCoveralls#, UsingCoveralls.adoc>> for more details.

=== Documentation Previews
When a pull request has changes to asciidoc files, you can use https://www.netlify.com/[Netlify] to see a preview of how the HTML version of those asciidoc files will look like when the pull request is merged. See <<UsingNetlify#, UsingNetlify.adoc>> for more details.

=== Making a Release

Here are the steps to create a new release.

.  Update the version number in link:{repoURL}/src/main/java/seedu/address/MainApp.java[`MainApp.java`].
.  Generate a JAR file <<UsingGradle#creating-the-jar-file, using Gradle>>.
.  Tag the repo with the version number. e.g. `v0.1`
.  https://help.github.com/articles/creating-releases/[Create a new release using GitHub] and upload the JAR file you created.

=== Managing Dependencies

A project often depends on third-party libraries. For example, CRM Book depends on the http://wiki.fasterxml.com/JacksonHome[Jackson library] for XML parsing. Managing these _dependencies_ can be automated using Gradle. For example, Gradle can download the dependencies automatically, which is better than these alternatives. +
a. Include those libraries in the repo (this bloats the repo size) +
b. Require developers to download those libraries manually (this creates extra work for developers)

[[GetStartedProgramming]]
[appendix]
== Suggested Programming Tasks to Get Started

Suggested path for new programmers:

1. First, add small local-impact (i.e. the impact of the change does not go beyond the component) enhancements to one component at a time. Some suggestions are given in <<GetStartedProgramming-EachComponent>>.

2. Next, add a feature that touches multiple components to learn how to implement an end-to-end feature across all components. <<GetStartedProgramming-RemarkCommand>> explains how to go about adding such a feature.

[[GetStartedProgramming-EachComponent]]
=== Improving each component

Each individual exercise in this section is component-based (i.e. you would not need to modify the other components to get it to work).

[discrete]
==== `Logic` component

*Scenario:* You are in charge of `logic`. During dog-fooding, your team realize that it is troublesome for the user to type the whole command in order to execute a command. Your team devise some strategies to help cut down the amount of typing necessary, and one of the suggestions was to implement aliases for the command words. Your job is to implement such aliases.

[TIP]
Do take a look at <<Design-Logic>> before attempting to modify the `Logic` component.

. Add a shorthand equivalent alias for each of the individual commands. For example, besides typing `clear`, the user can also type `c` to remove all persons in the list.
+
****
* Hints
** Just like we store each individual command word constant `COMMAND_WORD` inside `*Command.java` (e.g.  link:{repoURL}/src/main/java/seedu/address/logic/commands/FindCommand.java[`FindCommand#COMMAND_WORD`], link:{repoURL}/src/main/java/seedu/address/logic/commands/DeleteCommand.java[`DeleteCommand#COMMAND_WORD`]), you need a new constant for aliases as well (e.g. `FindCommand#COMMAND_ALIAS`).
** link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] is responsible for analyzing command words.
* Solution
** Modify the switch statement in link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser#parseCommand(String)`] such that both the proper command word and alias can be used to execute the same intended command.
** Add new tests for each of the aliases that you have added.
** Update the user guide to document the new aliases.
** See this https://github.com/se-edu/addressbook-level4/pull/785[PR] for the full solution.
****

[discrete]
==== `Model` component

*Scenario:* You are in charge of `model`. One day, the `logic`-in-charge approaches you for help. He wants to implement a command such that the user is able to remove a particular tag from everyone in the CRM Book, but the model API does not support such a functionality at the moment. Your job is to implement an API method, so that your teammate can use your API to implement his command.

[TIP]
Do take a look at <<Design-Model>> before attempting to modify the `Model` component.

. Add a `removeTag(Tag)` method. The specified tag will be removed from everyone in the CRM Book.
+
****
* Hints
** The link:{repoURL}/src/main/java/seedu/address/model/Model.java[`Model`] and the link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] API need to be updated.
** Think about how you can use SLAP to design the method. Where should we place the main logic of deleting tags?
**  Find out which of the existing API methods in  link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] and link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] classes can be used to implement the tag removal logic. link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] allows you to update a person, and link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] allows you to update the tags.
* Solution
** Implement a `removeTag(Tag)` method in link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`]. Loop through each person, and remove the `tag` from each person.
** Add a new API method `deleteTag(Tag)` in link:{repoURL}/src/main/java/seedu/address/model/ModelManager.java[`ModelManager`]. Your link:{repoURL}/src/main/java/seedu/address/model/ModelManager.java[`ModelManager`] should call `AddressBook#removeTag(Tag)`.
** Add new tests for each of the new public methods that you have added.
** See this https://github.com/se-edu/addressbook-level4/pull/790[PR] for the full solution.
*** The current codebase has a flaw in tags management. Tags no longer in use by anyone may still exist on the link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`]. This may cause some tests to fail. See issue  https://github.com/se-edu/addressbook-level4/issues/753[`#753`] for more information about this flaw.
*** The solution PR has a temporary fix for the flaw mentioned above in its first commit.
****

[discrete]
==== `Ui` component

*Scenario:* You are in charge of `ui`. During a beta testing session, your team is observing how the users use your CRM Book application. You realize that one of the users occasionally tries to delete non-existent tags from a contact, because the tags all look the same visually, and the user got confused. Another user made a typing mistake in his command, but did not realize he had done so because the error message wasn't prominent enough. A third user keeps scrolling down the list, because he keeps forgetting the index of the last person in the list. Your job is to implement improvements to the UI to solve all these problems.

[TIP]
Do take a look at <<Design-Ui>> before attempting to modify the `UI` component.

. Use different colors for different tags inside person cards. For example, `friends` tags can be all in brown, and `colleagues` tags can be all in yellow.
+
**Before**
+
image::getting-started-ui-tag-before.png[width="300"]
+
**After**
+
image::getting-started-ui-tag-after.png[width="300"]
+
****
* Hints
** The tag labels are created inside link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[the `PersonCard` constructor] (`new Label(tag.tagName)`). https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Label.html[JavaFX's `Label` class] allows you to modify the style of each Label, such as changing its color.
** Use the .css attribute `-fx-background-color` to add a color.
** You may wish to modify link:{repoURL}/src/main/resources/view/DarkTheme.css[`DarkTheme.css`] to include some pre-defined colors using css, especially if you have experience with web-based css.
* Solution
** You can modify the existing test methods for `PersonCard` 's to include testing the tag's color as well.
** See this https://github.com/se-edu/addressbook-level4/pull/798[PR] for the full solution.
*** The PR uses the hash code of the tag names to generate a color. This is deliberately designed to ensure consistent colors each time the application runs. You may wish to expand on this design to include additional features, such as allowing users to set their own tag colors, and directly saving the colors to storage, so that tags retain their colors even if the hash code algorithm changes.
****

. Modify link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] such that link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay`] can show a different style on error (currently it shows the same regardless of errors).
+
**Before**
+
image::getting-started-ui-result-before.png[width="200"]
+
**After**
+
image::getting-started-ui-result-after.png[width="200"]
+
****
* Hints
** link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] is raised by link:{repoURL}/src/main/java/seedu/address/ui/CommandBox.java[`CommandBox`] which also knows whether the result is a success or failure, and is caught by link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay`] which is where we want to change the style to.
** Refer to link:{repoURL}/src/main/java/seedu/address/ui/CommandBox.java[`CommandBox`] for an example on how to display an error.
* Solution
** Modify link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] 's constructor so that users of the event can indicate whether an error has occurred.
** Modify link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay#handleNewResultAvailableEvent(NewResultAvailableEvent)`] to react to this event appropriately.
** You can write two different kinds of tests to ensure that the functionality works:
*** The unit tests for `ResultDisplay` can be modified to include verification of the color.
*** The system tests link:{repoURL}/src/test/java/systemtests/AddressBookSystemTest.java[`AddressBookSystemTest#assertCommandBoxShowsDefaultStyle() and AddressBookSystemTest#assertCommandBoxShowsErrorStyle()`] to include verification for `ResultDisplay` as well.
** See this https://github.com/se-edu/addressbook-level4/pull/799[PR] for the full solution.
*** Do read the commits one at a time if you feel overwhelmed.
****

. Modify the link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] to show the total number of people in the CRM Book.
+
**Before**
+
image::getting-started-ui-status-before.png[width="500"]
+
**After**
+
image::getting-started-ui-status-after.png[width="500"]
+
****
* Hints
** link:{repoURL}/src/main/resources/view/StatusBarFooter.fxml[`StatusBarFooter.fxml`] will need a new `StatusBar`. Be sure to set the `GridPane.columnIndex` properly for each `StatusBar` to avoid misalignment!
** link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] needs to initialize the status bar on application start, and to update it accordingly whenever the CRM Book is updated.
* Solution
** Modify the constructor of link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] to take in the number of persons when the application just started.
** Use link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter#handleAddressBookChangedEvent(AddressBookChangedEvent)`] to update the number of persons whenever there are new changes to the addressbook.
** For tests, modify link:{repoURL}/src/test/java/guitests/guihandles/StatusBarFooterHandle.java[`StatusBarFooterHandle`] by adding a state-saving functionality for the total number of people status, just like what we did for save location and sync status.
** For system tests, modify link:{repoURL}/src/test/java/systemtests/AddressBookSystemTest.java[`AddressBookSystemTest`] to also verify the new total number of persons status bar.
** See this https://github.com/se-edu/addressbook-level4/pull/803[PR] for the full solution.
****

[discrete]
==== `Storage` component

*Scenario:* You are in charge of `storage`. For your next project milestone, your team plans to implement a new feature of saving the CRM Book to the cloud. However, the current implementation of the application constantly saves the CRM Book after the execution of each command, which is not ideal if the user is working on limited internet connection. Your team decided that the application should instead save the changes to a temporary local backup file first, and only upload to the cloud after the user closes the application. Your job is to implement a backup API for the CRM Book storage.

[TIP]
Do take a look at <<Design-Storage>> before attempting to modify the `Storage` component.

. Add a new method `backupAddressBook(ReadOnlyAddressBook)`, so that the CRM Book can be saved in a fixed temporary location.
+
****
* Hint
** Add the API method in link:{repoURL}/src/main/java/seedu/address/storage/AddressBookStorage.java[`AddressBookStorage`] interface.
** Implement the logic in link:{repoURL}/src/main/java/seedu/address/storage/StorageManager.java[`StorageManager`] and link:{repoURL}/src/main/java/seedu/address/storage/XmlAddressBookStorage.java[`XmlAddressBookStorage`] class.
* Solution
** See this https://github.com/se-edu/addressbook-level4/pull/594[PR] for the full solution.
****

[[GetStartedProgramming-RemarkCommand]]
=== Creating a new command: `remark`

By creating this command, you will get a chance to learn how to implement a feature end-to-end, touching all major components of the app.

*Scenario:* You are a software maintainer for `addressbook`, as the former developer team has moved on to new projects. The current users of your application have a list of new feature requests that they hope the software will eventually have. The most popular request is to allow adding additional comments/notes about a particular contact, by providing a flexible `remark` field for each contact, rather than relying on tags alone. After designing the specification for the `remark` command, you are convinced that this feature is worth implementing. Your job is to implement the `remark` command.

==== Description
Edits the remark for a person specified in the `INDEX`. +
Format: `remark INDEX r/[REMARK]`

Examples:

* `remark 1 r/Likes to drink coffee.` +
Edits the remark for the first person to `Likes to drink coffee.`
* `remark 1 r/` +
Removes the remark for the first person.

==== Step-by-step Instructions

===== [Step 1] Logic: Teach the app to accept 'remark' which does nothing
Let's start by teaching the application how to parse a `remark` command. We will add the logic of `remark` later.

**Main:**

. Add a `RemarkCommand` that extends link:{repoURL}/src/main/java/seedu/address/logic/commands/UndoableCommand.java[`UndoableCommand`]. Upon execution, it should just throw an `Exception`.
. Modify link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] to accept a `RemarkCommand`.

**Tests:**

. Add `RemarkCommandTest` that tests that `executeUndoableCommand()` throws an Exception.
. Add new test method to link:{repoURL}/src/test/java/seedu/address/logic/parser/AddressBookParserTest.java[`AddressBookParserTest`], which tests that typing "remark" returns an instance of `RemarkCommand`.

===== [Step 2] Logic: Teach the app to accept 'remark' arguments
Let's teach the application to parse arguments that our `remark` command will accept. E.g. `1 r/Likes to drink coffee.`

**Main:**

. Modify `RemarkCommand` to take in an `Index` and `String` and print those two parameters as the error message.
. Add `RemarkCommandParser` that knows how to parse two arguments, one index and one with prefix 'r/'.
. Modify link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] to use the newly implemented `RemarkCommandParser`.

**Tests:**

. Modify `RemarkCommandTest` to test the `RemarkCommand#equals()` method.
. Add `RemarkCommandParserTest` that tests different boundary values
for `RemarkCommandParser`.
. Modify link:{repoURL}/src/test/java/seedu/address/logic/parser/AddressBookParserTest.java[`AddressBookParserTest`] to test that the correct command is generated according to the user input.

===== [Step 3] Ui: Add a placeholder for remark in `PersonCard`
Let's add a placeholder on all our link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] s to display a remark for each person later.

**Main:**

. Add a `Label` with any random text inside link:{repoURL}/src/main/resources/view/PersonListCard.fxml[`PersonListCard.fxml`].
. Add FXML annotation in link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] to tie the variable to the actual label.

**Tests:**

. Modify link:{repoURL}/src/test/java/guitests/guihandles/PersonCardHandle.java[`PersonCardHandle`] so that future tests can read the contents of the remark label.

===== [Step 4] Model: Add `Remark` class
We have to properly encapsulate the remark in our link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] class. Instead of just using a `String`, let's follow the conventional class structure that the codebase already uses by adding a `Remark` class.

**Main:**

. Add `Remark` to model component (you can copy from link:{repoURL}/src/main/java/seedu/address/model/person/Address.java[`Address`], remove the regex and change the names accordingly).
. Modify `RemarkCommand` to now take in a `Remark` instead of a `String`.

**Tests:**

. Add test for `Remark`, to test the `Remark#equals()` method.

===== [Step 5] Model: Modify `Person` to support a `Remark` field
Now we have the `Remark` class, we need to actually use it inside link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`].

**Main:**

. Add `getRemark()` in link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`].
. You may assume that the user will not be able to use the `add` and `edit` commands to modify the remarks field (i.e. the person will be created without a remark).
. Modify link:{repoURL}/src/main/java/seedu/address/model/util/SampleDataUtil.java/[`SampleDataUtil`] to add remarks for the sample data (delete your `addressBook.xml` so that the application will load the sample data when you launch it.)

===== [Step 6] Storage: Add `Remark` field to `XmlAdaptedPerson` class
We now have `Remark` s for `Person` s, but they will be gone when we exit the application. Let's modify link:{repoURL}/src/main/java/seedu/address/storage/XmlAdaptedPerson.java[`XmlAdaptedPerson`] to include a `Remark` field so that it will be saved.

**Main:**

. Add a new Xml field for `Remark`.

**Tests:**

. Fix `invalidAndValidPersonAddressBook.xml`, `typicalPersonsAddressBook.xml`, `validAddressBook.xml` etc., such that the XML tests will not fail due to a missing `<remark>` element.

===== [Step 6b] Test: Add withRemark() for `PersonBuilder`
Since `Person` can now have a `Remark`, we should add a helper method to link:{repoURL}/src/test/java/seedu/address/testutil/PersonBuilder.java[`PersonBuilder`], so that users are able to create remarks when building a link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`].

**Tests:**

. Add a new method `withRemark()` for link:{repoURL}/src/test/java/seedu/address/testutil/PersonBuilder.java[`PersonBuilder`]. This method will create a new `Remark` for the person that it is currently building.
. Try and use the method on any sample `Person` in link:{repoURL}/src/test/java/seedu/address/testutil/TypicalPersons.java[`TypicalPersons`].

===== [Step 7] Ui: Connect `Remark` field to `PersonCard`
Our remark label in link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] is still a placeholder. Let's bring it to life by binding it with the actual `remark` field.

**Main:**

. Modify link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`]'s constructor to bind the `Remark` field to the `Person` 's remark.

**Tests:**

. Modify link:{repoURL}/src/test/java/seedu/address/ui/testutil/GuiTestAssert.java[`GuiTestAssert#assertCardDisplaysPerson(...)`] so that it will compare the now-functioning remark label.

===== [Step 8] Logic: Implement `RemarkCommand#execute()` logic
We now have everything set up... but we still can't modify the remarks. Let's finish it up by adding in actual logic for our `remark` command.

**Main:**

. Replace the logic in `RemarkCommand#execute()` (that currently just throws an `Exception`), with the actual logic to modify the remarks of a person.

**Tests:**

. Update `RemarkCommandTest` to test that the `execute()` logic works.

==== Full Solution

See this https://github.com/se-edu/addressbook-level4/pull/599[PR] for the step-by-step solution.

[appendix]
== Product Scope

*Target user profile*:

* Salespeople
* has a need to manage a significant number of people into either Leads or Contacts
* prefer desktop apps over other types
* can type fast
* prefers typing over mouse input
* is reasonably comfortable using CLI apps

=== Feature contributions:

David Ten: +
**Major Feature** : LinkedIn Synchronize

* Allows a Salesperson to connect his LinkedIn account to the application +
* Allows Contacts to be connected to their respective LinkedIn account


**Major Feature** : Alert for change of Account

* Allows a Salesperson to be alerted when one of their Contacts move companies +
* This allows them to sell to a new account using their old Contact.

Umar: +
**Major feature** : Added duplicate detection and display list of Leads and Contacts

* Implement duplicate detection by verifying the whether the phone number or email address of a Lead to be entered matches any of the phone numbers or email addresses
currently stored in the CRM Book.
* Implement the display of Leads list and Contacts list separately at the salesperson's request.

**Minor feature** : Command Alias

* Ensures that commands can be performed using its alias. +
* In the sales industry, a person may type fast and would want to execute a command quickly.
Hence, doing a command using its alias will ensure he/she can do a certain command quicker.

**Minor feature** : Enhanced Find Command

* Made Find Command be able to search for phone numbers and email addresses. +
* A user may want to find a Lead/Contact based on phone numbers and email addresses.

ZHU Leyan: +
**Major Feature** : Bulk Import of Leads

* Allows a salesperson to import a CSV file into the CRM Book +
* Allows a salesperson to sort all persons by name.


**Minor Feature** : Remark Command

* Allows a salesperson to add/remove/edit a remark of a person in the CRM Book +
* This allows them to record some special information of a customer.

Woody Lau: +
**Major Feature** : Lead and Contact Creation

* Breaks apart the Person class into Leads and Contacts +
* Each will have their own functions and fields +
* Conversion between Leads and Contacts will be supported.


**Minor Feature** : Account Creation

* Allows Contacts to belong to Accounts.

Liu Yiming: +
**Major Feature** : Change Theme

* Allows user to change color theme +
* This allows user to read the CRM Book easily under different settings


**Minor Feature** : Auto Completion of commands

* Allows user to key in commands more efficiently.

**Minor feature** : Color tags

*Each type of tag has a unique color +
*Allows easy identification of different tags


[appendix]
== User Stories

Priorities: High (must have) - `* * \*`, Medium (nice to have) - `* \*`, Low (unlikely to have) - `*`

[width="59%",cols="22%,<23%,<25%,<30%",options="header",]
|=======================================================================
|Priority |As a ... |I want to ... |So that I can...
|`* * *` |new salesperson |see usage instructions |refer to instructions when I forget how to use the App

|`* * *` |salesperson |add a new Lead|keep track of who I am selling to

|`* * *` |salesperson |add a new Account|keep track of my accounts

|`* * *` |salesperson |convert a Lead to a Contact|know who I have successfully sold to in the past

|`* * *` |salesperson |determine if a lead to be added is already a contact|not have redundant data in my CRM

|`* * *` |salesperson |identify duplicates|not have redundant data in my CRM

|`* * *` |salesperson |share posts to my LinkedIn feed|share more about my company's product

|`* * *` |salesperson |schedule appointments with Leads via Google Calendar|sell to them

|`* * *` |busy salesperson |autocomplete my commands|use CRM Book more efficiently

|`* * *` |new salesperson |bulk import leads|quickly populate my CRM-Book

|`* *` |salesperson |obtain list solely on either Leads or Contacts|identify who to promote an item to and who has bought an item from me

|`* *` |salesperson |view commute directions to appointment location|know how to get there quickly

|`* *` |salesperson |send emails from a standard email template|quickly cold-email for lead generation

|`* *` |busy salesperson |have different colors for my tags|identify the tags easily

|`* *` |salesperson |execute a command with as few types as possible|use my CRM Book quickly

|`* *` |health-conscious salesperson |change the color theme|prevent eye fatigue

|`* *` |salesperson |analyze a CSV file|know how much of that file is duplicated in my CRM

|`* *` |salesperson |export a CSV file of an account with related leads and contacts|handover an account to a colleague

|`* *` |new salesperson |bulk import leads|populate my CRM-Book

|`* *` |salesperson |find a lead or contact by name |locate details of persons without having to go through the entire list

|`* *` |salesperson |find an account by name |locate details of accounts without having to go through the entire list

|`* *` |salesperson |hide <<private-contact-detail,private contact details>> by default |minimize chance of someone else seeing them by accident

|`* *` |salesperson |see my calendar |schedule meetings without conflicting

|`* *` |salesperson |be reminded when a contract is expiring |contact my contact for renewal

|`* *` |salesperson |add a remark to a Lead or Contact|record detailed information about them

|`* *` |salesperson with many entries in the CRM|sort people by name|search for them easily

|`* *` |salesperson |schedule a meeting using Google Hangouts |meet my leads online more efficiently

|`*` |salesperson |see the type of marketing materials an account is interacting with |know what other materials to send to them

|=======================================================================

[appendix]
== Use Cases

(For all use cases below, the *System* is the `CRM Book` and the *Actor* is the `user`, unless specified otherwise)

[discrete]
=== Use case: Delete person

*MSS*

1.  User requests to list of all Leads and Contacts
2.  CRM Book shows a list of all Leads and Contacts
3.  User requests to delete a specific Lead/Contact in the list
4.  CRM Book deletes the person
+
Use case ends.

*Extensions*

[none]
* 2a. The list is empty.
+
Use case ends.

* 3a. The given index is invalid.
+
[none]
** 3a1. CRM Book shows an error message.
+
Use case resumes at step 2.


=== Use case: User requests to import a CSV file to CRM Book

*MSS*

1.  User enters command for importing file.
2.  CRM Book processes the corresponding CSV file and lists all persons including newly added ones.
3.  User requests to sort all persons by name.
4.  CRM sorts all persons and lists them.
+
Use case ends.

*Extensions*

[none]
* 1a. User enters an non-existent file.
+
[none]
** 1a1. CRM Book displays error message.
+
Use case ends.
+
* 1b. The file is not a CSV file.
+
[none]
** 1b1. CRM Book displays error message.
+
Use case ends.
+
* 3a. The CSV file is in wrong format.
+
[none]
** 3a1. CRM Book displays error message.
+
Use case ends.

// tag::displaylistusecase[]
=== Use case: User seeks Lead list or Contact list

*MSS*

1. User enters command for Lead list or Contact list.
2. CRM retrieves the Lead list or Contact list.
3. User sees the Lead list or Contact list.

*Extensions*

[none]
* 1a. User enters a keyword that is neither Lead nor Contact.

** 1a1. CRM Book displays an empty list.
+
Use case ends.
// end::displaylistusecase[]


// tag::addparentcompanytagusecase[]
=== Use case: User seeks to add a company to a Lead or Contact [Coming in v2.0]

*MSS*

1. User enters command to update the company of Lead or Contact.
2. CRM updates company of the Lead or Contact.
3. User sees the updated company of the Lead or Contact.

*Extensions*

[none]
* 1a. User enters command incorrectly.

** 1a1. CRM Book displays an error message.
+
Use case ends.

* 1a. The keyword  that user entered has a parent company.

** 1a1. CRM Book adds a tag named after the parent company to the Lead or Contact.
+
Use case ends.

* 1a. User enters a company (keyword) has no parent company.

** 1a1. CRM Book does not add any to the Lead or Contact.
+
Use case ends.
// end::addparentcompanytagusecase[]


// tag::findphonenumberandemailaddressusecase[]
=== Use case: User enters phone numbers and/or email addresses to find

*MSS*

1. User enters keywords (phone numbers and/or email addresses) for find command.
2. CRM searches for Leads and/or Contacts that match with the keywords.
3. User sees the Leads and/or Contacts that match with the keywords.

*Extensions*

[none]
* 1a. User enters find command incorrectly.

** 1a1. CRM Book displays error message.
+
Use case ends.

* 2a. CRM Book is unable to find Leads and/or Contacts that match with the keywords.

** 2a1. User sees an empty list.
+
Use case ends.
// end::findphonenumberandemailaddressusecase[]

=== Use case: User posts to LinkedIn

*MSS*

1. User enters command to login to LinkedIn
2. CRM book opens browser for LinkedIn login
3. User enters username and password
4. CRM book completes oAuth2 process and gets api key
5. User enters command to post to linkedIn
6. CRM book prompts user to enter a post
7. User enters post to share to LinkedIn
8. CRM book posts post to user's LinkedIn
+
Use case ends.

*Extensions*

[none]
* 1a. User is already logged in.
[none]
** 1a1. CRM book tells user that he is already logged in
+
Use case resumes at step 5.

[none]
* 3a. User enters invalid credentials.
[none]
** 3a1. CRM book tells user to reenter credentials
+
Use case resumes at step 4.

=== Use case: Auto-complete

*MSS*

1. User enters a letter.
2. CRM book shows a drop down textfield with all the commands containing the typed letter.
3. User selects the command he desires.
+
Use case ends.

*Extensions*

[none]
* 2a. No commands contain the typed letter.
+
Use case ends.

=== Use case: Convert a Lead to a Contact

*MSS*

1. User requests a list of Leads and Contacts
2. CRM Book shows the requested list
3. User finds and selects the Lead to convert
4. CRM Book determines if Lead can be converted and converts if possible
+
Use case ends.

*Extensions*

[none]
* 2a. List is empty.
+
Use case ends.

* 3a. User selected a Contact, not a Lead.
+
[none]
** 3a1. CRM Book displays an error message.
+
Use case resumes at step 2.

* 3a. The given index is invalid.
+
** 3a1. CRM Book displays an error message.
+
Use case resumes at step 2.

=== Use case: Color tag

*MSS*

1. User request to add a lead with a tag.
2. CRM book assign a color to the tag.
+
Use case ends.

=== Use case: Change theme

*MSS*

1.  User requests to change theme
2.  CRM Book changes the theme setting to display the chosen theme
+
Use case ends.

*Extensions*

* 2a. The input theme is same as current theme.
+
[none]
** 2a1. CRM Book shows an error message.
+
Use case ends.

* 2b. The input theme is invalid.
+
[none]
** 2b1. CRM Book shows an error message.
+
Use case ends.

[appendix]
== Non Functional Requirements

.  Should work on any <<mainstream-os,mainstream OS>> as long as it has Java `1.8.0_60` or higher installed.
.  Should be able to hold up to 1000 persons without a noticeable sluggishness in performance for typical usage.
.  A user with above average typing speed for regular English text (i.e. not code, not system admin commands) should be able to accomplish most of the tasks faster using commands than using the mouse.
.  Should process a query and respond within 3 seconds.
.  Should be compatible across Linux, Windows, and MacOS operating systems.

[appendix]
== Glossary

[[mainstream-os]] Mainstream OS::
Windows, Linux, Unix, OS-X

[[private-contact-detail]] Private contact detail::
A contact detail that is not meant to be shared with others

[appendix]
== Instructions for Manual Testing

Given below are instructions to test the app manually.

[NOTE]
These instructions only provide a starting point for testers to work on; testers are expected to do more _exploratory_ testing.

=== Launch and Shutdown

. Initial launch

.. Download the jar file and copy into an empty folder
.. Double-click the jar file +
   Expected: Shows the GUI with a set of sample contacts. The window size may not be optimum.

. Saving window preferences

.. Resize the window to an optimum size. Move the window to a different location. Close the window.
.. Re-launch the app by double-clicking the jar file. +
   Expected: The most recent window size and location is retained.


=== Deleting a Lead or Contact

. Deleting a Lead or Contact while all Leads and Contacts are listed

.. Prerequisites: List all Leads and Contacts using the `list` command. Multiple persons in the list.
.. Test case: `delete 1` +
   Expected: First Lead/Contact is deleted from the list. Details of the deleted Lead/Contact shown in the status message. Timestamp in the status bar is updated.
.. Test case: `delete 0` +
   Expected: No Lead/Contact is deleted. Error details shown in the status message. Status bar remains the same.
.. Other incorrect delete commands to try: `delete`, `delete x` (where x is larger than the list size) +
   Expected: Similar to previous.

// tag::testingfordisplaycommand[]
=== Displaying Lead or Contact list

. Finding Lead(s) or Contacts(s) based on phone numbers and email addresses.

.. Prerequisites: Nil.
.. Test case: `disp Lead`, `display Lead` +
   Expected: All Leads in the CRM Book. Timestamp in the status bar is updated.
.. Test case: `disp Contact`, `display Contact` +
   Expected: All Contacts in the CRM Book. Timestamp in the status bar is updated.
// end::testingfordisplaycommand[]


// tag::testingforduplicatedetection[]
=== Duplicate Detection

. Detecting a duplicate Lead or Contacts.

.. Prerequisites: There is at least 1 Lead or Contact.
.. Test case: `a n/John Tan p/99991234 e/johntan@gmail.com a/33, Eunos Street 7, #5-67`, `add n/John Tan p/99991234 e/johntan@gmail.com a/33, Eunos Street 7, #5-67` +
   Ensure the information entered has either a phone number or email address that is identical to any Lead or Contact in the CRM Book.
   Expected: Duplicate Lead/Contact message shown. Timestamp in the status bar is updated.
// end::testingforduplicatedetection[]

// tag::testingforexecutingaliascommands[]
=== Executing commands via alias

. Executing commands via its alias

.. Prerequisites: Read through the User Guide for commands that have aliases.
.. Test case: `disp Lead`, `display Lead` +
   Expected: All Leads in the CRM Book. Timestamp in the status bar is updated.
.. Test case: `l`, `list` +
   Expected: List all Leads and Contacts in the CRM Book. Timestamp in the status bar is updated.
// end::testingforexecutingaliascommands[]

// tag::testingforfindingphonenumberandemailaddresses[]
=== Finding Lead(s) and Contact(s) via Phone Numbers and Email Addresses

. Finding Lead(s) or Contacts(s) based on phone numbers and email addresses.

.. Prerequisites: Nil.
.. Test case: `f 99991234`, `find 99991234` +
   Expected: Lead/Contact with the phone number `99991234` is shown in the status message. Timestamp in the status bar is updated.
.. Test case: `f johntan@gmail.com`, `find johntan@gmail.com` +
   Expected: Lead/Contact with the email address `johntan@gmail.com` is shown in the status message. Timestamp in the status bar is updated.
// end::testingforfindingphonenumberandemailaddresses[]

=== Sorting all people

. Sorting all people in list by name alphabetically

.. Test case: `sort` +
   Expected: All people in list are sorted by name in alphabetical order.
.. Test case: `s` +
   Expected: All people in list are sorted by name in alphabetical order.

=== Adding/Editing/Removing a remark of a person

. Adding/Editing/Removing a remark of person in list

.. Test case: `remark 2 r/Likes to swim` +
   Expected: The remark "Likes to swim" is added to the second person in list.
.. Test case: `remark 2 r/Likes to read` +
   Expected: The remark of the second person in list is now changed to "Likes to read"
.. Test case: `rem 2 r/` +
   Expected: The remark of the second person in list is now removed.
.. Test case: `remark 0 r/aaa` +
   Expected: No person is added with remark. Error details show in the status message. Status bar remains the same.
.. Test case: `remark 1 Likes to swim` +
   Expected: No person is added with remark. Error details show in the status message. Status bar remains the same.
.. Test case: `remark r/Likes to swim` +
   Expected: Similar to previous.

=== Importing a CSV file

. Importing a list of Leads to the CRM Book

.. Prerequisites: We provide two sample csv files. Please download them and put them in the same folder as the jar file. If you choose to put them somewhere else, then you need to change the file path in the command accordingly.
.. Test case: `import ./sample1.csv` +
   Expected: The 200 Leads in the sample1.csv file are imported to the CRM Book.
.. Test case: `import ./sample2.csv` +
   Expected: Since the 16th person in this file has a wrong format of his phone, error details show in the status messages. Status bar remains the same.
.. Test case: `import ./` +
   Expected: It's an invalid file path. Error details "invalid file path" show in the status message. Status bar remains the same.
.. Test case: `import x` (where x is any valid file path but not in CSV)+
   Expected: Error details "not a csv file" show in the status message. Status bar remains the same.
.. Test case: `import` +
   Expected: Wrong command format. Error details show in the status message. Status bar remains the same.

=== Converting a Lead to a Contact

. Select a Lead to convert from the current list of people, and note their index number

.. If a Contact is chosen, an error will appear in the next step

. In the command bar, type `convert INDEX`
. See that the person is now a Contact
. Note that the fields Rating, and Website and Industry if they exist, disappear
. Note that the field Department appears
. Note that all other fields except the type remain the same

=== Editing the non-essential details

. Select a Lead or Contact from the current list of people, and note their index number. If Lead, read the `a.` sections. If Contact, read the `b.` sections.
. In the command bar, type `editdetails INDEX ...` or `adddetails INDEX ...`, followed by type-specific data +
At least one of the fields must be specified, or an error is given

.. If a Lead, the fields are `c/COMPANY`, `i/INDUSTRY`, `r/RATING`, `t/TITLE`, and `w/WEBSITE`
Company, industry and website are strings, and company must be alphanumeric +
Rating is an integer from 1 to 5, and numbers that do not fall within this range will throw an error +
Title is the honorific of the person, such as `Mr.`, `Mrs.`, `Dr.`, etc. +
Note, company cannot be deleted, only changed, once it is provided
.. If a Contact, the fields are `c/COMPANY`, `d/DEPARTMENT`, and `t/TITLE`
Company and department are strings, and company must be alphanumeric +
Title is the honorific of the person, such as `Mr.`, `Mrs.`, `Dr.`, etc. +
Note, company cannot be deleted, only changed, once it is provided

. See that the relevant changes are made

.. The rating will change to the provided number +
Website and industry will appear if provided

=== Adding an Account to a Contact

. Select a Contact from the current list of people, and note their index number

.. If a Lead is chosen, an error will appear in the next step

. In the command bar, type `account INDEX an/COMPANY`
. Note that the Company field has changed to reflect the new company

=== Logging in to LinkedIn

. In the command box, type linkedin_login

.. A browser window will appear. Enter your LinkedIn username and password, and accept the permissions requested

.. The browser window should close and say 'Successfully logged in to LinkedIn'

=== Sharing a Post to LinkedIn

. In the command box, type linkedin_share [content] where [content] is what you want to share on your LinkedIn profile

.. If you are already logged in to LinkedIn and did not revoke the app's permissions, CRM Book will say 'Post shared to your linkedIn account'

.. To check if the post is there, go to your LinkedIn account, click on your name at the top right corner, click Posts & Activity. If the post is not there yet, wait awhile and refresh, sometimes it takes a while before the post appears in the feed.

=== Setting your office location

. In the command box, type set_office_address a/[address] where address is a valid address

.. CRM book will say 'Office address set!'

=== Getting directions to a client's location

. In the command box, type select [index] where index is the index of a currently unselected person card

.. For example, select 3

.. If you have already set your office location, instead of doing a Google search of the person, the CRM Book will instead show you directions to your client's office, powered by Google Maps.

.. If Google Maps does not recognize the address, you may have to manually change the address in the Google Maps prompt

=== Change color theme of CRM Book

. In the command box, type changetheme [theme] where theme can be one of the three themes available, namely light, dark, blue.

.. For example, changetheme light

.. If the current theme is not light, theme will be changed to light with a success message.

.. If the current theme is light, CRM Book will give a message to notify the user that the current theme is light.
