# Zipwire CLI (zw)

A command-line interface for the Zipwire journaling application. Track time, manage activities, and view your productivity data from the terminal.

## Think of it like Git for Work

Just like you use `git` to log your commits, you use `zw` to track your working day. Every entry goes into your private journal, which Zipwire then uses to auto-fill your timesheets – so they're never wrong! The system sends them for approval with a perfect invoice attached.

## What is Zipwire?

Zipwire Approve is a timesheet and contractor management system designed for the modern flexible workforce. It solves a fundamental problem: how do you accurately track time, get it approved, and get paid – without the errors and delays that plague traditional timesheet systems?

### The Core Concept

**Your Private Journal** → **Auto-filled Timesheets** → **Workflow Approval** → **Automatic Invoicing**

1. **Journal**: You keep a private, detailed record of what you worked on each day. This journal belongs to you and is only visible to you. Track time against activities (like "Company > Project > Task") with notes about what you did.

2. **Timesheets**: When it's time to bill, Zipwire automatically creates timesheets from your journal data. The system applies billing rules (rates, minimums, overtime) to fill out the timesheet correctly – eliminating the common mistakes that cause rejections and invoice rework.

3. **Workflows**: Timesheets flow through approval chains you set up. A manager approves, then it goes to processing. The workflow defines who sees what and when. If your boss is away, a deputy can step in because items go to team inboxes, not individuals. Workflows link activities to billing rates, payment methods, and client invoicing information. They're automatically created when you first submit a timesheet for an unlinked activity, or you can set them up in advance.

4. **Invoicing**: Once approved, Zipwire can automatically generate invoices. Freelancers get invoices to send to agencies, and agencies get invoices to send to clients. No more rekeying data and introducing errors.

### Why It's Different

- **Privacy-first**: Your journal is yours. Zipwire only uses it to fill timesheets – you control your data.
- **Error reduction**: By auto-filling from detailed journal data, timesheets are accurate from the start.
- **Multi-client support**: Work for multiple clients? Zipwire automatically routes the right time to the right timesheet for the right client.
- **WhatsApp integration**: Track time and approve timesheets via WhatsApp – no need to open an app.
- **No passwords**: Use social logins or Ethereum wallet authentication.

This CLI gives you command-line access to all of this functionality, making it easy to track time, manage activities, create timesheets, and handle workflows from your terminal.

## Installation

### From Source

```bash
git clone https://github.com/lukepuplett/zwcli.git
cd zwcli
go build -o zw ./cmd/zw
sudo mv zw /usr/local/bin/
```

### Using Go Install

```bash
go install github.com/lukepuplett/zwcli/cmd/zw@latest
```

### Using NPM (Recommended)

Install the CLI globally using NPM:

```bash
npm install -g @zipwire/zw
```

After installation, the `zw` command will be available in your PATH.

**Using npx (No Installation Required):**

You can also run the CLI without installing it using npx:

```bash
npx @zipwire/zw --help
npx @zipwire/zw activity list
```

The NPM distribution uses a multi-package architecture that automatically installs the correct platform-specific binary. See [NPM_DISTRIBUTION.md](docs/NPM_DISTRIBUTION.md) for architecture details, troubleshooting, and maintainer workflows.

## Quick Start

### Getting Started: Choose Your Path

**New to Zipwire? Sign up from the command line:**
```bash
zw auth signup --name "Your Name" --whatsapp "+1234567890"
```
You'll receive a WhatsApp message from Zipwire's onboarding bot. Follow the prompts to activate your account — all from your phone, no web browser needed. Once activated, you're ready to use the CLI immediately.

**Already have an account? Log in:**
```bash
zw auth login
```
This generates a magic link to your email. Alternatively, if you have an API token:
```bash
zw auth login --token your-api-token
```

### Start Tracking Time

Once authenticated, you're ready to use the CLI:

1. **List your activities** to see what's available:
   ```bash
   zw activity list
   ```

2. **Track your first time entry**:
   ```bash
   zw journal track "Fixed authentication bug" -d 45 --activity "Company > Project > Development"
   ```

### Complete Workflow

See [Complete Workflow Example](#complete-workflow-example) below for the full journey from signup to invoicing.

## Command Structure

The CLI follows the pattern: `zw <noun> <verb> [options]`

### Activity Commands ✅ (Fully Implemented)

Manage activities for time tracking. Activities use a hierarchical structure: `Company > Project > Activity`:

```bash
# List all activities
zw activity list

# Search for activities
zw activity search "meeting"
zw activity search "ABC Corp"

# Create new activities
zw activity create "Company > Project > New Feature"

# Show recently used activities
zw activity recent
zw activity recent --period 2w  # Last 2 weeks

# Rename/merge activities (consolidate duplicates)
zw activity rename --from "Old Dev" --from "Dev Work" --to "General > Development"
zw activity rename --from "abe_jnla_ac71x94j8smyi0fu" --to "ABC Corp > General > Development"
```

**Activity Types:**
- **Client Activities**: Require workflow linking before timesheets can be created (e.g., "Acme Corp > Project > Task")
- **Personal Activities**: Don't require workflows (e.g., "Personal > Learning > Research")
- **Assigned Activities**: Created by clients/assigners with restricted editing capabilities

**Activity-Workflow Relationship:**
- Activities must be linked to workflows for billing and approval
- Linking happens automatically when creating timesheets, or manually via workflow commands
- Unlinked activities will prompt for workflow selection during timesheet creation
- Activities can be unlinked from workflows if needed (workflows must have no linked activities before deletion)

### Configuration Commands ✅ (Fully Implemented)

Manage CLI settings:

```bash
# View current configuration
zw config show

# Set configuration values
zw config set no-color true
zw config set output-format structured
zw config set work-day-hours 7.5

# Authentication
zw auth login                    # Web-based authentication (opens browser)
zw auth login --token <token>    # Manual token entry
zw auth status                   # Check authentication status
zw auth logout                   # Clear stored token
zw auth set-token <token>        # Set token manually (fallback)
```

### Journal Commands ✅ (Fully Implemented)

Track and manage time entries:

```bash
# Track time ✅ (IMPLEMENTED)
zw journal track "Fixed auth bug" -d 45 --activity "Company > Project > Bug Fix"
zw journal track "Team meeting" -d 30 --activity-key "abe_jnla_ac71x94j8s"  # using activity key
zw journal track "Conference" -d 1d    # 8 hours (work day)
zw journal track "Deep work" -d 2.5h   # 2.5 hours
zw journal track "Project work" -d 2h30m  # 2 hours 30 minutes

# Track with dates
zw journal track "Catch up" -d 120 --date "Monday" --activity "Company > Project > Development"
zw journal track "Review" -d 60 --date "yesterday" --activity-key "abe_jnla_xyz123"
zw journal track "Planning" -d 90 --date "2024-05-26" --activity "Company > Planning > Sprint Planning"

# AI/LLM Analysis Examples
zw journal list --from "2024-06-01" --to "2024-08-31" --format structured  # Summer report data
zw journal list --activity "Learning" --group-by-week --format structured  # Learning progress
zw activity list --format structured  # Activity analysis

# Activity suggestions - if you don't specify an activity, you'll get helpful suggestions:
# ✗ Error tracking: No activity specified. Please choose from recent activities or create a new one.
# 
# Recent activities you can use:
#   Company > Project > Development [abe_jnla_xyz123] - 2 hours ago
#   Company > Marketing > Blog Writing [abe_jnla_abc456] - 1 day ago
#   Personal > Learning > Research [abe_jnla_def789] - 3 days ago
# 
# Usage: Use --activity "Display Name" or --activity-key "key"

# View entries ✅ (FULLY IMPLEMENTED)
zw journal list                        # recent entries (default)
zw journal list --count 20             # last 20 entries
zw journal list --today                # today's entries
zw journal list --week                 # current week
zw journal list --week 35              # week 35 of current year
zw journal list --week 2025-W35        # specific week (ISO format)
zw journal list --from 2025-08-01 --to 2025-08-31  # date range
zw journal list --group-by-week        # group entries by week
zw journal list --activity "Zipwire > Development"  # filter by activity

# Show specific entry ✅ (FULLY IMPLEMENTED)
zw journal show jnla_ac71x94j8s        # show specific entry by key

# Edit entries ✅ (FULLY IMPLEMENTED)
zw journal edit jnla_ac71x94j8s --duration 2h30m
zw journal edit --last --duration 90m --public-note "Updated description"

# Delete entries ✅ (FULLY IMPLEMENTED)
zw journal delete jnla_ac71x94j8s
zw journal delete --last               # delete most recent entry
```

### Workflow Commands ✅ (Fully Implemented)

Manage workflows for timesheet approval and processing. Workflows define the approval chain, billing rates, and payment methods for your activities:

```bash
# List available workflows
zw workflow list

# Create approval workflow
zw workflow create --approve-name "Jane Doe" --approve-email "jane.doe@client.com"

# Create two-step workflow (approval + processing)
zw workflow create --approve-name "Manager" --approve-email "manager@client.com" --process-name "Admin" --process-email "admin@agency.com"

# Create workflow with billing information
zw workflow create --approve-name "Client Manager" --approve-email "manager@client.com" \
  --hourly-rate 75 --currency USD \
  --company-name "Acme Corp" --contact-name "John Smith" \
  --company-address "123 Main St\nNew York, NY 10001"

# Link activity to workflow
zw workflow link --activity "Company > Project > Development" --workflow-key "wf_123"
zw workflow link --activity-key "abe_jnla_ac71x94j8smyi0fu" --workflow-key "wf_456"

# Remove workflow link
zw workflow unlink --activity "Company > Project > Development"
zw workflow unlink --activity-key "abe_jnla_ac71x94j8smyi0fu"

# Delete workflow (only if no activities are linked)
zw workflow delete wf_abc123def456
```

**How Workflows Work:**
- **Automatic Creation**: When you create a timesheet for an activity without a workflow, the system prompts you to create one or select an existing workflow
- **Activity Linking**: Activities must be linked to workflows before timesheets can be sent. Personal activities (Company = "Personal") don't require workflows
- **Billing Integration**: Workflows store hourly rates, currency, and client invoicing information (company name, address, tax codes)
- **Payment Methods**: Link payment methods to workflows for automatic invoicing
- **Multi-Step Approval**: Support for simple approval or two-step processes (approval → processing)
- **Usage Tracking**: Workflows track how many times they've been used and when last used

For detailed workflow management documentation, see [TZ_WORKFLOW_MANAGEMENT.md](docs/TZ_WORKFLOW_MANAGEMENT.md).

### Timesheet Commands ✅ (Fully Implemented)

Create and manage timesheets from time entries. Timesheets automatically use the workflows linked to your activities:

```bash
# Create timesheets from unsheeted time entries
zw timesheet create --from "2024-01-01" --to "2024-01-31"
zw timesheet create --from "last Monday" --to "last Friday"
zw timesheet create --from "today" --to "yesterday"

# List timesheets with filtering
zw timesheet list                        # recent timesheets (default)
zw timesheet list --count 10             # last 10 timesheets
zw timesheet list --status draft         # only draft timesheets
zw timesheet list --status sent          # only sent timesheets
zw timesheet list --status done          # only completed timesheets
zw timesheet list --from 2024-01-01 --to 2024-03-31  # date range
zw timesheet list --page 2 --page-size 5  # pagination

# Show specific timesheet details
zw timesheet show ts_123456              # show timesheet by ID

**Detailed Timesheet View Example:**
```bash
✓ Retrieved timesheet: "Zipwire Development - Week 1" [ID: ts_abc123]
   📝 Draft → Standard Approval → Waiting for approval
   2024-01-01 to 2024-01-07 (Week 1)

📅 Daily Breakdown:

   🎯 Monday, January 1, 2024 (3 entries)
      📋 Frontend bug fixes - Zipwire > Development > Bug Fixes (6h 30m) [abe_jnle_abc123]
      📋 API integration work - Zipwire > Development > Backend (1h 30m) [abe_jnle_def456]
      8h

   🎯 Tuesday, January 2, 2024 (3 entries)
      📋 Team standup meeting - Zipwire > General > Meetings (2h 30m) [abe_jnle_ghi789]
      📋 Code review session - Zipwire > Development > Code Review (4h 15m) [abe_jnle_jkl012]  
      📋 Documentation updates - Zipwire > General > Documentation (1h 15m) [abe_jnle_mno345]
      8h

   🎯 Wednesday, January 3, 2024 (0 entries)
      --

   38h 30m across 12 entries
```
```

**Timesheet Status Emojis:**
- 📝 **Draft** - Timesheet is being prepared (unsent)
- 📤 **Sent** - Timesheet has been sent for processing
- ✅ **Done** - Timesheet has been completed and processed
```

**Workflow Integration:**
- Timesheets automatically use the workflow linked to each activity
- If an activity has no workflow, you'll be prompted to create or select one during timesheet creation
- Workflows define the approval chain (who approves, who processes)
- Billing rates and payment methods from workflows are used for invoicing
- Timesheets flow through workflow steps: Send → Process (optional) → Approve

### Smart Features ✅

The journal track command includes intelligent parsing:

**Duration Formats:**
- `45` or `45m` → 45 minutes
- `2h` → 2 hours (120 minutes)
- `1.5h` → 1.5 hours (90 minutes)
- `1d` → 8 hours (480 minutes, configurable)
- `2h30m` → 2 hours 30 minutes (150 minutes)

**Date Formats:**
- `today` → current date
- `yesterday` → previous day
- `Monday` → most recent Monday
- `last Monday` → Monday from previous week
- `2024-05-26` → specific date
- `May 26` → current year

**Configuration:**
```bash
zw config set work-day-hours 7.5  # customize how many hours '1d' represents
```

**Week Numbers:**
The CLI uses ISO 8601 week numbering (YYYY-WWW format):
- Week 1 is the week containing January 4th
- Weeks start on Monday
- `2025-W35` = week 35 of 2025
- `35` = week 35 of current year
- `W35` = week 35 of current year

**List Command Examples:**
```bash
# Basic listing
zw journal list
zw journal list --count 20

# Time-based filtering
zw journal list --today
zw journal list --week 35
zw journal list --week 2025-W35

# Date range filtering
zw journal list --from "last Monday" --to "Friday"
zw journal list --from 2025-08-01 --to 2025-08-31

# Grouping and filtering
zw journal list --group-by-week
zw journal list --activity "Zipwire > Development" --group-by-week
```

## Output Formats

### Human-Friendly (Default)

```
✓ Created activity: ABC Corp > Development > Testing [act_abc123]

🔄 Consolidating activities...

✓ Merging 3 activities → "General > Development"
  • "Old Dev" (5 entries)
  • "Dev Work" (12 entries)
  • "Development" (8 entries)

25 journal entries updated, 2 duplicate activities removed
```

### Structured Format

Add `--format structured` to any command for machine-readable output:

**Success Response:**
```
STATUS: SUCCESS
ACTION: activity_create
ACTIVITY_KEY: act_abc123
DISPLAY_NAME: ABC Corp > Development > Testing
COMPANY: ABC Corp
PROJECT: Development
ACTIVITY: Testing
CREATED: 2024-08-25T15:30:00Z
```

**Error Response with Suggestions:**
```
STATUS: ERROR
ACTION: journal_track
ERROR: No activity specified. Please choose from recent activities or create a new one.
SUGGESTIONS_COUNT: 3
SUGGESTIONS:
- ACTIVITY_1_NAME: Company > Project > Development
  ACTIVITY_1_KEY: abe_jnla_xyz123
  ACTIVITY_1_LAST_USED: 2 hours ago
- ACTIVITY_2_NAME: Company > Marketing > Blog Writing
  ACTIVITY_2_KEY: abe_jnla_abc456
  ACTIVITY_2_LAST_USED: 1 day ago
USAGE: Use --activity "Display Name" or --activity-key "key"
```

## Configuration

The CLI stores configuration in `~/.config/zw/config.yaml`. Available settings:

- `api-base-url`: Base URL for the Zipwire API
- `api-token`: API authentication token
- `no-color`: Disable colored output (true/false)
- `output-format`: Default output format (human/structured)
- `work-day-hours`: Hours for '1d' duration (default: 8)

## Global Flags

- `--config`: Specify a custom config file path
- `--no-color`: Disable colored output
- `--format`: Output format (human or structured)

## Examples

### Complete Workflow Example

Here's a typical workflow from time tracking to invoicing:

```bash
# 1. Authenticate (opens browser automatically)
zw auth login

# 2. Create or find an activity
zw activity list
zw activity create "Acme Corp > Website Redesign > Frontend Development"

# 3. Set up workflow for billing (if not already created)
zw workflow create --approve-name "Project Manager" --approve-email "pm@acme.com" \
  --hourly-rate 85 --currency USD \
  --company-name "Acme Corporation" --contact-name "Jane Manager"

# 4. Link activity to workflow
zw workflow link --activity "Acme Corp > Website Redesign > Frontend Development" \
  --workflow-key "wf_abc123"

# 5. Track your time
zw journal track "Implemented responsive navigation" -d 2h30m \
  --activity "Acme Corp > Website Redesign > Frontend Development"
zw journal track "Code review and fixes" -d 1h15m \
  --activity "Acme Corp > Website Redesign > Frontend Development"

# 6. Review your entries
zw journal list --today
zw journal list --week

# 7. Create timesheet from journal entries
zw timesheet create --from "last Monday" --to "last Friday"

# 8. View timesheet status
zw timesheet list --status sent
zw timesheet show ts_abc123
```

### Quick Start Example

```bash
# Authenticate (opens browser automatically)
zw auth login

# Track time (workflow will be created automatically if needed)
zw journal track "Fixed auth bug" -d 45 --activity "Company > Development"
zw journal list --today
```

## Development Status

This CLI currently has **comprehensive real API integration for activities, configuration, and journal tracking**, with advanced activity suggestions and intelligent error handling.

### ✅ What's Working Now:
- **Activity management** (list, search, create, recent, rename/merge)
- **Authentication & OAuth** - Web-based login, OAuth provider connections (connect, list, disconnect), API token management
- **Configuration management** - Settings, authentication, output format preferences
- **Journal time tracking** - Track time with intelligent activity suggestions, edit entries, view history with filtering
- **Smart activity selection** - Get helpful suggestions when no activity is specified
- **Workflow management** - Create workflows, link activities, manage approval processes, set up billing and payment methods
- **Timesheet management** - Create, list, and view timesheets from journal entries with status tracking (draft, sent, done)
- **Workflow invoicing** - PDF invoicing (enable/disable) and provider-based invoicing (set, unset, disable) with available options
- **Rate configuration** - Set hourly rates with currency, unit types, and billing constraints per workflow
- **Timesheet send status** - Handle multiple send statuses (sent, partial_failure, failure) with operation messages
- **Feedback submission** - Submit feedback directly from CLI
- **API error handling** - Deprecation warnings and structured error responses with suggestions
- **Real API integration** with production data
- **Advanced activity cleanup** - Consolidation and merge features
- **Dual input support** - Both activity keys and display names
- **Comprehensive error handling** with structured suggestions and actionable next steps
- **Consistent formatting** across human and structured output modes
- **LLM/AI-friendly data access** - Structured output for automated analysis and reporting

### 🤖 LLM/AI Integration

The CLI is designed to work seamlessly with AI assistants and LLMs for automated reporting and analysis. Instead of building dedicated "stats" features, the CLI provides raw data that AI can analyze:

**Example: Generate a Summer Work Report**
```bash
# Get all summer entries in structured format
zw journal list --from "2024-06-01" --to "2024-08-31" --format structured

# Get activity information
zw activity list --format structured

# Get configuration for context
zw config show --format structured
```

**AI Analysis Workflow:**
1. **Data Collection**: Use structured output to get complete datasets
2. **Pattern Analysis**: AI analyzes time patterns, project distribution, learning progress
3. **Report Generation**: AI creates comprehensive reports with insights and recommendations
4. **Custom Queries**: AI can run specific queries for targeted analysis

**Benefits of This Approach:**
- **No Feature Bloat**: CLI stays focused on data access, not analysis
- **Flexible Reporting**: AI can generate any type of report or analysis
- **Real-time Insights**: Always uses current data from the API
- **Custom Analysis**: AI can perform complex analysis not possible with fixed features

### ✅ Recently Added (Last 2 Months):
- **OAuth Integration** (Feb 10) - Connect to OAuth providers, manage connections with `zw oauth list`, `zw oauth connect`, `zw oauth disconnect` with full error handling
- **Workflow Invoicing** - PDF invoicing (enable/disable/show) and provider-based invoicing (set/unset/disable/show) with available projects, contacts, and service products
- **Rate Configuration** - Full support for hourly rates, currency, unit types, and billing constraints with `zw workflow rate set` and `zw workflow rate show`
- **Timesheet Send Status Improvements** - Proper handling of sent, partial_failure, and failure statuses with operation messages
- **Feedback Submit Command** - Submit feedback directly from the CLI with `zw feedback submit`
- **API Deprecation Warnings** - System for communicating deprecated API features to users
- **Hierarchical Output Formatting** - Visual hierarchy with symbols (↓ ▦ ▲ •) and color support for better readability

## Documentation

Additional technical documentation is available in the `docs/` directory:

- **[FORMATTING_FUNCTIONS_GUIDE.md](docs/FORMATTING_FUNCTIONS_GUIDE.md)** - Comprehensive reference for all formatting functions and patterns used throughout the CLI
- **[PLAN_OUTPUT_SAMPLES.md](docs/PLAN_OUTPUT_SAMPLES.md)** - Output samples and test cases for hierout integration
- **[PROMPTS.md](docs/PROMPTS.md)** - Reflection and documentation prompts for development workflow
- **[TZ_WORKFLOW_MANAGEMENT.md](docs/TZ_WORKFLOW_MANAGEMENT.md)** - Comprehensive guide to the workflow management system, including activity linking, billing integration, payment methods, and workflow lifecycle

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run tests: `go test ./...`
5. Submit a pull request

## License

MIT License - see LICENSE file for details.