MT#6497 API cfmappings GET

ipeshinskaya/InvoiceTemplate5
Gerhard Jungwirth 12 years ago
parent c1307b1cbe
commit a11b53aa3e

@ -0,0 +1,140 @@
package NGCP::Panel::Controller::API::CFMappings;
use Sipwise::Base;
use namespace::sweep;
use boolean qw(true);
use Data::HAL qw();
use Data::HAL::Link qw();
use HTTP::Headers qw();
use HTTP::Status qw(:constants);
use MooseX::ClassAttribute qw(class_has);
use NGCP::Panel::Utils::DateTime;
BEGIN { extends 'Catalyst::Controller::ActionRole'; }
require Catalyst::ActionRole::ACL;
require Catalyst::ActionRole::CheckTrailingSlash;
require Catalyst::ActionRole::HTTPMethods;
require Catalyst::ActionRole::RequireSSL;
class_has 'api_description' => (
is => 'ro',
isa => 'Str',
default =>
'Specifies callforward mappings of a subscriber, where multiple mappings can be specified per type (cfu, cfb, cft cfna) ' .
'One mapping consists of destinationset name (see <a href="#cfdestinationsets">CFDestinationSets</a>) and a timeset name ' .
'(see <a href="#cftimesets">CFTimeSets</a>).',
);
class_has 'query_params' => (
is => 'ro',
isa => 'ArrayRef',
default => sub {[
]},
);
with 'NGCP::Panel::Role::API::CFMappings';
class_has('resource_name', is => 'ro', default => 'cfmappings');
class_has('dispatch_path', is => 'ro', default => '/api/cfmappings/');
class_has('relation', is => 'ro', default => 'http://purl.org/sipwise/ngcp-api/#rel-cfmappings');
__PACKAGE__->config(
action => {
map { $_ => {
ACLDetachTo => '/api/root/invalid_user',
AllowedRole => [qw/admin reseller/],
Args => 0,
Does => [qw(ACL CheckTrailingSlash RequireSSL)],
Method => $_,
Path => __PACKAGE__->dispatch_path,
} } @{ __PACKAGE__->allowed_methods },
},
action_roles => [qw(HTTPMethods)],
);
sub auto :Private {
my ($self, $c) = @_;
$self->set_body($c);
$self->log_request($c);
return 1;
}
sub GET :Allow {
my ($self, $c) = @_;
my $page = $c->request->params->{page} // 1;
my $rows = $c->request->params->{rows} // 10;
{
my $items = $self->item_rs($c); # items is actually a voip_subscribers
my $total_count = int($items->count);
$items = $items->search(undef, {
page => $page,
rows => $rows,
});
my (@embedded, @links);
for my $subs ($items->search({}, {order_by => {-asc => 'me.id'}})->all) {
push @embedded, $self->hal_from_item($c, $subs, "cfmappings");
push @links, Data::HAL::Link->new(
relation => 'ngcp:'.$self->resource_name,
href => sprintf('%s%d', $self->dispatch_path, $subs->id),
);
}
push @links,
Data::HAL::Link->new(
relation => 'curies',
href => 'http://purl.org/sipwise/ngcp-api/#rel-{rel}',
name => 'ngcp',
templated => true,
),
Data::HAL::Link->new(relation => 'profile', href => 'http://purl.org/sipwise/ngcp-api/'),
Data::HAL::Link->new(relation => 'self', href => sprintf('%s?page=%s&rows=%s', $self->dispatch_path, $page, $rows));
if(($total_count / $rows) > $page ) {
push @links, Data::HAL::Link->new(relation => 'next', href => sprintf('%s?page=%d&rows=%d', $self->dispatch_path, $page + 1, $rows));
}
if($page > 1) {
push @links, Data::HAL::Link->new(relation => 'prev', href => sprintf('%s?page=%d&rows=%d', $self->dispatch_path, $page - 1, $rows));
}
my $hal = Data::HAL->new(
embedded => [@embedded],
links => [@links],
);
$hal->resource({
total_count => $total_count,
});
my $response = HTTP::Response->new(HTTP_OK, undef,
HTTP::Headers->new($hal->http_headers(skip_links => 1)), $hal->as_json);
$c->response->headers($response->headers);
$c->response->body($response->content);
return;
}
return;
}
sub HEAD :Allow {
my ($self, $c) = @_;
$c->forward(qw(GET));
$c->response->body(q());
return;
}
sub OPTIONS :Allow {
my ($self, $c) = @_;
my $allowed_methods = $self->allowed_methods;
$c->response->headers(HTTP::Headers->new(
Allow => $allowed_methods->join(', '),
Accept_Post => 'application/hal+json; profile=http://purl.org/sipwise/ngcp-api/#rel-'.$self->resource_name,
));
$c->response->content_type('application/json');
$c->response->body(JSON::to_json({ methods => $allowed_methods })."\n");
return;
}
sub end : Private {
my ($self, $c) = @_;
$self->log_response($c);
return 1;
}
# vim: set tabstop=4 expandtab:

@ -0,0 +1,200 @@
package NGCP::Panel::Controller::API::CFMappingsItem;
use Sipwise::Base;
use namespace::sweep;
use boolean qw(true);
use Data::HAL qw();
use Data::HAL::Link qw();
use HTTP::Headers qw();
use HTTP::Status qw(:constants);
use MooseX::ClassAttribute qw(class_has);
use NGCP::Panel::Utils::ValidateJSON qw();
use NGCP::Panel::Utils::DateTime;
use Path::Tiny qw(path);
use Safe::Isa qw($_isa);
BEGIN { extends 'Catalyst::Controller::ActionRole'; }
require Catalyst::ActionRole::ACL;
require Catalyst::ActionRole::HTTPMethods;
require Catalyst::ActionRole::RequireSSL;
with 'NGCP::Panel::Role::API::CFMappings';
class_has('resource_name', is => 'ro', default => 'cfmappings');
class_has('dispatch_path', is => 'ro', default => '/api/cfmappings/');
class_has('relation', is => 'ro', default => 'http://purl.org/sipwise/ngcp-api/#rel-cfmappings');
__PACKAGE__->config(
action => {
map { $_ => {
ACLDetachTo => '/api/root/invalid_user',
AllowedRole => [qw/admin reseller/],
Args => 1,
Does => [qw(ACL RequireSSL)],
Method => $_,
Path => __PACKAGE__->dispatch_path,
} } @{ __PACKAGE__->allowed_methods },
},
action_roles => [qw(HTTPMethods)],
);
sub auto :Private {
my ($self, $c) = @_;
$self->set_body($c);
$self->log_request($c);
return 1;
}
sub GET :Allow {
my ($self, $c, $id) = @_;
{
last unless $self->valid_id($c, $id);
my $dset = $self->item_by_id($c, $id);
last unless $self->resource_exists($c, dset => $dset);
my $hal = $self->hal_from_item($c, $dset, "cfdestinationsets");
my $response = HTTP::Response->new(HTTP_OK, undef, HTTP::Headers->new(
(map { # XXX Data::HAL must be able to generate links with multiple relations
s|rel="(http://purl.org/sipwise/ngcp-api/#rel-resellers)"|rel="item $1"|r
=~ s/rel=self/rel="item self"/r;
} $hal->http_headers),
), $hal->as_json);
$c->response->headers($response->headers);
$c->response->body($response->content);
return;
}
return;
}
sub HEAD :Allow {
my ($self, $c, $id) = @_;
$c->forward(qw(GET));
$c->response->body(q());
return;
}
sub OPTIONS :Allow {
my ($self, $c, $id) = @_;
my $allowed_methods = $self->allowed_methods;
$c->response->headers(HTTP::Headers->new(
Allow => $allowed_methods->join(', '),
Accept_Patch => 'application/json-patch+json',
));
$c->response->content_type('application/json');
$c->response->body(JSON::to_json({ methods => $allowed_methods })."\n");
return;
}
sub PATCH :Allow {
my ($self, $c, $id) = @_;
my $guard = $c->model('DB')->txn_scope_guard;
{
my $preference = $self->require_preference($c);
last unless $preference;
my $json = $self->get_valid_patch_data(
c => $c,
id => $id,
media_type => 'application/json-patch+json',
ops => [qw/add replace remove copy/],
);
last unless $json;
my $dset = $self->item_by_id($c, $id);
last unless $self->resource_exists($c, destinationset => $dset);
my $old_resource = $self->hal_from_item($c, $dset, "destinationsets")->resource;
my $resource = $self->apply_patch($c, $old_resource, $json);
last unless $resource;
my $form = $self->get_form($c);
$dset = $self->update_item($c, $dset, $old_resource, $resource, $form);
last unless $dset;
$guard->commit;
if ('minimal' eq $preference) {
$c->response->status(HTTP_NO_CONTENT);
$c->response->header(Preference_Applied => 'return=minimal');
$c->response->body(q());
} else {
my $hal = $self->hal_from_item($c, $dset, "destinationsets");
my $response = HTTP::Response->new(HTTP_OK, undef, HTTP::Headers->new(
$hal->http_headers,
), $hal->as_json);
$c->response->headers($response->headers);
$c->response->header(Preference_Applied => 'return=representation');
$c->response->body($response->content);
}
}
return;
}
sub PUT :Allow {
my ($self, $c, $id) = @_;
my $guard = $c->model('DB')->txn_scope_guard;
{
my $preference = $self->require_preference($c);
last unless $preference;
my $dset = $self->item_by_id($c, $id);
last unless $self->resource_exists($c, destinationset => $dset);
my $resource = $self->get_valid_put_data(
c => $c,
id => $id,
media_type => 'application/json',
);
last unless $resource;
my $old_resource = { $dset->get_inflated_columns };
my $form = $self->get_form($c);
$dset = $self->update_item($c, $dset, $old_resource, $resource, $form);
last unless $dset;
$guard->commit;
if ('minimal' eq $preference) {
$c->response->status(HTTP_NO_CONTENT);
$c->response->header(Preference_Applied => 'return=minimal');
$c->response->body(q());
} else {
my $hal = $self->hal_from_item($c, $dset, "destinationsets");
my $response = HTTP::Response->new(HTTP_OK, undef, HTTP::Headers->new(
$hal->http_headers,
), $hal->as_json);
$c->response->headers($response->headers);
$c->response->header(Preference_Applied => 'return=representation');
$c->response->body($response->content);
}
}
return;
}
sub DELETE :Allow {
my ($self, $c, $id) = @_;
my $guard = $c->model('DB')->txn_scope_guard;
{
my $rule = $self->item_by_id($c, $id, "rules");
last unless $self->resource_exists($c, rule => $rule);
try {
$rule->delete;
} catch($e) {
$c->log->error("Failed to delete rewriterule with id '$id': $e");
$self->error($c, HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error");
last;
}
$guard->commit;
$c->response->status(HTTP_NO_CONTENT);
$c->response->body(q());
}
return;
}
sub end : Private {
my ($self, $c) = @_;
$self->log_response($c);
return 1;
}
# vim: set tabstop=4 expandtab:

@ -0,0 +1,122 @@
package NGCP::Panel::Form::CFMappingsAPI;
use HTML::FormHandler::Moose;
use HTML::FormHandler::Widget::Block::Bootstrap;
use Moose::Util::TypeConstraints;
extends 'HTML::FormHandler';
has '+widget_wrapper' => (default => 'Bootstrap');
sub build_render_list {[qw/fields actions/]}
sub build_form_element_class {[qw(form-horizontal)]}
has_field 'id' => (
type => 'Hidden',
noupdate => 1,
);
has_field 'cfu' => (
type => 'Repeatable',
do_wrapper => 1,
do_label => 0,
required => 0,
element_attr => {
rel => ['tooltip'],
title => ['Call Forward Unconditional']
},
);
has_field 'cfb' => (
type => 'Repeatable',
do_wrapper => 1,
do_label => 0,
required => 0,
element_attr => {
rel => ['tooltip'],
title => ['Call Forward Busy']
},
);
has_field 'cft' => (
type => 'Repeatable',
do_wrapper => 1,
do_label => 0,
required => 0,
element_attr => {
rel => ['tooltip'],
title => ['Call Forward Timeout']
},
);
has_field 'cfna' => (
type => 'Repeatable',
do_wrapper => 1,
do_label => 0,
required => 0,
element_attr => {
rel => ['tooltip'],
title => ['Call Forward Unavailable']
},
);
has_field 'cfu.destinationset' => (
type => 'Text',
do_wrapper => 1,
do_label => 0,
);
has_field 'cfu.timeset' => (
type => 'Text',
do_wrapper => 1,
do_label => 0,
);
has_field 'cfb.destinationset' => (
type => 'Text',
do_wrapper => 1,
do_label => 0,
);
has_field 'cfb.timeset' => (
type => 'Text',
do_wrapper => 1,
do_label => 0,
);
has_field 'cft.destinationset' => (
type => 'Text',
do_wrapper => 1,
do_label => 0,
);
has_field 'cft.timeset' => (
type => 'Text',
do_wrapper => 1,
do_label => 0,
);
has_field 'cfna.destinationset' => (
type => 'Text',
do_wrapper => 1,
do_label => 0,
);
has_field 'cfna.timeset' => (
type => 'Text',
do_wrapper => 1,
do_label => 0,
);
has_field 'cft.ringtimeout' => (
type => 'PosInteger',
do_wrapper => 1,
do_label => 0,
);
has_block 'fields' => (
tag => 'div',
class => [qw(modal-body)],
render_list => [qw(cfu cfb cft cfna)],
);
1;
# vim: set tabstop=4 expandtab:

@ -0,0 +1,163 @@
package NGCP::Panel::Role::API::CFMappings;
use Moose::Role;
use Sipwise::Base;
with 'NGCP::Panel::Role::API' => {
-alias =>{ item_rs => '_item_rs', },
-excludes => [ 'item_rs' ],
};
use boolean qw(true);
use TryCatch;
use Data::HAL qw();
use Data::HAL::Link qw();
use HTTP::Status qw(:constants);
use JSON::Types;
use NGCP::Panel::Utils::Subscriber;
use NGCP::Panel::Form::CFMappingsAPI;
sub get_form {
my ($self, $c) = @_;
return NGCP::Panel::Form::CFMappingsAPI->new;
}
sub hal_from_item {
my ($self, $c, $item, $type) = @_;
my $form;
my $resource = { subscriber_id => $item->id, cfu => [], cfb => [], cfna => [], cft => [], };
my $b_subs_id = $item->id;
my $p_subs_id = $item->provisioning_voip_subscriber->id;
for my $mapping ($item->provisioning_voip_subscriber->voip_cf_mappings->all) {
my $dset = $mapping->destination_set ? $mapping->destination_set->name : undef;
my $tset = $mapping->time_set ? $mapping->time_set->name : undef;
push $resource->{$mapping->type}, {
destinationset => $dset,
timeset => $tset,
};
}
my $hal = Data::HAL->new(
links => [
Data::HAL::Link->new(
relation => 'curies',
href => 'http://purl.org/sipwise/ngcp-api/#rel-{rel}',
name => 'ngcp',
templated => true,
),
Data::HAL::Link->new(relation => 'collection', href => sprintf("%s", $self->dispatch_path)),
Data::HAL::Link->new(relation => 'profile', href => 'http://purl.org/sipwise/ngcp-api/'),
Data::HAL::Link->new(relation => 'self', href => sprintf("%s%d", $self->dispatch_path, $item->id)),
Data::HAL::Link->new(relation => "ngcp:$type", href => sprintf("/api/%s/%d", $type, $item->id)),
Data::HAL::Link->new(relation => "ngcp:subscribers", href => sprintf("/api/subscribers/%d", $b_subs_id)),
],
relation => 'ngcp:'.$self->resource_name,
);
$form //= $self->get_form($c);
return unless $self->validate_form(
c => $c,
form => $form,
resource => $resource,
run => 0,
);
$hal->resource($resource);
return $hal;
}
sub item_rs {
my ($self, $c, $type) = @_;
my $item_rs;
$item_rs = $c->model('DB')->resultset('voip_subscribers')
->search(
{ status => { '!=' => 'terminated' } },
{ prefetch => 'provisioning_voip_subscriber',}
);
if($c->user->roles eq "reseller") {
$item_rs = $item_rs->search({
'contact.reseller_id' => $c->user->reseller_id,
}, {
join => { 'contract' => 'contact' },
});
}
return $item_rs;
}
sub item_by_id {
my ($self, $c, $id) = @_;
my $item_rs = $self->item_rs($c);
return $item_rs->find($id);
}
sub update_item {
my ($self, $c, $item, $old_resource, $resource, $form) = @_;
delete $resource->{id};
my $schema = $c->model('DB');
return unless $self->validate_form(
c => $c,
form => $form,
resource => $resource,
);
if (! exists $resource->{destinations} ) {
$resource->{destinations} = [];
}
if (ref $resource->{destinations} ne "ARRAY") {
$self->error($c, HTTP_UNPROCESSABLE_ENTITY, "Invalid field 'destinations'. Must be an array.");
return;
}
for my $d (@{ $resource->{destinations} }) {
if (exists $d->{timeout} && ! $d->{timeout}->is_integer) {
$c->log->error("Invalid field 'timeout'.");
$self->error($c, HTTP_UNPROCESSABLE_ENTITY, "Invalid field 'timeout'.");
return;
}
}
my $subscriber = $schema->resultset('provisioning_voip_subscribers')->find($resource->{subscriber_id});
unless ($subscriber) {
$self->error($c, HTTP_UNPROCESSABLE_ENTITY, "Invalid 'subscriber_id'.");
return;
}
try {
my $primary_nr_rs = $subscriber->voip_subscriber->primary_number;
my $number;
if ($primary_nr_rs) {
$number = $primary_nr_rs->cc . ($primary_nr_rs->ac //'') . $primary_nr_rs->sn;
} else {
$number = ''
}
my $domain = $subscriber->domain->domain // '';
$item->update({
name => $resource->{name},
subscriber_id => $resource->{subscriber_id},
})->discard_changes;
$item->voip_cf_destinations->delete;
for my $d ( @{$resource->{destinations}} ) {
delete $d->{destination_set_id};
$d->{destination} = NGCP::Panel::Utils::Subscriber::field_to_destination(
destination => $d->{destination},
number => $number,
domain => $domain,
uri => $d->{destination},
);
$item->create_related("voip_cf_destinations", $d);
}
} catch($e) {
$c->log->error("failed to create cfdestinationset: $e");
$self->error($c, HTTP_INTERNAL_SERVER_ERROR, "Failed to create cfdestinationset.");
return;
};
return $item;
}
1;
# vim: set tabstop=4 expandtab:

@ -65,6 +65,7 @@ $ua->ssl_opts(
callforwards => 1,
cfdestinationsets => 1,
cftimesets => 1,
cfmappings => 1,
};
foreach my $link(@links) {
my $rex = qr/^<\/api\/[a-z]+\/>; rel=\"collection http:\/\/purl\.org\/sipwise\/ngcp-api\/#rel-([a-z]+s)\"$/;

Loading…
Cancel
Save