Skip to content
This repository has been archived by the owner on May 1, 2020. It is now read-only.

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
tobybatch committed May 20, 2019
0 parents commit 4e9dbf7
Show file tree
Hide file tree
Showing 9 changed files with 452 additions and 0 deletions.
229 changes: 229 additions & 0 deletions Command/NeontribeCvsImportCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
<?php
namespace KimaiPlugin\NeontribeCvsImportBundle\Command;

use App\Configuration\FormConfiguration;
use App\Entity\Customer;
use App\Entity\Project;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\ORM\NoResultException;
use KimaiPlugin\NeontribeCvsImportBundle\Repository\NeontribeCvsImportRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use App\Entity\Activity;
use App\Entity\Timesheet;

class NeontribeCvsImportCommand extends Command {

protected static $defaultName = 'neontribe:csv:import';

/**
*
* @var Registry
*/
protected $doctrine;

/**
*
* @var NeontribeCvsImportRepository
*/
protected $repository;

/**
*
* @var FormConfiguration
*/
protected $configuration;

/**
*
* @param RegistryInterface $registry
*/
public function __construct(RegistryInterface $registry, NeontribeCvsImportRepository $repository, FormConfiguration $configuration) {
$this->doctrine = $registry;
$this->repository = $repository;
$this->configuration = $configuration;

parent::__construct(self::$defaultName);
}

/**
*
* {@inheritdoc}
*/
protected function configure() {
$this->setName('kimai:csv:import')
->setDescription('Import from CSV')
->setHelp('Read timesheets from a CSV file and import records. Creates Customers, Projects and Activities as needed.')
->addArgument('file', InputArgument::REQUIRED, 'Relative path to the CSV file.')
->addOption('offset', null, InputArgument::OPTIONAL, 'Number of rows to skip before starting the import', 0)
->addOption('count', null, InputArgument::OPTIONAL, 'Number of rows to import', 99999)
->addOption('ignore-hashes', null, InputArgument::OPTIONAL, 'Ignore hash clashes and always create a new timesheet', 1);
}

/**
*
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output) {
$io = new SymfonyStyle($input, $output);

$filename = $input->getArgument('file');
$offset = $input->getOption('offset');
$count = $input->getOption('count');
$ignoreHashes = $input->getOption('count');

$file = new \SplFileObject($filename);
if ($offset > 0) {
$file->seek($offset);
}

$hashData = $this->repository->getHashData();
$hashes = array_keys($hashData);

for ($i = 0; $i < $count and $file->valid(); $i ++, $file->next()) {
$line = str_getcsv($file->current());
if (count($line) != 9) {
$io->error("Wrong count (" . count($line) . ") in line " . ($offset + $i) . ": " . $file->current());
continue;
}
$hash = md5($file->current());
if (! $ignoreHashes && in_array($hash, $hashes)) {
$io->comment("Duplicate timesheet, skipping line " . ($offset + $i) . ", ID " . $line[0]);
continue;
}

$this->importLine($line);
$hashData[$hash] = $line[0];
}

$this->doctrine->getManager()->flush();
$this->repository->saveHashData($hashData);
}

public function importLine($elements) {
$customerName = $elements[1];
$projectName = $elements[2];
$activityName = $elements[3];
$start = $elements[4];
$duration = $elements[5];
$description = $elements[6];
$userName = $elements[7];
$email = $elements[8];

$customer = $this->getCompany($customerName);
$project = $this->getProject($projectName, $customer);
$activity = $this->getActivity($activityName, $project);
$user = $this->getUser($userName, $email);

$begin = new \DateTime($start);
$end = new \DateTime($start);
$end->add(new \DateInterval('PT' . $duration . 'S'));

$timesheet = new Timesheet();
$timesheet->setBegin($begin)
->setEnd($end)
->setDuration($duration)
->setDescription($description)
->setProject($project)
->setActivity($activity)
->setUser($user);

$this->doctrine->getManager()->persist($timesheet);
}

public function getCompany($customerName): Customer {
$customer = $this->doctrine->getRepository(Customer::class)->findOneBy([
'name' => $customerName
]);

if ($customer) {
return $customer;
}

$_customer = new Customer();
$_customer->setName($customerName)
->setCountry($this->configuration->find('customer.country'))
->setCurrency($this->configuration->find('customer.currency'))
->setTimezone($this->configuration->find('customer.timezone'));

$entityManager = $this->doctrine->getManager();
$entityManager->persist($_customer);
$entityManager->flush();

return $_customer;
}

public function getProject($projectName, $customer): Project {
$project = $this->doctrine->getRepository(Project::class)->findOneBy([
'name' => $projectName
]);

if ($project) {
return $project;
}

$_project = new Project();
$_project->setName($projectName)->setCustomer($customer);

$entityManager = $this->doctrine->getManager();
$entityManager->persist($_project);
$entityManager->flush();

return $_project;
}

public function getActivity($activityName, $project): Activity {
$activity = $this->doctrine->getRepository(Activity::class)->findOneBy([
'name' => $activityName,
'project' => $project
]);

if ($activity) {
return $activity;
}

$_activity = new Activity();
$_activity->setName($activityName)->setProject($project);

$entityManager = $this->doctrine->getManager();
$entityManager->persist($_activity);
$entityManager->flush();

return $_activity;
}

public function getUser($userName, $userEmail) {
try {
$user = $this->doctrine->getRepository(User::class)->findOneBy([
'username' => $userName
]);

if ($user) {
return $user;
}
} catch (NoResultException $nre) {
// Fail silently. The above usersearch if the user doesn't exist.
// TODO: Fix this.
}

$_user = new User();
$_user->setUsername($userName)
->setEmail($userEmail)
->setPassword(md5(uniqid()))
->setEnabled(true)
->setRoles([
User::DEFAULT_ROLE
]);

$entityManager = $this->doctrine->getManager();
$entityManager->persist($_user);
$entityManager->flush();

return $_user;
}
}
19 changes: 19 additions & 0 deletions DependencyInjection/NeontribeCvsImportExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
namespace KimaiPlugin\NeontribeCvsImportBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class NeontribeCvsImportExtension extends Extension {

public function load(array $configs, ContainerBuilder $container) {
try {
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yaml');
} catch (\Exception $e) {
echo '[NeontribeCvsImport] invalid services config found: ' . $e->getMessage();
}
}
}
29 changes: 29 additions & 0 deletions Entity/NeontribeCvsImport.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php
namespace KimaiPlugin\NeontribeCvsImportBundle\Entity;

class NeontribeCvsImport {

private $hashes = [];

/**
*
* @return string
*/
public function getHashes(): array {
return $this->hashes;
}

/**
*
* @param string|null $customCss
* @return NeontribeCvsImport
*/
public function setHashes(string $hashes = null) {
if (null === $hashes) {
$hashes = '';
}

$this->hashes = $hashes;
return $this;
}
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Kevin Papst - https://www.kevinpapst.de

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
15 changes: 15 additions & 0 deletions NeontribeCvsImportBundle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

/*
* This file is part of the Kimai CustomCSSBundle.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace KimaiPlugin\NeontribeCvsImportBundle;

use App\Plugin\PluginInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class NeontribeCvsImportBundle extends Bundle implements PluginInterface {
}
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
## Kimai import plugin

This creates a console command that imports timesheets into Kimai.

It reads a CSV file and creates a timesheet for each line it finds. If the Customer, Project or Activity does not exist it will create one. The deafult password for a new user is scrambled (but not fully secured). Use the password reset to set that.

The fields in the CSV are:

* id, The UID for the row. This is used to log each row imported.
* customer name, The name of the customer.
* project name, The name of the project
* activity name, The name of the activity
* start, The sate of the activity in the format YYYY-MM-DD HH:MM:SS
* duration, In minutes
* description, The text description of the timesheet entry
* user name, The username of the logger
* email, The email of the logger

Newly created projects are assigned the customer specified by the line. Activities are assigned to the Project specified by the line.

### Getting the data

To get timesheets out of an existing kimai then use a version of this SQL:

select
t.id as id,
c.name as customer,
p.name as project,
a.name as activity,
t.start_time as date,
t.duration as duration,
t.description as title,
u.username as username,
u.email as email
from
kimai2_timesheet t
inner join kimai2_users u on t.user=u.id
inner join kimai2_activities a on t.activity_id=a.id
inner join kimai2_projects p on a.project_id=p.id
inner join kimai2_customers c on p.customer_id=c.id;

Loading

0 comments on commit 4e9dbf7

Please sign in to comment.