forked from PhillipTaylor/Wardrobe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.pm
81 lines (61 loc) · 1.83 KB
/
Main.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package Wardrobe::Model::Main;
use base qw/DBIx::Class::Schema/;
use Text::CSV::Encoded;
__PACKAGE__->load_namespaces;
# creat_from_csv_file (str filename, bool header_record);
sub create_from_csv_file {
my ($self, $csv_filename, $header_record) = @_;
my $parser = Text::CSV::Encoded->new({
encoding_in => "utf8",
encoding_out => "utf8",
escape_char => '"',
sep_char => ',',
allow_whitespace => 1
});
Wardrobe->log->info("loading in new data from $csv_filename");
open my $fh, "<", $csv_filename;
my $line_no = 0;
my $bad = 0;
my $dupes = 0;
foreach my $line (<$fh>) {
if (!$parser->parse($line)) {
Wardrobe->log->warn("Skipped line $line_no - broken");
$bad++;
} else {
if ($line_no == 0 && $header_record) {
$line_no++;
next;
} else {
(my $clothing_name, my $category_name) = $parser->fields();
my $added = create_clothing_and_category($clothing_name, $category_name);
if (!$added) {
$dupes++;
}
}
}
$line_no++;
}
close $fh;
return ($line_no, $bad, $dupes);
}
sub create_clothing_and_category {
my ($clothing_name, $category_name) = @_;
Wardrobe->log->debug("Parsed: Clothing Name: $clothing_name| Category Name: $category_name");
my $clothing_item = Wardrobe->get_schema()->resultset('Clothing')->search({
name => $clothing_name
})->single;
if ($clothing_item) {
Wardrobe->log->warn('Existing clothing item found. skipped');
return 0;
}
my $category = Wardrobe->get_schema()->resultset('Category')->find_or_create({
name => $category_name
}, { key => 'category_name' });
Wardrobe->log->info("creating new clothing: $clothing_name (category already exists: $category->in_storage)");
$clothing_item = Wardrobe->get_schema()->resultset('Clothing')->create({
name => $clothing_name,
category => $category
});
return 1;
}
1;